Android 未经询问就授予我的应用程序运行时权限

Android granted runtime permissions to my app without asking

我正在尝试专门针对 Android sdk > 23 测试运行时权限。但是我的应用程序在没有询问的情况下自动获得权限。

注意:我正在使用 sdk 版本 24。这是我正在使用的代码片段:

public void onCalendarClick(View view) {
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager
            .PERMISSION_DENIED) {
       if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_CALENDAR)) {
            //Display Explanation to the user
            //For granting permissions to the app.
        }
        else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, CALLBACK_CALENDAR);
        }
    }
}

@Override
public void onRequestPermissionsResult(int resultCode, String permission[], int grantResults[]) {
    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Toast toast;
        switch (resultCode) {
            case CALLBACK_CALENDAR : toast = Toast.makeText(this,"Calendar Permission Granted!!",Toast.LENGTH_LONG);
                toast.show(); break;
            //Other Cases
        }
    }
}

当我点击Calendar Button时,onCalendarClick()方法运行,没有请求任何权限,App直接显示Calendar Permission Granted!! toast。在应用程序的设置中,虽然显示 无权限 Granted/Requested

我是不是遗漏了什么或做错了什么?感谢您的帮助。

您遗漏了代码的顺序。检查这个:

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

                // permission was granted, yay! Do the
                // calendar-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
    }
}

有一点不同,您甚至在知道您在谈论 CALENDAR 权限之前就询问是否已授予权限。所以,你应该先检查当前的权限响应是否是你想要的,然后再检查权限是否被授予。

来源:https://developer.android.com/training/permissions/requesting.html

就是这样。我发现对于 android sdk > 22,虽然运行时权限是以编程方式为您的应用程序添加的,但您仍然 需要声明您的应用程序的权限AndroidManifest.xml 文件。所以,添加代码后:

<uses-permission android:name="android.permission.WRITE_CALENDAR"/>

AndroidManifest.xml 中,应用程序请求权限,它终于可以运行了。 更多信息: .感谢大家帮助我)