从Android6.0开始,权限获取不再是简单地在AndroidManifest.xml添加几行代码了,Google引入了动态权限的概念,需要在代码中添加。
动态权限添加步骤如下,以读取和写入权限为例:
1.AndroidManifest.xml中添加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
1.1 从Android10开始,还需要添加:
<application
android:requestLegacyExternalStorage="true"
...
</application>
2.在Activity相应位置调用:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == -1) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
Log.d("TAG", "onCreate: 申请获得Write权限!");
} else {
Log.d("TAG", "onCreate: 已获得Write权限!");
}
}
然而在Android11开始,WRITE_EXTERNAL_STORAGE等特殊权限的获取又发生了变化…
![Android11+的特殊权限变化](https://i-blog.csdnimg.cn/blog_migrate/fab1ca58a23991c533ec5ae09c8aadc0.png#pic_center)
当仍沿用Android10-的权限获取方式时,会在调用权限时抛出异常
因为在Andorid11+中,Google添加了一个新的权限:MANAGE_EXTERNAL_STORAGE
当APP动态请求权限时,会引导用户进入一个权限设置界面
![文件所有权设置界面](https://i-blog.csdnimg.cn/blog_migrate/df416a4815a26ef0d12280cbcc9c63f2.png#pic_center)
所以,在Android11+中:
1.2 AndroidManifest.xml中添加权限:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
该权限仅支持Android11+
![该权限仅支持Android11+](https://i-blog.csdnimg.cn/blog_migrate/932c37e8bf1b24859af10df4178b9962.png#pic_center)
2.1 在Activity相应位置调用:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.setData(Uri.parse("package:" + mContext.getPackageName()));
startActivityForResult(intent, 1024);
}
2.2 所以合并起来的代码是:
public void getWriteRight() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.setData(Uri.parse("package:" + mContext.getPackageName()));
startActivityForResult(intent, 1024);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == -1) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
Log.d("TAG", "onCreate: 申请获得Write权限!");
} else {
Log.d("TAG", "onCreate: 已获得Write权限!");
}
}
}