2014-01-22

Force Android MTP database refresh if file in storage changed

Method 1.
Old method, not recommended.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Force whole SDCard rescan.
Side-effect: Some devices will force close or cause System UI exception.

Method 2.
Send intent to scan specific file
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
You need a for loop or recursive call if your target is a directory.

Method 3.
Similar with method 2, but do your Media scan by yourself.
public class MediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mScanner;
private File mFile;
public MediaScanner(Context context, File file) {
   mFile = file;
   mScanner = new MediaScannerConnection(context, this);
   mScanner.connect();
}
@Override
public void onMediaScannerConnected() {
   mScanner.scanFile(mFile.getAbsolutePath(), null);
}
@Override
public void onScanCompleted(String path, Uri uri) {
   mScanner.disconnect();
}
}
public class YourClass {
    ...
    new MediaScanner(context, file);
    ...
}
Same as method 2, you need a for loop or recursive call if your target is a directory.
Suggest to use Thread or ExecutorService for a better performance.

No comments: