Sta*_*wed 2 java android garbage-collection
假设如下:
public interface Listener {
   public void onListen();
}
public class ActionClass {
   WeakReference<Listener> listener = null;
   public void doAction(String action, Listener listener) {
      this.listener = new WeakReference<Listener>(listener);
      doTheAction(action);
   }
   public void actionComplete() {
     if (listener != null && listener.get() != null)
          listener.onListen();
   } 
}
public class AnotherClass {
   ActionClass actioner = new ActionClass();
   void init()  {
      actioner.doAction("something", new Listener() {
          onListened() {
              Log.d("Tag", "Action complete!");
          }
      };
   }
}
对不起,如果有拼写错误/语法错误,这更像是伪代码.
无论如何,在"Action"完成的时候很多时候,即使"AnotherClass"的实例仍然存在,WeakReference to listener也会被GCed.有办法避免这种情况吗?
让AnotherClass实现Listener或者在里面有一个私有实例.IE:
Listener myListener = new Listener() {
  public void onListed() {
    ....
  }
};
对侦听器的AnotherClass引用将使其引用保持活动状态(直到程序中有AnotherClass引用)
| 归档时间: | 
 | 
| 查看次数: | 84 次 | 
| 最近记录: |