Jul 30, 2012

Force MediaScannerConnection to rescan updated media file

MediaScannerConnection provides a way for applications to pass a newly created or downloaded media file to the media scanner service. The media scanner service will read metadata from the file and add the file to the media content provider. The MediaScannerConnectionClient provides an interface for the media scanner service to return the Uri for a newly scanned file to the client of the MediaScannerConnection class.

MediaScannerConnectionClient provide an interface for notifying clients of MediaScannerConnection when a connection to the MediaScanner service has been established and when the scanning of a file has completed.


In the article "Set latitude and longitude in Exif, setAttribute() and saveAttributes()", the updated GPS Tags in Exif cannot be recognized by build-in Gallery app after updated, untill system system re-boot! It's because the system MediaStore not yet known it. In order to force MediaStore to re-scan the updated file, we can call pass the updated media file to MediaScannerConnection.

 public static void scanFile(Context context, String path, String mimeType ) {
  Client client = new Client(path, mimeType);
     MediaScannerConnection connection = new MediaScannerConnection(context, client);
     
     client.connection = connection;
     connection.connect();
 }

 private static final class Client implements MediaScannerConnectionClient {
     private final String path;
     private final String mimeType;
     MediaScannerConnection connection;

     public Client(String path, String mimeType) {
         this.path = path;
         this.mimeType = mimeType;
     }
     
     @Override
     public void onMediaScannerConnected() {
         connection.scanFile(path, mimeType);
     }

     @Override
     public void onScanCompleted(String path, Uri uri) {
         connection.disconnect();    
     }
 }


Call scanFile(<context>, <path>, null) to scan the file.
If mimeType is null, then the mimeType will be inferred from the file extension.

Reference: http://stackoverflow.com/questions/5107823/force-scan-files-after-taking-photo


No comments:

Post a Comment

Infolinks In Text Ads