Android M权限授予回调

Android M permission grant callback

我正在 Android M Dev Preview 上测试权限系统。我对回调函数有疑问。 Activity class 有一个新的 API:

public void onRequestPermissionsResult (int requestCode, 
               String[] permissions, int[] grantResults) { }

我想问一下为什么权限和grantResults参数定义为数组?我知道可以使用 requestPermissions() 同时请求多个权限,但是如果请求代码用于请求的权限集,那么仅仅有一个整数 grantResults 就足够了吗(不确定权限参数) ?

否,因为用户可以独立授予或拒绝您请求的任何权限。

例如,假设我有:

  private static final String[] PERMS_ALL={
    CAMERA,
    WRITE_EXTERNAL_STORAGE
  };

我打电话给:

requestPermissions(PERMS_ALL, RESULT_PERMS_ALL);

CAMERAWRITE_EXTERNAL_STORAGE 在不同的权限组中。系统将提示用户,per group,授予或拒绝权限。他们根据权限提供结果,因为我们请求权限(而不是组)。但用户可以:

  • 两者都授予
  • 两者都否认
  • 授予 CAMERA 但不授予 WRITE_EXTERNAL_STORAGE
  • 授予 WRITE_EXTERNAL_STORAGE 但不授予 CAMERA

因此,他们给了我们完整的结果名单。

就我个人而言,我不会使用这些结果并调用 checkSelfPermission(),以防出现一些奇怪的竞争条件,即我有一段时间没有用 onRequestPermissionResult() 调用并且用户更改他们的想法首先通过设置。

为我工作

检查并请求许可

if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {


            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION )) {

                // 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(this,
                        new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION },
                        MY_PERMISSIONS_REQUEST_ACCESS_LOCATION);

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

            return;
        }

回调

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_LOCATION: {
                // 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.
                    moveToNextActivity();

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