前段时间各大平台app市场纷纷加大app审核力度,android生态环境日趋健康,在日常的客户端开发当中,我们就需要时刻持有隐私安全的意识,让自己站在用户的角度上合理的保证隐私安全。
本文只探讨 动态权限授予实现解耦
调用流程
private fun userRequestPermissions() {
val permissionCameraLinkedViewModel =
PermissionCameraLinkedViewModel()
val permissionRecordLinkedViewModel =
PermissionRecordLinkedViewModel()
val loginViewModel = LoginViewModel()
loginViewModel.loginSuccess.observe(this, Observer {
if (it) {
Toast.makeText(baseContext, "登录成功", Toast.LENGTH_SHORT).show()
}
})
viewModel.requestPermissions(permissionCameraLinkedViewModel, permissionRecordLinkedViewModel, loginViewModel, activity = this)
}
业务链式分发 通过activity 注入 fragment PermissionProxy 转发权限请求并处理结果 ,通过livedata 更新视图
fun requestPermissions(vararg permissions: BaseLinkedViewModel, activity: FragmentActivity) {
//link
for ((index, value) in permissions.withIndex()) {
if (index != permissions.size - 1) {
value.next = permissions[index + 1]
}
}
permissions[0].next()
}
调用权限请求
fun requestPermission(permission: String) {
val granted = isGranted(permission)
if (granted) {
val permissionCallback: PermissionCallback? =
permissionCallbacks.get(permission);
permissionCallbacks.remove(permission)
permissionCallback?.onNext(permission, true, false)
} else {
//是否已拒绝过 已拒绝禁止再次弹出请求权限
val refused = shouldShowRequestPermissionRationale(permission)
val permissionCallback: PermissionCallback? =
permissionCallbacks.get(permission);
// permissionCallbacks.remove(permission)
permissionCallback?.onNext(permission, false, refused)
showGlobalDialog(refused, permission)
}
}
abstract class BaseLinkedViewModel : BaseViewModel() {
lateinit var next:BaseLinkedViewModel;
abstract fun next()
}
//model分离
class PermissionCameraLinkedViewModel : BaseRequestPermissionLinkedViewModel() {
override fun bindPermissions(): String = Manifest.permission.CAMERA
}
class PermissionRecordLinkedViewModel : BaseRequestPermissionLinkedViewModel() {
override fun bindPermissions(): String = Manifest.permission.RECORD_AUDIO
}
open class LoginViewModel : BaseLinkedViewModel() {
val loginSuccess = MutableLiveData<Boolean>()
override fun next() {
loginSuccess.value = true
}
}