How to listen to new photos in android?

My application processes images, I can process already saved images on an Android device. I also want to process new images. Is there any listener who will notify me when new photos arrive in the gallery? I searched for two days. I could not get anything solid.

I read about FileObserver , will this help me listen to both users uploading images and new photos using the camera?

+5
source share
1 answer

new photos arrive at the gallery

means it has been added to MediaStore .

First of all, FileOberver is a killer memory approach. Consider a large file size. Rather, ContentObserver seems to be a much better approach.

 getContentResolver().registerContentObserver(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, true, new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { Log.d("your_tag","Internal Media has been changed"); super.onChange(selfChange); Long timestamp = readLastDateFromMediaStore(context, MediaStore.Images.Media.INTERNAL_CONTENT_URI); // comapare with your stored last value and do what you need to do } } ); getContentResolver().registerContentObserver(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { Log.d("your_tag","External Media has been changed"); super.onChange(selfChange); Long timestamp = readLastDateFromMediaStore(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // comapare with your stored last value and do what you need to do } } ); private Long readLastDateFromMediaStore(Context context, Uri uri) { Cursor cursor = context.getContentResolver().query(uri, null, null, null, "date_added DESC"); PhotoHolder media = null; Long dateAdded =-1; if (cursor.moveToNext()) { Long dateAdded = cursor.getLong(cursor.getColumnIndexOrThrow(MediaColumns.DATE_ADDED)); } cursor.close(); return dateAdded; } 

It is probably a good idea to do this in a service (ever running)! You will also need to unregister onDestroy()

A warning. This only says when the MediaStore was changed, it does not say anything special about adding / removing. To do this, you may need to query MediaStore to detect any changes from your previous database or something like that.

+8
source

Source: https://habr.com/ru/post/1244631/


All Articles