Search code examples
androidandroid-5.0-lollipopandroid-galleryandroid-fileandroid-mediascanner

Make image File visible in Android Gallery on Lollipop


I am trying to make some pictures that are taken in the app visible in the Gallery (so they can be shared and looked at outside of the app), but I want to keep the images themselves inside the data directory of the app so when the app is deleted they get removed (so they are stored in "{sdcard}/Android/data/{appID}/Pictures/{subfolder}/").

I have looked at a lot of answers and for older versions of Android both of the following solutions work, but they don't seem to work in Lollipop:

MediaScannerConnection.scanFile(this,
    new String[]{file.toString()}, new String[] { "image/jpeg" },
    new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {
            Log.i("ExternalStorage", "Scanned " + path + ":");
            Log.i("ExternalStorage", "-> uri=" + uri);
        }
    });

Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new 
    Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
sendBroadcast(mediaScanIntent);

I have tested this in a Nexus 4 (Android 5.0.1) and a Nexus 6 (Android 5.1) and it doesn't work. In a Nexus 7 (Android 4.2.2) it does work. All 3 devices have a ".onmedia" file in the {sdcard}/Android/data/ folder, so no normal media scan should pick them up...

Does anyone know a work around to get this to work on all devices/Android versions? Should this because of the noMedia file not work in the first place and is Lollipop the only version that does this correctly?

Edit: Note that even a restart of the phone (which should also trigger a rescan of files) doesn't work. And for good reason as the files are in a subfolder of a ".nomedia" directory... So any solution containing a MEDIA_MOUNTED broadcast is kind of useless I assume.


Solution

  • Try below code. It working for me in Lollipop, Hope working for you as well

    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DATA,"file path");
    values.put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg");
    mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
    

    EDIT: Don't forget to add this to your manifest (although in Lollipop it should no longer be necessary):

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