4

I need to monitor all files in a folder, when a file opened (FileObserver.OPEN) I want to execute a method. The problem is some times, the FileObserver instance is collected by GC, I tried this:

    final MyFileObserver fo = new MyFileObserver("/mnt/sdcard/Musicas");
    threadFileObserver = new Runnable() {
        @Override
        public void run() {
            fo.startWatching();
        }
    };
    t = new Thread(threadFileObserver);
    t.run();

But is being collected. The question is, what is the best solution for a instance of FileObserver not be collected?

tks!!!

danilodeveloper
  • 3,840
  • 2
  • 36
  • 56

2 Answers2

4

I'm guessing the startWatching() method returns immediately, your Thread finishes running, and your method returns. At this point, your FileObserver, being a local variable, is not visible from anywhere. Your thread has finished running and there is no reference to it. Both are garbage collected. Define the FileObserver as a static variable or a field in something that isn't garbage collected, not as a local variable in a method.

juell
  • 4,930
  • 4
  • 18
  • 19
  • Where did you declare the static? – juell May 25 '11 at 13:35
  • Also, are you trying to keep track of what happens to the file even if your app UI is not showing? What is the motivation behind what you are trying to do? – juell May 25 '11 at 13:37
  • In main Activity. I think I need to keep the the Activity running in a background process or something like. – danilodeveloper May 25 '11 at 13:38
  • Did you exit the Activity in the meantime? – juell May 25 '11 at 13:40
  • Yes, sometimes the user execute other application acessing by the main Android menu. I think this moment my instance is being collected. I tryied create a service and start the FileObserver instance, but not work. – danilodeveloper May 25 '11 at 13:55
  • OhHiThere, your answers helped me to find a path to the possible solution. tks man!!! – danilodeveloper May 25 '11 at 14:12
  • Glad you figured it out. Did you put it in a service? – juell May 25 '11 at 15:59
  • 1
    Yes, I created a service running in a background process, the listener of FileObserver is started after the service start up. With this solution the FileObserver not collected anymore. Tks for your help!!! – danilodeveloper May 25 '11 at 16:34
  • 1
    Could you post the solution? That would really help others including me. Thank you! – shanabus Sep 01 '11 at 03:17
1

Keep fo in the application scope by making it a global variable of your main/UI Activity.

Haphazard
  • 10,900
  • 6
  • 43
  • 55