Android6.0动态申请SD卡读写的权限

时间:2022-09-04 19:58:33

Android6.0之后系统对权限的管理更加严格了,不但要在AndroidManifest中添加,还要在应用运行的时候动态申请。下面是动态申请SD卡读写的权限

  1. 在AndroidManifest中添加SD卡读写的权限
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  1. 动态申请权限
 private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE" };


public static void verifyStoragePermissions(Activity activity) {

try {
//检测是否有写的权限
int permission = ActivityCompat.checkSelfPermission(activity,
"android.permission.WRITE_EXTERNAL_STORAGE");
if (permission != PackageManager.PERMISSION_GRANTED) {
// 没有写的权限,去申请写的权限,会弹出对话框
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}

把verifyStoragePermissions方法放在onCreate方法中即可。