简体   繁体   English

Android棉花糖权限

[英]android marshmallow permission

How can I get MY_PERMISSIONS_REQUEST_READ_PHONE_STATE in the code below ? 如何通过下面的代码获取MY_PERMISSIONS_REQUEST_READ_PHONE_STATE? I didn't see it . 我没看到。 I searched in dev.android.com but didnt find anything. 我在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.
    }
}

As you can see in the comments, this is an app-defined int constant, so just define it as such: 正如您在注释中看到的那样,这是一个应用程序定义的int常量,因此只需将其定义为:

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

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

Then, use it onRequestPermissionsResult() : 然后,在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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM