使用WeakReferenced侦听器

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!");
          }
      };


   }
}
Run Code Online (Sandbox Code Playgroud)

对不起,如果有拼写错误/语法错误,这更像是伪代码.

无论如何,在"Action"完成的时候很多时候,即使"AnotherClass"的实例仍然存在,WeakReference to listener也会被GCed.有办法避免这种情况吗?

spa*_*ici 6

让AnotherClass实现Listener或者在里面有一个私有实例.IE:

Listener myListener = new Listener() {
  public void onListed() {
    ....
  }
};
Run Code Online (Sandbox Code Playgroud)

对侦听器的AnotherClass引用将使其引用保持活动状态(直到程序中有AnotherClass引用)