FileObserver doesn't work
Asked Answered
O

4

3

In my Android app I want to detect events from directory. Here is code:

String path = Environment.getExternalStorageDirectory()
            + File.separator + "test2";
    Log.d("test", "path is " + path);

    FileObserver fileObserver = new FileObserver(path, FileObserver.ALL_EVENTS) {
        @Override
        public void onEvent(int event, String path) {
            Log.d("test", "event dectect " + event + " " + path);
        }
    };

    fileObserver.startWatching();

I copy new file to the directory. But I don't get any event. Please show me where I made a mistake.

Oblique answered 5/9, 2015 at 4:55 Comment(2)
probably Activity is in Pause or Stop state when copying new file in directory. so try it by copying file in directory from adb shell without minimizing ActivityMaryleemarylin
I copied the new file using wife transfer ( I uploaded it from my computer). So I don't think the Activity is in Pause or Stop.Oblique
C
18

You cannot use a local variable to store your FileObserver, it would be available for garbage collection after the method is run.

Warning: If a FileObserver is garbage collected, it will stop sending events. To ensure you keep receiving events, you must keep a reference to the FileObserver instance from some other live object.

Solution: save it to a field.

Cofer answered 5/9, 2015 at 5:10 Comment(0)
L
1

Adding storage permission worked for me.

Lomax answered 31/5, 2018 at 12:31 Comment(0)
P
0

It seems that FileObserver does not work on symbolic links, which is what is returned by Environment.getExternalStorage().

The trick for me was to resolve the links using File.getCanonicalPath()

Example:

File file = new File(Environment.getExteranlStorage(), "myfile");
new FileObserver(file.getCanonicalPath()) ...
Parolee answered 31/5, 2016 at 21:16 Comment(0)
E
0

Expanding on @user3219477's answer be sure to go in to Settings->Apps->YourApp and grant Storage permission if you aren't requesting it dynamically in your app.

Ezequieleziechiele answered 11/10, 2021 at 15:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.