用的框架:
/**
* 动态权限
* https://github.com/googlesamples/easypermissions
* */
implementation 'pub.devrel:easypermissions:1.3.0'
业务流程:
- 调用权限服务之前,获取当前权限状态,如果没有则申请权限
- 获取到了权限则调用服务,否则禁止调用(闪退)
来个调用相机的例子:
- 添加imageview点击事件,点击调用相册
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
methodRequiresCameraPermission();
}
});
- 调用相机的代码如下:
// 相机权限
@AfterPermissionGranted(KapPermissionUtils.RC_CAMERA_AND_LOCATION)
private void methodRequiresCameraPermission(){
String[] perms = KapPermissionUtils.KapPermissionCamera();
if (EasyPermissions.hasPermissions(getContext(), perms)) {
pushImageActivity();// 按业务自己跳转
} else {
EasyPermissions.requestPermissions(this, alert_permission_camera,
KapPermissionUtils.RC_CAMERA_AND_LOCATION, perms);
}
}
- 系统权限回调交托
/** 权限申请 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// 权限申请
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
- 自己写的一个配置类
/**
* Created by jing on 2017/7/4.
* 动态权限申请
*/
public class KapPermissionUtils {
/** 相机相册 */
public static final int RC_CAMERA_AND_LOCATION = 1001;
public static String[] KapPermissionCamera(){
String[] perms;
perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
return perms;
}
/** 通讯录 */
public static final int RC_CONTACTS_PERM= 1003;
public static String[] KapPermissionContacts(){
String[] perms;
perms = new String[]{Manifest.permission.READ_CONTACTS};
return perms;
}
public static final int RC_SD_PERM = 1002;//
}