Android 检查权限

Android check permission

我正在使用新引入应用权限的 SDK 版本 23 开发我的项目。 在某些指南中,他们使用以下代码来读取 phone 状态权限是否被授予

if (ContextCompat.checkSelfPermission(serviceContext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
    //Read Phone state
   }else{
}

但我直接访问 checkSelfPermission 如下所示

if(serviceContext.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
      //Read Phone state
   }else{
}

一切正常。 我的问题是上面这些代码之间有什么区别?检查是否授予权限的正确方法是什么?

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
    }
}

My question is what's the difference between above these codes?

None,在 API 23(+) 台设备上。

设备 运行 使用较旧版本的 Android,但是,当您尝试直接调用 context.checkSelfPermission() 时,将生成错误。此方法直到 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());
}

which is the correct way to check for permission granted or not?

所以,要回答这个问题:如果您支持设备运行宁Android'Marshmallow' 6.0 和更新版本,那么您可以使用任何一种方法。但是,由于您更有可能还想支持一些旧版本的 Android, 使用 ContextCompat.

另一个解决方案:

//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();
        }
    }
}

将此代码添加到 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();