是否可以在最低SDK <23时设置checkSelfPermission?

Ard*_*rdi 26 android android-6.0-marshmallow

Android-M中的新运行时权限要求最低23个API级别,但我的项目中仍需要最低16个API级别.

在此输入图像描述

那么,如何使这个代码更向前兼容?

问候

Com*_*are 57

使用ContextCompat.checkSelfPermission() ,, ActivityCompat.requestPermissions()ActivityCompat.shouldShowPermissionRequestRationale(),从support-v4库(v23或更高版本).这些是向后兼容的; 如果你是在一个旧版本的Android上运行,他们会"做正确的事"(例如,返回PackageManager.PERMISSION_GRANTEDContextCompat.checkSelfPermission()).

  • 我也使用支持v4和ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED在HTC Incredible与android 2.3.3上返回false.知道为什么吗? (5认同)
  • 它是.. minSdkVersion ="7"android:targetSdkVersion ="23" (4认同)

Md.*_*rim 5

只需在获得检查权限之前检查您的android版本:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for Activity#requestPermissions for more details.
                    return;
                }
            }else{
              //Do Your Stuff
           }
Run Code Online (Sandbox Code Playgroud)