Man*_*nju 8 android contentobserver
我要求跟踪在设备上创建的.jpg类型的新图像文件.我一直在使用这样做ContentObserver在MediaStore使用下面的类MediaStoreObserver,并且注册了相同的我的服务之一.
我注意到,onChange()为单个文件创建多次调用该方法.我知道创建的媒体文件会在许多表中更新,MediaStore因此onChange()会被多次调用.
我的问题:如何注册MediaStore仅用于图像文件创建/编辑操作?
- 提前谢谢,Manju
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);
Run Code Online (Sandbox Code Playgroud)
简短的回答:你不能,每当有更新/插入/删除时,都是由提供者发送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
Run Code Online (Sandbox Code Playgroud)
编辑更新的文件部分,每当步骤 5 中的搜索命中时,我都会从 MediaStore 读取修改日期字段,这意味着您实际上应该将文件 (uri) 和修改日期存储在数据类中,但作为搜索查找使用文件小路。每当找到文件时,您应该检查修改日期是否匹配,如果不匹配,则它是更新的文件。
| 归档时间: |
|
| 查看次数: |
3547 次 |
| 最近记录: |