310

我正在开发一个带有服务的 Android 2.3.3 应用程序。我在该服务中有这个与主要活动进行通信:

public class UDPListenerService extends Service
{
    private static final String TAG = "UDPListenerService";
    //private ThreadGroup myThreads = new ThreadGroup("UDPListenerServiceWorker");
    private UDPListenerThread myThread;
    /**
     * Handler to communicate from WorkerThread to service.
     */
    private Handler mServiceHandler;

    // Used to receive messages from the Activity
    final Messenger inMessenger = new Messenger(new IncomingHandler());
    // Use to send message to the Activity
    private Messenger outMessenger;

    class IncomingHandler extends Handler
    {
        @Override
        public void handleMessage(Message msg)
        {
        }
    }

    /**
     * Target we publish for clients to send messages to Incoming Handler.
     */
    final Messenger mMessenger = new Messenger(new IncomingHandler());
    [ ... ]
}

在这里,final Messenger mMessenger = new Messenger(new IncomingHandler());我收到以下 Lint 警告:

This Handler class should be static or leaks might occur: IncomingHandler

这是什么意思?

4

7 回答 7

398

如果IncomingHandler类不是静态的,它将引用您的Service对象。

Handler同一个线程的对象都共享一个共同的 Looper 对象,它们向该对象发送消息并从中读取。

由于消息中包含 target Handler,所以只要消息队列中有带有 target handler 的消息,就不能对 handler 进行垃圾回收。如果处理程序不是静态的,即使在被销毁之后,您的ServiceActivity不能被垃圾收集。

这可能会导致内存泄漏,至少在一段时间内 - 只要消息留在队列中。除非您发布长时间延迟的消息,否则这不是什么大问题。

您可以制作IncomingHandler静态并WeakReference为您的服务提供:

static class IncomingHandler extends Handler {
    private final WeakReference<UDPListenerService> mService; 

    IncomingHandler(UDPListenerService service) {
        mService = new WeakReference<UDPListenerService>(service);
    }
    @Override
    public void handleMessage(Message msg)
    {
         UDPListenerService service = mService.get();
         if (service != null) {
              service.handleMessage(msg);
         }
    }
}

请参阅Romain Guy 的这篇文章以获取更多参考

于 2012-07-10T07:13:38.647 回答
73

正如其他人提到的那样,Lint 警告是因为潜在的内存泄漏。Handler.Callback您可以通过在构造时传递 a 来避免 Lint 警告Handler(即您没有子类Handler并且没有Handler非静态内部类):

Handler mIncomingHandler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        // todo
        return true;
    }
});

据我了解,这不会避免潜在的内存泄漏。Message对象持有对对象的引用,mIncomingHandler对象持有引用,Handler.Callback对象持有对对象的引用Service。只要Looper消息队列中有消息,Service就不会被GC。但是,除非您在消息队列中有长时间延迟的消息,否则这不会是一个严重的问题。

于 2013-02-11T00:55:56.540 回答
33

这是一个使用弱引用和静态处理程序类来解决问题的通用示例(如 Lint 文档中所建议的那样):

public class MyClass{

  //static inner class doesn't hold an implicit reference to the outer class
  private static class MyHandler extends Handler {
    //Using a weak reference means you won't prevent garbage collection
    private final WeakReference<MyClass> myClassWeakReference; 

    public MyHandler(MyClass myClassInstance) {
      myClassWeakReference = new WeakReference<MyClass>(myClassInstance);
    }

    @Override
    public void handleMessage(Message msg) {
      MyClass myClass = myClassWeakReference.get();
      if (myClass != null) {
        ...do work here...
      }
    }
  }

  /**
   * An example getter to provide it to some external class
   * or just use 'new MyHandler(this)' if you are using it internally.
   * If you only use it internally you might even want it as final member:
   * private final MyHandler mHandler = new MyHandler(this);
   */
  public Handler getHandler() {
    return new MyHandler(this);
  }
}
于 2015-01-07T18:25:07.773 回答
27

这种方式对我来说效果很好,通过将处理消息的位置保持在其自己的内部类中来保持代码清洁。

您希望使用的处理程序

Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());

内部类

class IncomingHandlerCallback implements Handler.Callback{

        @Override
        public boolean handleMessage(Message message) {

            // Handle message code

            return true;
        }
}
于 2013-04-17T23:16:47.073 回答
2

在@Sogger's answer的帮助下,我创建了一个通用处理程序:

public class MainThreadHandler<T extends MessageHandler> extends Handler {

    private final WeakReference<T> mInstance;

    public MainThreadHandler(T clazz) {
        // Remove the following line to use the current thread.
        super(Looper.getMainLooper());
        mInstance = new WeakReference<>(clazz);
    }

    @Override
    public void handleMessage(Message msg) {
        T clazz = mInstance.get();
        if (clazz != null) {
            clazz.handleMessage(msg);
        }
    }
}

界面:

public interface MessageHandler {

    void handleMessage(Message msg);

}

我使用它如下。但我不是 100% 确定这是否是安全的。也许有人可以对此发表评论:

public class MyClass implements MessageHandler {

    private static final int DO_IT_MSG = 123;

    private MainThreadHandler<MyClass> mHandler = new MainThreadHandler<>(this);

    private void start() {
        // Do it in 5 seconds.
        mHandler.sendEmptyMessageDelayed(DO_IT_MSG, 5 * 1000);
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case DO_IT_MSG:
                doIt();
                break;
        }
    }

    ...

}
于 2017-03-27T13:40:04.987 回答
0

我不确定,但您可以尝试在 onDestroy() 中将处理程序初始化为 null

于 2015-01-07T09:25:08.470 回答
0

我很困惑。我发现的示例完全避免了静态属性并使用 UI 线程:

    public class example extends Activity {
        final int HANDLE_FIX_SCREEN = 1000;
        public Handler DBthreadHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                int imsg;
                imsg = msg.what;
                if (imsg == HANDLE_FIX_SCREEN) {
                    doSomething();
                }
            }
        };
    }

我喜欢这个解决方案的一点是尝试混合类和方法变量没有问题。

于 2020-01-10T03:46:04.780 回答