I\'m using this code to copy an image using documentFile.createFile()
private void newcopyFile(File fileInput, String outputParentPath,
You could use this or this is how I've implemented a listener(observer) to ContentResolver
changes, using ContentObserver
to know when is the appropriate time to run a query for getting newly created image from ContentResolver
.
First create ContentObserver
Class:
This class as its name tells us, observes any content changes in our desired Uri.
class MyObserver extends ContentObserver {
public MyObserver(android.os.Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
this.onChange(selfChange, null);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
//(SDK>=16)
// do s.th.
// depending on the handler you might be on the UI
// thread, so be cautious!
// This is my AsyncTask that queries ContentResolver which now
// is aware of newly created media file.
// You implement your own query here in whatever way you like
// This query will contain info for newly created image
asyncTaskGetPhotosVideos = new AsyncTaskGetPhotosVideos();
asyncTaskGetPhotosVideos.execute();
}
}
and at the end of your copy method, you could set ContentObserver
to your ContentResolver
on specific Uri.
getContentResolver().registerContentObserver(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
true,
myObserver);
and don't forget to unregister your observer otherwise you will face memory leak. I would prefer to do it at the end of my AsyncTask (onPostExecute).
getContentResolver().unregisterContentObserver(myObserver);
You could choose to have a ContentObserver
on your desired Uri through your entire app lifecycle to get notified whenever a media got changed, deleted or inserted from outside or within your app.
For this approach, you could register your observer in the onResume()
lifecycle method and unregister it in the onPause()
method.
Sorry i posted wrong code
When you add files to Android’s filesystem these files are not picked up by the MedaScanner automatically. But often they should be.
So to add a file to content provider manually
So use this code :-
Intent intent =
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
For more methods of doing this and for reference visit this site:-
http://www.grokkingandroid.com/adding-files-to-androids-media-library-using-the-mediascanner/