Notifies the OS to index the new image, so it shows up in Gallery. - Android Media

Android examples for Media:Media Scan

Description

Notifies the OS to index the new image, so it shows up in Gallery.

Demo Code


import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.view.View;

public class Main{
    /** Notifies the OS to index the new image, so it shows up in Gallery. Allows optional callback method to notify client when
     * the scan is completed, e.g. so it can access the "content" URI that gets assigned.
     *//*from   w ww  . ja  va2  s .c  o m*/
    public static void scanSavedMediaFile(final Context context,
            final String path, final MediaScannerCallback callback) {
        // silly array hack so closure can reference scannerConnection[0] before it's created 
        final MediaScannerConnection[] scannerConnection = new MediaScannerConnection[1];
        try {
            MediaScannerConnection.MediaScannerConnectionClient scannerClient = new MediaScannerConnection.MediaScannerConnectionClient() {
                public void onMediaScannerConnected() {
                    scannerConnection[0].scanFile(path, null);
                }

                public void onScanCompleted(String scanPath, Uri scanURI) {
                    scannerConnection[0].disconnect();
                    if (callback != null) {
                        callback.mediaScannerCompleted(scanPath, scanURI);
                    }
                }
            };
            scannerConnection[0] = new MediaScannerConnection(context,
                    scannerClient);
            scannerConnection[0].connect();
        } catch (Exception ignored) {
        }
    }
    public static void scanSavedMediaFile(final Context context,
            final String path) {
        scanSavedMediaFile(context, path, null);
    }
}

Related Tutorials