1. 程式人生 > >常被忽略的警告:This Handler class should be static or leaks might occur

常被忽略的警告:This Handler class should be static or leaks might occur

在Android開發中,使用多執行緒處理時,如果需要通知介面需要用到Handler機制,如果不注意就會報如下警告資訊:

在StackOverflow上有這樣一篇文章講到了這個問題(感謝何海英):

http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler

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:

staticclassIncomingHandlerextendsHandler{privatefinalWeakReference<UDPListenerService> mService;IncomingHandler(UDPListenerService service){
        mService =newWeakRference<UDPListenerService>(service);}@Overridepublicvoid handleMessage(Message msg){UDPListenerService service = mService.get();if(service !=null){
              service.handleMessage(msg);}}}