我正在尝试在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()
也始终为false。在我必须使用上下文菜单两次才能执行我想要的操作之前未授予权限时。这是不可接受的。
// 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中是否存在可能导致错误的已知错误?代码似乎没问题,因为实际上我可以授予/拒绝存储权限。我想立即拥有它。
答案 0 :(得分:2)
权限请求和返回的结果是异步的。执行onRequestPermissionsResult()
后,您的应用将被授予或拒绝该权限。在某些情况下,这将导致整个应用程序重新启动(某些权限。)仅供参考,外部存储 应该是其中之一,但是现在M有一个问题,即应用程序并非总是如此授予此权限时重新启动。