FileObserver CREATE or DELETE received only for files

限于喜欢 提交于 2019-12-03 07:23:15
Eugene Loy

The reason of this is that android does not abstract over underlying file system well enough and returns underlying event code with some of the flags raised (some of the higher bits of the event). This is why comparing the event value with the event type directly does not work.

To solve this you can drop extra flags by applying FileObserver.ALL_EVENTS event mask (using bitwise and) to actual event value stripping it down to event type.

Using the code you've provided in your question this will look something like this:

private final class DirectoryObserver extends FileObserver {

    private DirectoryObserver(String path, int mask) {
        super(path, mask);
    }

    @Override
    public void onEvent(int event, String pathString) {
        event &= FileObserver.ALL_EVENTS;
        switch (event) {
            case FileObserver.DELETE_SELF:
                //do stuff
                break;

            case FileObserver.CREATE:
            case FileObserver.DELETE:
                //do stuff
                break;
        }
    }
}

I've tested on two devices, one with Ice Cream Sandwich and one with Lollipop. They always come out with the same int, so I just defined two new constants:

/**
 * Event type: A new subdirectory was created under the monitored directory<br>
 * For some reason this constant is undocumented in {@link FileObserver}.
 */
public static final int CREATE_DIR = 0x40000100;
/**
 * Event type: A subdirectory was deleted from the monitored directory<br>
 * For some reason this constant is undocumented in {@link FileObserver}.
 */
public static final int DELETE_DIR = 0x40000200;

Both of these are successfully received when filtering for CREATE and DELETE.

Pasquale Anatriello

Ther's an issue on that. Seems the doc is wrong https://code.google.com/p/android/issues/detail?id=33659

on this answer Android: FileObserver monitors only top directory someone published a recursive file observer that should work for you

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!