MediaScanner, onScanCompleted is not called
-
22-07-2021 - |
Pregunta
I have a problem with MediaScanner. I use it to scan a single File with this code:
public class SingleMediaScanner implements MediaScannerConnectionClient {
private static final String TAG = "SingleMediaScanner";
public MediaScannerConnection mMs;
private String mFile;
public SingleMediaScanner(Context context, String s) {
mFile = s;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
public void onMediaScannerConnected() {
Log.d(TAG, "MediaScanner conectado");
mMs.scanFile(mFile, null);
}
public void onScanCompleted(String path, Uri uri) {
Log.d(TAG, "MediaScanner terminó de escanear");
mMs.disconnect();
}
}
If I scan a file at the beginning of an activity (onCreate), it works perfect. The scanner is connected, it scans the file and after that, is completed.
But if I call the scanner and then I go to another activity, the MediaScanner leaks memory because it doesn't call the onScanCompleted method. And if I use unbindService() with the scanner before leaving the activity, the scanner doesn't work (the file doesn't appear in the gallery app).
I need to use the scanner when I leave the activity. What can I do?
Solución
There are other ways to add the file to the Gallery by using the static scanFile() method or by sending a BroadCast. Normally these should suit your need fine. You only need a MediaScannerConnection if you need some control over the addition process.
I have written a blog post about how to use the other methods to trigger the MediaScanner.