Moon Light Box

Time is Money

Android - FileObserver Cannot Work in KitKat and Lollipop

| Comments

From Android Developers, we can use FileObserver to know files or folders changed on sdcard.

We usually use this to implement.

public class StorageMonitor extends FileObserver {
    public StorageMonitor(String path) {
        super(path);
    }

    @Override
    public void onEvent(int event, String path) {
        switch (event) {
            case FileObserver.ACCESS:
                Log.i("FileObserver", "ACCESS: " + path);
                break;
            case FileObserver.ATTRIB:
                Log.i("FileObserver", "ATTRIB: " + path);
                break;
            case FileObserver.CLOSE_NOWRITE:
                Log.i("FileObserver", "CLOSE_NOWRITE: " + path);
                break;
            case FileObserver.CLOSE_WRITE:
                Log.i("FileObserver", "CLOSE_WRITE: " + path);
                break;
            case FileObserver.CREATE:
                Log.i("FileObserver", "CREATE: " + path);
                break;
            case FileObserver.DELETE:
                Log.i("FileObserver", "DELETE: " + path);
                break;
            case FileObserver.DELETE_SELF:
                Log.i("FileObserver", "DELETE_SELF: " + path);
                break;
            case FileObserver.MODIFY:
                Log.i("FileObserver", "MODIFY: " + path);
                break;
            case FileObserver.MOVE_SELF:
                Log.i("FileObserver", "MOVE_SELF: " + path);
                break;
            case FileObserver.MOVED_FROM:
                Log.i("FileObserver", "MOVED_FROM: " + path);
                break;
            case FileObserver.MOVED_TO:
                Log.i("FileObserver", "MOVED_TO: " + path);
                break;
            case FileObserver.OPEN:
                Log.i("FileObserver", "OPEN: " + path);
                break;
            default:
                Log.i("FileObserver", "DEFAULT(" + event + "): " + path);
                break;
        }
    }
}

And start StorageMonitor in onCreat().

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
    StorageMonitor storageMonitor = new StorageMonitor(sdcard);
    storageMonitor.startWatching();
}

Launched application and modified files/folders on sdcard. Then I cannot see any event printed in logcat. I tried several Android Phones and versions (HTC ONE X 4.2.2, Samsung Note3 4.4.2, Google Nexus5 5.0...etc). FileObserver worked well in some Android Phones, for example, HTC ONE X 4.2.2 always passed.

Last, I try to use other constructor of FileObserver. It works for all!!

public StorageMonitor(String path) {
    super(path, FileObserver.ALL_EVENTS);
}

God, is this Google bug?

Comments

comments powered by Disqus