ContentObserver onChange() 方法被调用很多次



我需要跟踪在设备上创建的任何.jpg类型的新图像文件。 我已经使用ContentObserverMediaStore使用下面的类MediaStoreObserver来做到这一点,并且, 在我的一项服务中注册相同的内容。

我注意到onChange()方法在单个文件创建中被多次调用。 我知道创建的媒体文件在许多MediaStore表中更新,因此onChange()被多次调用。

我的问题:如何注册MediaStore仅图像文件创建/编辑操作?

-提前感谢, 馒头

private class MediaStoreObserver extends ContentObserver {
public MediaStoreObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
//check image file changes in MediaStore
readFromMediaStore(_context,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
}
//register for external media changes for image files
if(mediaStoreObserver!=null){
_context.getContentResolver().registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
false,mediaStoreObserver);

简短回答:你不能,它是提供者发送notifyChange(与观察者一起接收onChange)每当有内容时:更新/插入/删除

更长的答案:这是为了实现您想要的(如何注册到MediaStore进行仅图像文件创建/编辑操作?

启动时从MediaStore读取图像表,并将_data列(文件路径)存储在排序collection中,这是一个带有路径(字符串)的排序collection。每当您收到onChange调用时,请创建上述排序的新集合,然后循环新集合并搜索您创建的原始集合,使用二进制搜索(因为集合已排序,我们希望保持较低的时间复杂度)。这将导致一个运行时间为 O(n*logn) 的相当有效的实现。

或者在伪代码中:

1. Read current image columns from media store (the `_data column as projection)
2. Store result in a collection, with string type
3. Sort collection
4. Upon `onChange` is received, make a new collection as step 1-3
5. Loop over collection created in 4 and search each string you take out with 
binary search in the sorted collection you got from step 3, if item is not found 
then the item is new
6. Make the collection in 4 the current cached version of mediastore 
7. Time complexity is O(n*log n) for the above algorithm 

编辑更新的文件部分,每当我在步骤 5 中的搜索命中时,我都会从 MediaStore 读取修改日期字段,这意味着您实际上应该将文件(uri) 和修改日期存储在数据类中,但作为搜索查找使用文件路径。每当找到文件时,您都应该检查修改的日期是否匹配,如果不匹配,那么它是一个更新的文件。

我遇到了同样的问题,并通过从onchange覆盖中删除super.onchange来修复它。

@Override
public void onChange(boolean selfChange, @Nullable Uri uri) {
super.onChange(selfChange, uri);
if (uri == null) return;
if (!uri.equals(Uri.parse("content://settings/system/volume_music_speaker"))) 
return;
//your code here...
} 

最新更新