Android检查权限

时间:2015-11-05 09:25:10

标签: android android-permissions android-6.0-marshmallow

我正在SDK版本23中开发我的项目,其中新引入了应用程序权限。 在某些指导原则中,他们使用以下代码来阅读电话状态许可是否已授予

BEGIN
  DELETE FROM dml_exception;
  raise value_error;
END;

但我直接访问if (ContextCompat.checkSelfPermission(serviceContext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { //Read Phone state }else{ } ,如下所示

checkSelfPermission

它工作正常。 我的问题是上面这些代码之间的区别是什么?。这是检查是否授予许可的正确方法?

4 个答案:

答案 0 :(得分:8)

  

我的问题是上述代码之间的区别是什么?

无,在API 23(+)设备上。

但是,当您尝试直接调用context.checkSelfPermission()时,运行旧版Android的设备会产生错误。在 API 23 之前,此方法无法使用。

ContextCompat提供了一种向后兼容的方式,可以在旧API上运行checkSelfPermission()。如果您查看实施,您只需将调用委托给checkPermission()并使用应用程序自己的流程参数即可完成此操作。 checkPermission()自首次发布API以来就已经可用,因此可以全面使用。

public static int checkSelfPermission(@NonNull Context context, @NonNull String permission) {
    if (permission == null) {
        throw new IllegalArgumentException("permission is null");
    }

    return context.checkPermission(permission, android.os.Process.myPid(), Process.myUid());
}
  

这是检查授予权限的正确方法吗?

所以,回答这个问题:如果你只是支持运行Android' Marshmallow' 6.0和更新,那么你可以使用任何一种方法。但是,由于您更有可能支持某些旧版Android,使用ContextCompat

答案 1 :(得分:4)

official and recent way上的所有设备支持编码使用以下代码段

请求您需要的权限

 // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(thisActivity,
                    Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                Manifest.permission.READ_CONTACTS)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(thisActivity,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }

处理权限请求响应

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

答案 2 :(得分:0)

另一种解决方案:

//Requesting permission
private void requestStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
}

//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if(requestCode == STORAGE_PERMISSION_CODE){

        //If permission is granted
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            //Displaying a toast
            Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
        }else{
            //Displaying another toast if permission is not granted
            Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
        }
    }
}

答案 3 :(得分:0)

将此代码添加到Gradle中

implementation 'com.karumi:dexter:5.0.0'

并将此代码添加到您的代码中

Dexter.withActivity(getActivity()).withPermission(Manifest.permission.CAMERA).withListener(
                            new PermissionListener() {
                                @Override
                                public void onPermissionGranted(PermissionGrantedResponse response) {
                                  YourCode
                                }

                                @Override
                                public void onPermissionDenied(PermissionDeniedResponse response) {

                                }

                                @Override
                                public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {

                                }
                            }
                    ).check();