ContextCompat.checkSelfPermission的用例是什么? [英] What is the use case for ContextCompat.checkSelfPermission?

查看:618
本文介绍了ContextCompat.checkSelfPermission的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有以下方法来检查AppCompatActivity中的棉花糖的运行时权限:

if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
    boolean hasPermission = checkSelfPermission(Manifest.permission.XX)
                == PackageManager.PERMISSION_GRANTED;
    if(!hasPermission) {
        if(shouldShowRequestPermissionRationale(Manifest.permission.XX)) {
            // explain reason for permission, try again

        } else {
            // user deny with "don't show again"
        }
    }
}

到目前为止,我发现它对棉花糖非常有效.但是,我应该担心M之前版本中的权限,我应该使用解决方案

取决于权限阻止程序的实现(例如,通过Xposed),或者为应用程序提供了虚假数据,否则应用程序的进程将被撤消权限. >

您将无法检测到该应用程序是否获取了假数据,但在这种情况下,您的应用程序至少不会崩溃.

如果在进程级别上撤消了许可,则ContextCompat.checkSelfPermission()甚至在pre-M之前也能够检测到它,并返回PERMISSION_DENIED.请注意,如果使用ContextCompat方法,则还必须使用ActivityCompat.shouldShowRequestPermissionRationale()ActivityCompat.requestPermissions()方法或它们的FragmentCompat版本.

有关更多详细信息,请参见此处:用于处理权限的支持库方法.

Currently I have the following method to check for runtime permission in AppCompatActivity for Marshmallow :

if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
    boolean hasPermission = checkSelfPermission(Manifest.permission.XX)
                == PackageManager.PERMISSION_GRANTED;
    if(!hasPermission) {
        if(shouldShowRequestPermissionRationale(Manifest.permission.XX)) {
            // explain reason for permission, try again

        } else {
            // user deny with "don't show again"
        }
    }
}

So far I find it works reasonably well for Marshmallow. However, should I be worrying about permission in pre-M versions that I should use ContextCompat.checkSelfPermission() instead? I know permissions in pre-M can be modified by using Xposed or similar frameworks, does that mean ContextCompat.checkSelfPermission() is able to sufficiently detect permission denials due to Xposed etc too?

解决方案

Depending on the implementation of the permission blocker (e.g. via Xposed) either the app is provided with fake data or the app's process will have the permission revoked.

You won't be able to detect whether the app gets fake data or not, but in that case your app will at least not crash.

If the permission is revoked on process level, then ContextCompat.checkSelfPermission() is able to detect it even on pre-M and returns PERMISSION_DENIED. Note that if you use the ContextCompat method you also have to use the ActivityCompat.shouldShowRequestPermissionRationale() and ActivityCompat.requestPermissions() methods or their FragmentCompat versions.

See here for more details: Support library methods for handling permissions.

这篇关于ContextCompat.checkSelfPermission的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆