Android How to use MediaScannerConnection scanFile
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
How to use MediaScannerConnection scanFile?
MediaScannerConnection.scanFile(this, new String[]{file.getPath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// now visible in gallery
}
});
MediaScannerConnection.scanFile() returning null uri
I can't seem to figure out why it can't return a valid uri if the file is being saved in the phone and the path is a valid one
It is valid. However, it is not indexable by MediaStore
on Android 10 and higher. MediaStore
will no longer index files in app-specific external storage, such as getExternalFilesDir()
, which is what you are using.
If your objective is to have the image be usable by every app on the device, then getting indexed by MediaStore
is fine. On Android 10+, you can insert()
into the MediaStore
and use the resulting Uri
for writing out your content. See this sample app for a demonstration, though in my case I am writing out a video, not a PNG.
If, instead, all you want to do is share this content, then do not use MediaScannerConnection
. Instead, use FileProvider
. See the documentation and this sample app (though in my case I am sharing a PDF, not a PNG).
Using MediaScannerConnection.scanFile() in a fragment?
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.
Related Topics
Understanding Fragment'S Setretaininstance(Boolean)
Facebook Android Generate Key Hash
Determining the Current Foreground Application from a Background Task or Service
Android Studio Adds Unwanted Permission After Running Application on Real Device
How to Update Gradle in Android Studio
How to Use Recyclerview Inside Nestedscrollview
How to Use Drawerlayout to Display Over the Actionbar/Toolbar and Under the Status Bar
How to Run a Runnable Thread in Android At Defined Intervals
Repeat a Task With a Time Delay
"R Cannot Be Resolved to a Variable"
Filter Logcat to Get Only the Messages from My Application in Android
How to Use Inputfilter to Limit Characters in an Edittext in Android
Service VS Intentservice in the Android Platform
How to Connect to Android With Adb Over Tcp