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


I am developing an Android 2.3.3 application with a service. I have this service to communicate with the main activity:

  Provides public class UDPListenerService service {Personal Static Last String TAG = "UDPListenerService"; // Private Thread Group meritades = new thread group ("UDPPListenerSework"); Private UDPListenerThread myThread; / ** * Handler to communicate from ServiceTrade to service * / personal handler mServiceHandler; // Last Messenger used to receive messages from activity inMessenger = new Messenger (new incoming handler ()); // Use the private messenger outMessenger to send a message to the activity; Expands the class incoming handler handler {@Override Public void handleMessage} {}} / ** * Targets we publish for sending messages to incoming handlers for customers * / Last Messenger mMessenger = New Messenger (new incoming handler ()); [...]}   

And here, Last Messenger mMessenger = New Messenger (new incoming handler ()); , I get the following lint warning:

This handler class must be static or leak: Incoming handler

What it means ?

If incoming handler class is not static, then this will be your service The object will be referenced.

Handlers Objects share a shared loop object for the same thread, which they post and read messages

as Messages have targets handlers , as long as there are messages with target handlers in the message queue, the handler can not be collected garbage. If the handler is not stable, garbage can not be collected even if your service or activity is destroyed.

This may lead to memory leak, at least for some time - unless the message is in the queue. As long as you do not give long-delayed messages, it is not much of a problem.

You can make inning handler stable and WeakReference in your service: Handler Expands Handler {Private Final Week Reference & lt; UDPListenerService & gt; MService; InningHandler (UDPListener Service Service) {MS ervice = New Week Reference & lt; UDPListenerService & gt; (Service); } @ Override Public Wide Handess (Message Message) {UDPListenerService service = mService.get (); If (service! = Null) {service.handleMessage (msg);

Comments