我正在尝试在 Marshmallow 中获得存储许可。一切似乎都很好,我可以授予或拒绝许可。
private static final int REQUEST_STORAGE = 1;
// request storage permission
private void requestStoragePermission() {
String[] permissions = new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE };
if (!hasStoragePermission()) {
Log.e(TAG, "No storage permission at the moment. Requesting...");
ActivityCompat.requestPermissions(this, permissions, REQUEST_STORAGE);
} else
Log.e(TAG, "We already have storage permission. Yay!");
}
// check is storage permission granted
private boolean hasStoragePermission() {
String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
int hasPermission = ContextCompat.checkSelfPermission(this, storagePermission);
return (hasPermission == PackageManager.PERMISSION_GRANTED);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "Storage permission granted");
} else {
Log.e(TAG, "Storage permission denied");
Toast.makeText(getApplicationContext(), getString(R.string.no_storage_permission), Toast.LENGTH_SHORT).show();
}
break;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
然而问题就在这里。当我第一次使用这个功能时,hasStoragePermission()
总是错误的,即使在授予权限之后也是如此。在我必须使用上下文菜单两次才能执行我想要的操作之前未授予权限时。这是不可接受的。
// some code...
// even more code...
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ID_CONTEXT_MENU_SAVE_IMAGE:
// in order to save anything we need storage permission
requestStoragePermission();
Log.e("SomeActivity", "storagePermissionGranted: " + hasStoragePermission());
if (!hasStoragePermission())
return false;
saveImageToDisk(mPendingImageUrlToSave);
break;
}
return super.onContextItemSelected(item);
}
Android Marshmallow 中是否有任何已知的错误可能导致它?代码似乎没问题,因为实际上我可以授予/拒绝存储权限。不过,我想立即拥有它。