是否可以在最小SDK上设置checkSelfPermission< 23?

时间:2015-09-16 17:27:17

标签: android android-6.0-marshmallow

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

enter image description here

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

此致

5 个答案:

答案 0 :(得分:54)

来自set.seed(1) Df1 <- data.frame(year=rep(2015,1e6), month=sample(3:7,1e6,replace=TRUE), Vol=rnorm(1e6)) system.time(result.mrg <- merge(Df1,Df2,by=c("year","month"))) # user system elapsed # 11.8 0.0 11.8 system.time(result.dt <- setkey(setDT(Df1),year,month[setDT(Df2),IB:=IB]) # user system elapsed # 0.07 0.00 0.06 identical(result.mrg$IB, result.dt$IB) # [1] TRUE 库(v23或更高版本)的

Use ContextCompat.checkSelfPermission()ActivityCompat.requestPermissions()ActivityCompat.shouldShowPermissionRequestRationale()。这些是向后兼容的;如果您使用的是旧版Android,他们会“做正确的事情”(例如,support-v4返回PackageManager.PERMISSION_GRANTED)。

答案 1 :(得分:4)

在获得检查权限之前,请检查您的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
           }

答案 2 :(得分:4)

如果你不想使用AppCompatActivity,这里描述的方式 https://codemammoth.blogspot.gr/2016/06/how-to-invoke-checkselfpermission.html

您必须调用方法:)

答案 3 :(得分:1)

您可以检查构建版本if(Build.Version.SDK_INT >= Build.VERSION_CODES.MARSHMALLOW)。然后在那里处理marshmallow权限,否则处理其他版本。

答案 4 :(得分:1)

checkSelfPermission在sdk 23之上可用。

我们可以使用包管理器检查权限是否可用

public static Boolean checkpermissions(Activity activity) {


        PackageManager mPackageManager = activity.getPackageManager();
        int hasPermStorage = mPackageManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, activity.getPackageName());


        if (hasPermStorage != PackageManager.PERMISSION_GRANTED) {
            // do stuff
            //Toast.makeText(getApplicationContext(), "No permission", Toast.LENGTH_LONG).show();

            return false;
        } else if (hasPermStorage == PackageManager.PERMISSION_GRANTED) {

            // do stuff
            //Toast.makeText(getApplicationContext(), "Has permission", Toast.LENGTH_LONG).show();

            return true;
        }else
            return false;
    }