MY_PERMISSONS_REQUEST 没有定义?

MY_PERMISSONS_REQUEST not defined?

我正在尝试检查应用程序的权限,目前正在接受 Android 开发人员培训。 但是,我在插入 page.

中规定的代码时遇到了问题

该页面声称 MY_PERMISSIONS_REQUEST 是应用程序定义的 int 常量。但是,当我把它放在我的实际应用程序中时,它说它没有定义...

有人可以解释为什么会这样吗? 谢谢!

示例代码:

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

您可以将其定义为字段常量,如下所示:

private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;

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

这是因为可能还有其他要求。您可以通过您定义的请求码来区分它。