Android development, using lint detection will prompt such a sentence: This Handler class should is static or leaks might occur. A memory leak may occur if the static adornment is applied to the handler.
ADT20 There is a change: Look for handler leaks:this check makes sure, a handler inner class does not hold an implicit reference to its outer class. Implied handler should not include implicit references to external classes.
Extension is: Handler under the same thread share a Looper object, the message retains a reference to handler, as long as there is a message in the queue, then handler can not be recycled, if handler is not static, Service and activity using handler cannot be recycled, even if their OnDestroy methods are invoked. This can lead to memory leaks. Of course this usually doesn't happen unless you send a long-delayed message.
When you add Hanlder as static, you will find that methods and member variables calling external classes in handler require that they all be defined as final, which is obviously unlikely. It is recommended to add an internal static handler class in your service or activity that holds a weak reference to the service or activity so that the final question can be resolved.
Static classIncominghandlerextendsHandler {Private FinalWeakreference<udplistenerservice>Mservice; Incominghandler (Udplistenerservice service) {Mservice=NewWeakrference<udplistenerservice>(service); } @Override Public voidhandlemessage (Message msg) {Udplistenerservice service=Mservice.get (); if(Service! =NULL) {service.handlemessage (msg); } } }
Static classMyHandlerextendsHandler {weakreference<PopupActivity>mactivity; MyHandler (popupactivity activity) {mactivity=NewWeakreference<popupactivity>(activity); } @Override Public voidhandlemessage (Message msg) {popupactivity theactivity=Mactivity.get (); Switch(msg.what) { Case0: theActivity.popPlay.setChecked (true); Break; } } }; MyHandler Ttshandler=NewMyHandler ( This); PrivateCursor Mcursor; Private voidTest () {Ttshandler.sendemptymessage (0); } }
Static classMhandlerextendsHandler {weakreference<OuterClass>Outerclass; Mhandler (Outerclass activity) {Outerclass=NewWeakreference<outerclass>(activity); } @Override Public voidhandlemessage (android.os.Message msg) {Outerclass Theclass=Outerclass.get (); Switch(msg.what) { Case0: { //accessing external class members and methods using Theclass Break; } default: {LOG.W (TAG,"Unknown handler Message:" +msg.what); } } } }
"Android" [turn] Android handler should be set to static