使用权限动态类库EasyPermissions

比如我要获取一个打开相机的权限

1.最开始还是在AndroidManifest.xml写进自己需要的权限:

   
    
    

2.在Activity中首先建一个String数组,把需要的权限都加进去:

//设置权限
private String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA};
private static final int PERMISSIONS = 1000;     //请求码

3.在需要的位置写入请求的权限

if (EasyPermissions.hasPermissions(MainActivity.this, permissions)){
    Intent intent_code = new Intent(this, CaptureActivity.class);
    startActivityForResult(intent_code, 111);
}else {
    //没有打开相关权限、申请权限
    EasyPermissions.requestPermissions(MainActivity.this, "需要获取您的相册、照相使用权限", PERMISSIONS, permissions);
}

4.剩下的代码写在activity里面就好了

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    //框架要求必须这么写
    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}


//成功打开权限
public void onPermissionsGranted(int requestCode, @NonNull List perms) {
    Toast.makeText(this, "相关权限获取成功", Toast.LENGTH_SHORT).show();
}
//用户未同意权限
public void onPermissionsDenied(int requestCode, @NonNull List perms) {
    Log.d("**", "onPermissionsDenied: 拒绝权限");
    if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
        new AppSettingsDialog.Builder(this)
                .setRationale("没有该权限,此应用程序可能无法正常工作。打开应用设置屏幕以修改应用权限")
                .setTitle("必需权限")
                .build()
                .show();
    }
}

 

你可能感兴趣的:(android)