5

这是我的代码:

public class SyncNotifyService extends Service {
    private final static String TAG = "FileService";
    SDCardListener fileObserver = null;


@Override
public IBinder onBind(Intent intent) {
    return null;
}

public File getCacheDir() {
    if (!StorageUtil.isExternalStorageAvailable()) {
        return null;
    }

    File dir = new File(Environment.getExternalStorageDirectory(), "Cache");
    return dir;
}

@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "onCreate");

    fileObserver = new SDCardListener(FileCache.getCacheDir().getPath(), FileObserver.MODIFY);
    fileObserver.startWatching();
}

class SDCardListener extends FileObserver {
    public SDCardListener(String path, int mask) {
        super(path, mask);
    }

    @Override
    public void onEvent(int event, String path) {
        final int action = event & FileObserver.ALL_EVENTS;
        switch (action) {
        case FileObserver.MODIFY:
            Log.d(TAG, "event: MODIFY");
            break;
        }
    }
}

}

嗨,我使用此代码通知目录。但我发现它从不调用 onEvent 使用 FileObserver.MODIFY 参数,有人知道如何编写正确的代码吗?我的安卓版本是 4.1.1

4

3 回答 3

0

When you create the FileObserver the path should be absolute to the directory containing the file that you are observing:

fileObserver = new SDCardListener(FileCache.getCacheDir().getAbsolutePath(), FileObserver.MODIFY);

Also, change this:

 public void onEvent(int event, String path) {

    switch (action) {
    case FileObserver.MODIFY:
        Log.d(TAG, "event: MODIFY");
        break;
    }
}

If onEvent is not triggered, try to change how you initialize the FileObserver so that it listents to ALL_EVENTS and print the event that is trigger. Then you can figure out why MODIFY is not trigger.

于 2014-01-09T20:21:40.943 回答
0

也许您编写 onEvent 的方式不合适,请使用

if (!event.equals(MODIFY)) { return;} 

//the code you want 
if (path.equals(blah blah blah)) {
//some code.. 
}

这是我在 FileObserver 中使用的方式,试试吧...

于 2013-06-25T15:17:43.847 回答
0

FileObserver根本不是递归的!

检查这个:

https://code.google.com/p/android/issues/detail?id=33659

我建议使用RecursiveFileObserver类:

https://github.com/owncloud/android/blob/master/src/com/owncloud/android/utils/RecursiveFileObserver.java

于 2015-05-27T18:17:00.417 回答