在Android开发中,获取本地存储权限是常见的操作,例如读写SD卡、内部存储等。从Android 6.0(API 级别 23)开始,为了增强用户隐私保护,系统对权限管理进行了重大更新,要求应用在运行时请求权限。以下是获取本地存储权限的5个关键步骤:
步骤1:在AndroidManifest.xml中声明权限
首先,需要在应用的AndroidManifest.xml文件中声明所需的权限。对于本地存储权限,通常使用以下两个权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
对于Android 10(API 级别 29)及更高版本,由于对存储权限的变更,推荐使用以下权限:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
步骤2:运行时请求权限
从Android 6.0开始,应用需要在运行时请求权限。以下是一个简单的示例代码,展示如何请求存储权限:
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
}
步骤3:处理权限请求结果
在Activity的onRequestPermissionsResult方法中处理权限请求的结果:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other permissions this app might request
}
}
步骤4:使用ContextCompat.checkSelfPermission检查权限
在执行需要权限的操作之前,可以使用ContextCompat.checkSelfPermission来检查权限是否已经被授予:
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Permission has already been granted
} else {
// Permission is not granted
}
步骤5:适配Android 10及以上版本
对于Android 10及以上版本,系统对存储权限有了新的要求。应用需要请求MANAGE_EXTERNAL_STORAGE权限,并且用户必须明确授权。以下是一个适配Android 10及以上版本的示例:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.MANAGE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.MANAGE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_MANAGE_EXTERNAL_STORAGE);
} else {
// Permission has already been granted
}
}
在onRequestPermissionsResult方法中处理该权限的请求结果。
通过以上5个步骤,您可以在Android应用中成功获取本地存储权限。请注意,始终确保您的应用在请求权限时遵循最佳实践,并尊重用户的隐私。
