问题描述
我需要监视的文件夹中的所有文件,当文件打开(FileObserver.OPEN)我想执行的方法。问题是有些时候,FileObserver实例由GC回收,我想这样的:
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();
不过被收集。现在的问题是,什么是FileObserver的实例,不收取?
But is being collected.The question is, what is the best solution for a instance of FileObserver not be collected?
TKS !!!
推荐答案
我猜startWatching()方法立即返回,你的线程完成运行,和你的方法返回。在这一点上,你的FileObserver,作为一个局部变量,是不可见的,从任何地方。你的线程运行完毕,也没有提到它。两者都是垃圾收集。定义FileObserver为静态变量或者未垃圾回收,而不是在方法的局部变量的东西字段。
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.
这篇关于FileObserver实例将被垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!