摘要: Android M运行targetSdkVersion < 23的应用时,调用checkSelfPermission,不管用户是否取消授权,checkSelfPermission的返回值始终为PERMISSION_GRANTED的解决办法
  1. If your application is targeting an API level before 23 (Android M) then both:ContextCompat#checkSelfPermission and Context#checkSelfPermission doesn't work and always returns 0 (PERMISSION_GRANTED). Even if you run the application on Android 6.0 (API 23).

  2. It's not fully true that if you targeting an API level before 23 then  you don't have to take care of permissions. If you targeting an API level before 23 then:

    • Android < 6.0: Everything will be ok.

    • Android 6.0: Application's run-time permissions will be granted by default (compatibility mode applies), but the user can change run-time permissions in Android Settings, then you may have a problem.

  3. As I said in the 1st point, if you targeting an API level before 23 on Android 6.0 thenContextCompat#checkSelfPermission and Context#checkSelfPermission doesn't work. Fortunately you can use PermissionChecker#checkSelfPermission to check run-time permissions.

Example code:

    public boolean selfPermissionGranted(String permission) {        // For Android < Android M, self permissions are always granted.        boolean result = true;        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {            if (targetSdkVersion >= Build.VERSION_CODES.M) {                // targetSdkVersion >= Android M, we can                // use Context#checkSelfPermission                result = context.checkSelfPermission(permission)                        == PackageManager.PERMISSION_GRANTED;            } else {                // targetSdkVersion < Android M, we have to use PermissionChecker                result = PermissionChecker.checkSelfPermission(context, permission)                        == PermissionChecker.PERMISSION_GRANTED;            }        }        return result;    }

In order to obtain target Sdk Version you can use:

    try {        final PackageInfo info = context.getPackageManager().getPackageInfo(                context.getPackageName(), 0);        targetSdkVersion = info.applicationInfo.targetSdkVersion;    } catch (PackageManager.NameNotFoundException e) {        e.printStackTrace();    }

It works on Nexus 5 with Android M.


© 著作权归作者所有
  • 分类:A

更多相关文章

  1. Android之Menu菜单 onCreateOptionsMenu使用Menu按键显示不了问
  2. Android(安卓)Java方法链起来!链式调用方法、仿Builder 等。
  3. android 9.0 在rk3326平台上hidl的使用
  4. Android(安卓)调用系统相机拍照的返回结果
  5. android 分享功能
  6. android学习小结3
  7. 卡联系人IccProvider
  8. Android(安卓)AsyncTask
  9. Android调用Jni,非常简单的一个Demo

随机推荐

  1. android 监听联系人数据库
  2. Android动态生成RadioButton
  3. 如何开始使用Android应用程序模板
  4. android colors.xml 开发必备
  5. 【Android】AsyncTask 实现登陆
  6. Android(安卓)Parcelable Example (转)
  7. Android(安卓)圆角矩形ImageView
  8. Android(安卓)xml资源文件animal动画解析
  9. android:persistentDrawingCache用法说明
  10. Android(安卓)电源管理