Android运行时权限不起作用

时间:2018-07-19 14:45:41

标签: android android-activity permissions

我从活动的onCreate方法调用了权限函数,该函数应将布尔值相应地设置为true和false。但是在授予权限后,布尔变量不会返回true。从oncreate方法调用verifyStoragePermissions是否有问题?请提出适当的方法。谢谢。

注意:我已经在清单文件中添加了权限。

Boolean PermissionGranted = false;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public  void verifyStoragePermissions(Activity activity) {
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }else{
        PermissionGranted = true;
    }
}

@Override
public void onRequestPermissionsResult(
        int requestCode,
        String permissions[],
        int[] grantResults) {
    super.onRequestPermissionsResult(requestCode,permissions,grantResults);
    if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        PermissionGranted = true;
        System.out.println("P granted");
    } else {
        PermissionGranted = false;
        System.out.println("P not granted");
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    verifyStoragePermissions(this);
    if(!PermissionGranted) {
    ...
    }else{
    ...
    }
    .....
}

2 个答案:

答案 0 :(得分:1)

根据您在此处输入的代码,您遇到的问题应该是AndroidManifest中缺少的权限。

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

处理权限时,请不要忘记将其放入AndroidManifest中。

有关许可的更多信息,请检查此link

答案 1 :(得分:0)

您需要添加

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

到您的AndroidManifest.xml文件。