1、手动申请
Android6.0之后系统对权限的管理更加严格了,不但要在AndroidManifest中添加,还要在应用运行的时候动态申请。下面是动态申请SD卡读写的权限
在AndroidManifest中添加SD卡读写的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
动态申请权限
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方法中即可。
2、默认申请
https://github.com/Karumi/Dexter
通过上面库,接入方式:
在build.gradle加入
dependencies{
implementation 'com.karumi:dexter:5.0.0'
}
然后在mainactivity加入
static final String[] PERMISSIONS = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
};
private void initPermissions() {
Dexter.withActivity(this).withPermissions(PERMISSIONS)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()){
Toast.makeText(getApplication(),"权限获取成功!",Toast.LENGTH_LONG).show();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
}).check();
}
然后在oncreate()中加入initPermissions()就行了
以上两种方法,亲测可用。
网友评论