前言
应用的使用需要申请权限,但是如果用户禁用掉,或者禁用并不再提醒就必须到系统设置中开启。
代码语言:javascript复制// 权限
implementation 'com.yanzhenjie:permission:2.0.3'
获取权限
代码语言:javascript复制interface PermissionsCallBack {
fun Granted();
}
private fun getPermission(callback: PermissionsCallBack) {
if (hasPermissions) {
callback.Granted()
return
}
if (AndPermission.hasPermissions(this, *permissions)) {
hasPermissions = true
callback.Granted()
return
}
AndPermission
.with(this)
.runtime()
.permission(*permissions)
.onGranted {
hasPermissions = true
callback.Granted()
}
.onDenied {
mContext?.let {
Toasty.info(it, "授权失败,功能无法使用!").show()
AlertDialog.Builder(it)
.setTitle("提示")
.setMessage("需要打开应用权限才能正常使用!")
.setNegativeButton("取消", object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
dialog?.dismiss()
}
})
.setPositiveButton("确定", object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
dialog?.dismiss()
gotoMiuiPermission()
}
}).create().show()
}
}
.start();
}
打开权限设置页面
我们可以打开系统的设置页面,但是该页面会有应用卸载的功能,为了让用户直接跳转到应用权限页面,我们就要根据不同的系统进行调用。
代码语言:javascript复制/**
* 跳转到miui的权限管理页面
*/
private fun gotoMiuiPermission() {
val i = Intent("miui.intent.action.APP_PERM_EDITOR")
val componentName = ComponentName(
"com.miui.securitycenter",
"com.miui.permcenter.permissions.PermissionsEditorActivity"
)
i.component = componentName
i.putExtra("extra_pkgname", activity?.packageName)
try {
startActivity(i)
} catch (e: Exception) {
e.printStackTrace()
gotoMeizuPermission()
}
}
/**
* 跳转到魅族的权限管理系统
*/
private fun gotoMeizuPermission() {
val intent = Intent("com.meizu.safe.security.SHOW_APPSEC")
intent.addCategory(Intent.CATEGORY_DEFAULT)
intent.putExtra("packageName", activity?.packageName)
try {
startActivity(intent)
} catch (e: java.lang.Exception) {
e.printStackTrace()
gotoHuaweiPermission()
}
}
/**
* 华为的权限管理页面
*/
private fun gotoHuaweiPermission() {
try {
val intent = Intent()
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val comp = ComponentName(
"com.huawei.systemmanager",
"com.huawei.permissionmanager.ui.MainActivity"
) //华为权限管理
intent.component = comp
startActivity(intent)
} catch (e: java.lang.Exception) {
e.printStackTrace()
getAppDetailSettingIntent()
}
}
/**
* 跳转到权限设置界面
*/
private fun getAppDetailSettingIntent() {
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
intent.data = Uri.fromParts("package", activity?.packageName, null)
startActivity(intent)
}