如何解决FileObserver收到奇怪事件
| 好的,这很简单:我有一个FileObserver类,用于观察带有音乐的文件夹。因此,我实现了onEvent和所有这些东西,但是当我使用文件管理器将文件移动或粘贴到该文件夹时,而不是获取FileObserver.MOVED_TO或FileObserver.CREATE,我得到的是奇怪的事件,其编号为1073741656,没有记录在: http://developer.android.com/reference/android/os/FileObserver.html 那么,如何获得这些特定事件,例如删除,移动,创建和粘贴? [编辑] 这是代码: private class MusicsFileObserver extends FileObserver {
public MusicsFileObserver(String root) {
super(root);
if (!root.endsWith(File.separator)) {
root += File.separator;
}
}
@SuppressWarnings(\"unused\")
public void close() {
super.finalize();
}
public void onEvent(final int event,String path) {
//here is the problem,if you see the documentation,when a file is moved
//to this directory,event should be equal to FileObserver.MOVED_TO,//a constant value of 128. But when debugging,instead of entering here one time
//with event == 128,this method onEvent is being called 4~5 times with event
//with numbers like 1073741656
if (event != FileObserver.ACCESS || event != FileObserver.OPEN || event != 32768)
runOnUiThread(new Runnable() {
public void run() {
rescanMusics();
}
});
}
}
解决方法
对于遇到此问题的其他人,我发现MOVED_TO和MOVED_FROM事件的高位在事件标志中处于打开状态。 MOVED_FROM为0x40000040,MOVED_TO为0x40000080。解决方法是简单地用事件代码“和” ALL_EVENTS并关闭高位,即“ event&= FileObserver.ALL_EVENTS \”
更新:我找到了可以从http://rswiki.csie.org/lxr/http/source/include/linux/inotify.h?a=m68k#L45获得的inotify标志,如果google添加了这些标志,那就太好了FileObserver文档的位标志。
, 观察者事件类型如下:
public void onEvent(int event) {
if ((FileObserver.CREATE & event)!=0) {
// do what ever you want.
} else if ((FileObserver.MODIFY & event)!=0) {
// do what ever you want.
} ...... etc
}
, 如果其他人来自Google,请从文档中了解这一点:
startWatching()
开始观看事件。监视的文件或目录此时必须存在,否则将不报告任何事件
(即使稍后出现)。如果已经开始监视,则此
通话无效。
, 尝试在Application类中链接对Observer的引用。
像这样
private ArrayList<FileObserver> mObservers = new ArrayList<FileObserver>();
public void addObserver(FileObserver observer){
mObservers.add(observer);
}
public void removeObserver(FileObserver observer){
mObservers.remove(observer);
}
这对我有用!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。