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 UDPListenerServi
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 mService;
IncomingHandler(UDPListenerService service) {
mService = new WeakReference(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