Android运行时权限不断被拒绝

时间:2018-06-11 00:49:32

标签: java android permissions runtime

我正在尝试为Android应用程序请求运行时权限。这是我的代码:

private static final int PERMISSION_REQUEST_CODE = 1;
String installPermission = Manifest.permission.INSTALL_PACKAGES;
String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;

@Click(R.id.buttonVersionUpgrade)
void buttonVersionUpgradeClicked(View v) {
    if (!checkPermission(installPermission)) {
        requestPermission(installPermission);
    }
    if (!checkPermission(writePermission)) {
        requestPermission(writePermission);
    }
}

private boolean checkPermission(String permission){
    if (Build.VERSION.SDK_INT >= 23) {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(), permission);
        if (result == PackageManager.PERMISSION_GRANTED){
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }
}

private void requestPermission(String permission){
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)){
        Toast.makeText(getApplicationContext(), "Permission required for features to work.",Toast.LENGTH_LONG).show();
    }
    ActivityCompat.requestPermissions(this, new String[]{permission},PERMISSION_REQUEST_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission Granted.",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),"Permission Denied.",
                        Toast.LENGTH_LONG).show();
            }
            break;
    }
}

在我的AndroidManifest.xml中:

<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

但是,上面的代码会在不提示用户许可的情况下继续显示权限被拒绝。有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

首先if (Build.VERSION.SDK_INT >= 23) {...}是不必要的,因为ContextCompat.checkSelfPermission已经处理了必要的向后兼容性。

  

但是,上面的代码仍然显示权限被拒绝   提示用户许可。

这是因为,android.permission.INSTALL_PACKAGES&amp; android.permission.DELETE_PACKAGES不适用于第三方应用程序。

如果您只请求android.permission.WRITE_EXTERNAL_STORAGE,那么您应该看到正确的权限对话框。

显示保护级别为dangerous的权限的权限请求。您可以参考此document来确定保护级别。有关权限级别和类型的详细信息,请参阅此permission overview document

答案 1 :(得分:0)

我的清单错误:

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

我在“ WRITE_EXTERNAL_STORAGE ”之后有空格。我删除了,现在一切正常。