How to listen new photos in android?

Deadly 提交于 2019-12-13 11:48:31

问题


I need to listen to new images that comes from any source like downloading images, capture new images, other apps download images..etc Is there any listener that will trigger event whenever new photos is added to gallery? I have been searching for two days. I could not get anything solid.

I read about FileObserver, will that help?


回答1:


new photos arrives to gallery

means it has been added to the MediaStore.

First of all, FileOberver is a memory-killer approach. Consider a high volume of files. Rather ContentObserver seems a far 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;
}

Probably a good idea to do this in a service (ever running)! You will also need to unregister in the onDestroy()

Warning: This only tells you when the MediaStore has been changed, it does not tellly anything specific about addition/deletion. For this, you may have to query the MediaStore to detect any change from your previous database or something.



来源:https://stackoverflow.com/questions/35859816/how-to-listen-new-photos-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!