深色模式
Android 权限请求封装
封装 PermissionRequestHelper 类
kotlin
import android.content.pm.PackageManager
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class PermissionRequestHelper(private val activity: AppCompatActivity) {
// 接收权限请求结果的回调
private val multiplePermissionsLauncher = activity.registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
// 权限请求结果回调
handlePermissionsResult(permissions)
}
// 请求多个权限
fun requestPermissions(permissions: Array<String>) {
// 检查每个权限是否已经授权,如果未授权则请求权限
val permissionsToRequest = permissions.filter { permission ->
ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED
}.toTypedArray()
// 请求未授权的权限
if (permissionsToRequest.isNotEmpty()) {
multiplePermissionsLauncher.launch(permissionsToRequest)
} else {
// 所有权限都已授权,执行相应操作
onUserAlreadyAccept?.invoke()
}
}
// 处理权限请求结果
private fun handlePermissionsResult(permissions: Map<String, Boolean>) {
for ((permission, isGranted) in permissions) {
if (isGranted) {
// 权限已授权
onUserAccept?.invoke(permission)
} else {
// 权限被拒绝
if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
// 用户拒绝且不再询问
onUserDenyPermanent?.invoke(permission)
} else {
// 用户拒绝,但可以再次请求权限
onUserDeny?.invoke(permission)
}
}
}
}
// - 用户已经授权过所有权限
private var onUserAlreadyAccept: (() -> Unit)? = null
fun onUserAlreadyAccept(action: () -> Unit) {
onUserAlreadyAccept = action
}
// - 用户同意
private var onUserAccept: ((String) -> Unit)? = null
fun onUserAccept(action: (String) -> Unit) {
onUserAccept = action
}
// - 用户拒绝
private var onUserDeny: ((String) -> Unit)? = null
fun onUserDeny(action: (String) -> Unit) {
onUserDeny = action
}
// - 用户拒绝且不再询问
private var onUserDenyPermanent: ((String) -> Unit)? = null
fun onUserDenyPermanent(action: (String) -> Unit) {
onUserDenyPermanent = action
}
}
使用 PermissionRequestHelper
由于activity.registerForActivityResult()
方法需要在Activity的onStart()
之前调用,所以,可以在BaseActivity
中创建PermissionRequestHelper
的实例。
kotlin
abstract class BaseActivity : AppCompatActivity() {
lateinit var permissionHelper : PermissionRequestHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
permissionHelper = PermissionRequestHelper(this)
// ...
}
}
在BaseActivity
的子类中,发起权限请求,并处理回调。
kotlin
// 示例:请求读取手机状态权限
permissionHelper
.apply {
onUserAlreadyAccept { // 用户已经授权过所有权限 }
onUserAccept { // 用户同意 }
onUserDeny { // 用户拒绝 }
onUserDenyPermanent { // 用户拒绝且不再询问 }
}
.requestPermissions(arrayOf(Manifest.permission.READ_PHONE_STATE))