Android 6.0以上动态获取权限

时间:2022-04-04 15:31:03

首先在清单文件中注册

然后在MainActivity.java中将权限封装到一个String数组中

 static final String[] PERMISSION = new String[]{
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.RECEIVE_BOOT_COMPLETED
};

然后在onCreate()方法中加入一下代码:

 if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
//Android 6.0申请权限
ActivityCompat.requestPermissions(this, PERMISSION, 1);
} else {
Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();
}

我通常将上述代码写在另一个方法中,然后在onCreate()方法中调用。