Android 将EasyPermissions进一步封装,使得动态权限申请更加简明
1.引入依赖:
implementation 'pub.devrel:easypermissions:3.0.0'
2.在BaseActivity处理统一的结果回调和请求Code
核心内容:
(1)处理Activity本身继承的方法onRequestPermissionsResult
(2)实现接口EasyPermissions.PermissionCallbacks来接收请求结果
(3)定义申请权限跳转带出去的Code(Int类型,合法范围0-255)
(4)定义PermissionsCallBack是对结果返回的进一步简化 (非必须)
/***Author:XingHai.Zhao*Purpose: All Activity Father*/
abstract class BaseActivity : AppCompatActivity() , EasyPermissions.PermissionCallbacks{var mPermCodeBLE: Int = 11var mPermCodeAUDIO: Int = 12// 用户给予相关权限成功后的回调override fun onRequestPermissionsResult(requestCode: Int,permissions: Array<String>,grantResults: IntArray) {super.onRequestPermissionsResult(requestCode, permissions, grantResults)// 进一步使用 EasyPermissions 处理后续结果EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)}override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {// 授予权限mPermissionsCallBack?.let {it.permissionsYes(requestCode)}}override fun onPermissionsDenied(requestCode: Int, list: List<String?>) {// 请求权限被拒mPermissionsCallBack?.let {it.permissionsNo(requestCode)}}var mPermissionsCallBack: PermissionsCallBack? = nullinterface PermissionsCallBack {fun permissionsYes(code: Int) //获取授权成功fun permissionsNo(code: Int) //获取授权成功}// 获取蓝牙相关的权限fun getBlePerm(): Array<String> {return when {Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> arrayOf(Manifest.permission.BLUETOOTH_SCAN,Manifest.permission.BLUETOOTH_CONNECT,Manifest.permission.BLUETOOTH_ADVERTISE,Manifest.permission.ACCESS_FINE_LOCATION)Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> arrayOf(Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.ACCESS_FINE_LOCATION)else -> arrayOf(Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.ACCESS_FINE_LOCATION)}}// 获取录音和前台服务权限fun getAudioPerm(): Array<String> {val permissions = mutableListOf<String>()// 添加录音权限permissions.add(Manifest.permission.RECORD_AUDIO)// 根据 Android 版本添加前台服务权限if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {permissions.add(Manifest.permission.FOREGROUND_SERVICE)}return permissions.toTypedArray()}}
3具体请求用蓝牙举例:
//权限判断,第一次弹出系统的授权提示框if (EasyPermissions.hasPermissions(this, *getBlePerm())) {if (!BluetoothAdapter.getDefaultAdapter().isEnabled) {//打开蓝牙开关startActivity(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))}// 有权限 直接执行---在这里执行下一步操作 用蓝牙举例的话 这里要开启蓝牙搜索} else {// 没有权限,进行权限请求EasyPermissions.requestPermissions(this,getString("需要赋予相关权限,方能正常使用该功能!"),mPermCodeBLE,*getBlePerm())}mPermissionsCallBack = object :PermissionsCallBack{override fun permissionsYes(code: Int) {---在这里执行下一步操作 用蓝牙举例的话 这里要开启蓝牙搜索}override fun permissionsNo(code: Int) {}}