这个处理程序类应该是静态的或可能发生泄漏:IncomingHandler [英] This Handler class should be static or leaks might occur: IncomingHandler
问题描述
我开发一个Android 2.3.3应用程序与服务。我有这样的服务中与主要业务沟通:
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());
[ ... ]
}
在这里,最后使者mMessenger =新使者(新IncomingHandler());
,我得到以下皮棉警告:
And here, final Messenger mMessenger = new Messenger(new IncomingHandler());
, I get the following Lint warning:
此处理类应该是静态的或可能发生泄漏:IncomingHandler
这是什么意思?
推荐答案
如果 IncomingHandler
类不是一成不变的,它会产生一个参考你的服务
对象。
If IncomingHandler
class is not static, it will have a reference to your Service
object.
处理程序
对象为同一线程都有一个共同的Looper对象,他们发布的消息和读取。
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.
这可能会导致内存泄漏,有一段时间,至少 - 只要邮件保留INT队列。除非您发布拖延已久的消息,这不是大问题。
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.
您可以 IncomingHandler
静态,并有一个的WeakReference
为您服务:
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
这篇关于这个处理程序类应该是静态的或可能发生泄漏:IncomingHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!