Android READ_EXTERNAL_STORAGE permission not working

最后都变了- 提交于 2019-11-28 01:50:36
Jordi Castilla

PROBLEM
Your have the error

java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/35634 from pid=25240, uid=10070 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission().

CAUSE
You are not giving correctly permissions because of android:maxSdkVersion="18", which according to documentation.

The highest API level at which this permission should be granted to your app. Setting this attribute is useful if the permission your app requires is no longer needed beginning at a certain API level.

As long as you didn't give permissions to API 21 your app is behaving ok.

Check this topic for further info.

SOLUTION
If you wanna give read permissions under API 21, you must declare them as:

<uses-permission 
    android:name="android.permission.READ_EXTERNAL_STORAGE"
    android:maxSdkVersion="21" />

IMPORTANT:

This only make sense when you need to give extra permissions because some old api's require permissions that new versions doesn't, so user experience get's improved because you only ask for certain permissions when needed.


So (in this case) the correct way will be:

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

ADD ON
If you want to save data you must add WRITE_EXTERNAL_STORAGE permissions.

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

Simply replace with the below one and try,

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

While debugging on some devices you need to grant permission explicitly by going to your settings --> apps --> MY_APPLICATION --> Permissions and then grant required permissions.

In addition to adding the below in AndroidManifest.xml

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

we also need to request permission in the activity for the app to actually have access to external storage. https://developer.android.com/training/permissions/requesting.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!