Search code examples
androidsaveandroid-gallery

Save photos to Android Gallery


I try to add a Bitmap photo that I took with the phone to the gallery in Android Studio but I am getting the error:

Failed to insert image
   java.lang.SecurityException: Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=4110, uid=10058 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()

I have used in the Manifest xml:

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

The way I save the image is:

MediaStore.Images.Media.insertImage(getContentResolver(), FullBitmap, "Name" , "Date");

I am using the Nexus 5 emulator and Android version 5.1.


Solution

  • As @njzk2 pointed out, do not use the android:maxSdkVersion attribute. This attribute is meant for permissions that are no longer necessary for higher API levels. The example given in the documentation is one of the few reasons you should apply this attribute:

    For example, beginning with Android 4.4 (API level 19), it's no longer necessary for your app to request the WRITE_EXTERNAL_STORAGE permission when your app wants to write to its own application-specific directories on external storage (the directories provided by getExternalFilesDir()). However, the permission is required for API level 18 and lower.

    In your case, you are accessing a public directory; for which you do need WRITE_EXTERNAL_STORAGE permission on all API levels.