好的,这很简单:我有一个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();
}
});
}
}
答案 0 :(得分:11)
对于遇到此问题的任何其他人,我发现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标记,如果谷歌将这些位标记添加到FileObserver文档中会很好。
答案 1 :(得分:4)
观察者事件类型如下:
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
}
答案 2 :(得分:1)
如果其他人来自Google,请注意the documentation:
startWatching()
开始观看活动。 此时必须存在受监视的文件或目录,否则不会报告任何事件 (即使它稍后出现)。如果监控已经开始,这个 电话没有效果。
答案 3 :(得分:0)
尝试在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);
}
这对我有用!