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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…