android 棉花糖权限

android marshmallow permission

如何在下面的代码中得到 MY_PERMISSIONS_REQUEST_READ_PHONE_STATE?我没看到。我在 dev.android.com 中搜索但没有找到任何内容。

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

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

        // 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_PHONE_STATE},
                MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);

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

正如您在评论中看到的那样,这是一个应用程序定义的 int 常量,因此只需这样定义即可:

// Add this definition:
public static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 999;

private void checkPermission() {
   //.....
}

然后,使用它onRequestPermissionsResult():

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

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


            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

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