Reputation: 3462
I am trying to get a list of all images on the device. The key command to achieve that is the querying command:
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, null);
which I put within the onCreate() method of the main activity.
within the manifest file I put the required permission (under the root node):
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
As far as I understand this is all I need to do. Yet this code fails (at the above command) with a security exception, telling me that I need READ_EXTERNAL_STORAGE permission. I thought I asked for it, but it isn't there. I tried to debug it, and it isn't there. I tried to add a requestPermissions(...) command before the query, and it doesn't work.
the exact error message I get is this:
java.lang.RuntimeException: Unable to start activity componentInfo{com.galamit.pic1/com.galamit.pic1.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=26249, uid=10012 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
I feel I miss something pretty basic, but can't figure out what it might be. Any clue?
EDIT: the request permission part looks like this:
if(this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
}
Upvotes: 1
Views: 339
Reputation: 1006614
I would like to understand why the permission requested in the manifest is not enough
It is not supposed to be enough on Android 6.0+ devices, if your targetSdkVersion
is 24 or higher. For newer apps and newer devices, you also have to request certain permissions at runtime, and READ_EXTERNAL_STORAGE
is one of those.
The reason why your requestPermissions()
call is not working is because that call is not synchronous. It is asynchronous. You will not know until onRequestPermissionsResult()
whether you got the permission or not.
So, you need to isolate your query()
work into a separate method, that you call from two places:
Where it is now, if and only if checkSelfPermission()
says that you already have the permission
onRequestPermissionsResult()
, for your particular request, if the result indicates that user agreed to grant you permission
Upvotes: 2