Often, when we use Handler, this Handler class should is static or leaks might occur, for people who have code cleanliness. I can't stand it.
So how do we fix it?
Many articles have been consulted, and the general explanation is that messages queued in the program message queue maintain the application of the target handler class. If handler is an internal class, it also maintains a reference to its external class (usually activity or service, etc.). As long as there is a message in the queue, then handler cannot be recycled, and if handler is not static then service and activity using handler cannot be recycled, which can lead to memory leaks.
In general, we're keeping a weak reference to an external class in handler.
//declares a static class, inherited from Handler,//and holds a weak reference to the outer class (assuming that the outer class is parentactivity) Private Static classMyHandlerextendsHandler {weakreference mouterclass; MyHandler (Outerclass clz) {mouterclass CLZ=NewWeakReference (CLZ); } @Override Public voidhandlemessage (Message msg) {Outerclass CLZ=Mouterclass.get (); Switch(msg.what) { CaseSOMETHING:clz.doSomething (); Break; Defaule: Break; } } }; //then declare, then use handler to PrivateMyHandler handler =NewMyHandler ( This);
Solutions for handler warnings in Android