同一线程的 Handler 对象都共享一个公共的 Looper 对象,它们向其发送消息并从中读取消息.由于消息包含目标Handler,只要消息队列中有带有目标处理器的消息,处理器就不能被垃圾回收.如果 handler 不是静态的,你的 Service 或 Activity 不能被垃圾回收,即使在被销毁之后也是如此.这可能会导致内存泄漏,至少在一段时间内 - 只要消息保持在队列中.除非您发布延迟很长时间的消息,否则这不是什么大问题.您可以将 IncomingHandler 设为静态,并为您的服务设置一个 WeakReference:static class IncomingHandler extends Handler {私有最终 WeakReference移动服务;IncomingHandler(UDPListenerService 服务){mService = new WeakReference(service);}@覆盖公共无效handleMessage(消息消息){UDPListenerService 服务 = mService.get();如果(服务!= null){service.handleMessage(msg);}}}请参阅 Romain Guy 的 帖子以进一步参考I'm developing an Android 2.3.3 application with a service. I have this inside that service to communicate with Main activity: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()); [ ... ]}And here, final Messenger mMessenger = new Messenger(new IncomingHandler());, I get the following Lint warning:This Handler class should be static or leaks might occur: IncomingHandlerWhat does it mean? 解决方案 If IncomingHandler class is not static, it will have a reference to your Service object.Handler objects for the same thread all share a common Looper object, which they post messages to and read from.As messages contain target Handler, as long as there are messages with target handler in the message queue, the handler cannot be garbage collected. If handler is not static, your Service or Activity cannot be garbage collected, even after being destroyed.This may lead to memory leaks, for some time at least - as long as the messages stay int the queue. This is not much of an issue unless you post long delayed messages.You can make IncomingHandler static and have a WeakReference to your service: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); } }}See this post by Romain Guy for further reference 这篇关于这个 Handler 类应该是静态的,否则可能会发生泄漏:IncomingHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
05-18 21:40