I am downloading a file from within a Fragment
asynchronously and would like to call MediaScannerConnection.scanFile()
when the download completes. I am able to get desired results if I sit and wait for the download to finish without navigating away from my Fragment (or its hosting activity). The problem I am facing is that MediaScannerConnection.scanFile()
requires a context and I don't want to limit the user to staying within a Fragment
/Activity
just so that context is not null.
How do I make use of MediaScannerConnection.scanFile()
in the background so that I can scan the files and display a Toast
when the scanning is complete while still navigating in other parts of my app (or even tabbing out of my app)?
This is how I am currently scanning (with a context):
public static void mediaScanFile(Context context, String path) {
MediaScannerConnection.scanFile(context,
new String[]{path}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.d("Tag", "Scan finished. You can view the image in the gallery now.");
}
});
}
First of all, downloading a file from a Fragment
which may be destroyed soon is not a good idea. You should use foreground service instead.
If you still want to stick with fragments, in your case, you can make use of the application context.
Before starting the download, store a reference of the application context as a field in your fragment.
Context appContext;
// Inside onCreateView
appContext = getContext().getApplicationContext();
Then you can use the application context for scanning media.
This won't cause memory leak because the application context is a single shared instance and won't be destroyed until the app is killed.