运用场景
- 谷歌在Android M版本之后,为了用户安全,提出了权限机制,所以开发者需要在代码层进行基本的系统权限逻辑编码
- 开发者在基本的系统权限开发中,处理的逻辑有点繁琐
这里介绍一个处理权限的库-easypermissions,这个库主要功能就是在系统权限的逻辑上面封装了一些我们经常用到的逻辑,更方便我们的使用,接下来我们一起去了解一下吧
结构介绍
1.activity和fragment页面权限的申请
2.自定义的dialog
3.弹出系统设置页面
简单使用
依赖 implementation 'pub.devrel:easypermissions:2.0.0'
申请权限
这里举个栗子,申请相机权限和地理位置权限
@AfterPermissionGranted(Constant.RC_CAMERA_AND_LOCATION)
private fun methodRequiresTwoPermission() {
val perms = arrayOf(Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION)
if (EasyPermissions.hasPermissions(this, *perms)) {
// Already have permission, do the thing
// ...
} else {
// Do not have permissions, request them now
//这个方法是用户在拒绝权限之后,再次申请权限,才会弹出自定义的dialog,详情可以查看下源码 shouldShowRequestPermissionRationale()方法
EasyPermissions.requestPermissions(
PermissionRequest.Builder(this, RC_CAMERA_AND_LOCATION, *perms)
.setRationale(R.string.camera)
.setPositiveButtonText(R.string.yes)
.setNegativeButtonText(R.string.no)
.build())
}
}
//接受系统权限的处理,这里交给EasyPermissions来处理,回调到 EasyPermissions.PermissionCallbacks接口
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults,this)//注意这个this,内部对实现该方法进行了查询,所以没有this的话,回调结果的方法不生效
}
实现 EasyPermissions.PermissionCallbacks ,重写以下两个方法 (弹出系统框时,用户点击接受和拒绝按钮)
override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
// Check if at least one permission in the list of denied permissions has been permanently
// denied (user clicked "Never ask again").
// This will display a dialog directing them to enable the permission in app settings.
//如果用户点击永远禁止,这个时候就需要跳到系统设置页面去手动打开了
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
AppSettingsDialog.Builder(this).build().show()
}
}
override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
//设置页面跳转需要处理的逻辑
if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
// Do something after user returned from app settings screen, like showing a Toast.
Toast.makeText(this, R.string.returned_from_app_settings_to_activity, Toast.LENGTH_SHORT)
.show()
}
}
实现 EasyPermissions.RationaleCallbacks,重写以下两个方法 (弹出自定义dialog时,用户点击接受和拒绝按钮)
override fun onRationaleDenied(requestCode: Int) {
}
override fun onRationaleAccepted(requestCode: Int) {
}
好啦,大概这个权限库就这么简单的介绍完了,可以github上看看,多学学别人写的代码也是蛮不错的,里面有些设计模式也可以学习一下