我試圖獲得棉花糖的存儲權限。一切似乎都很好,我可以授予或拒絕許可。運行時權限:授權後立即沒有權限
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有沒有任何已知的錯誤可能導致它?代碼似乎沒問題,因爲實際上我可以授予/拒絕存儲權限。我想立即擁有它。
我的問題的唯一解決方案就是把'if(mPendingImageUrlToSave!= null){saveImageToDisk(mPendingImageUrlToSave); mPendingImageUrlToSave = null; }'授予'onRequestPermissionsResult' - >權限。這是微不足道的,它可能是首選的方式。但令人討厭的是,許可不會立即被授予... – koras
以及將相同的'requestStoragePermission()' – koras