First explain this sentence this Handler class should is static or leaks might occur, roughly meaning: theHandler class should be defined as a static class, otherwise it could lead to memory leaks.
Concrete how to solve, in the foreign people raised, as follows:
Issue:ensures that Handler classes does not hold on to a reference to an outer class
In Android, Handler classes should is static or leaks might occur. Messages enqueued on the application thread ' s MessageQueue also retain their target Handler. If The Handler is a inner class, its outer class would be retained as well. To avoid leaking the outer class, declare the Handler as a static nested class with a weakreference to its outer class.
Broadly translated as follows:
The Handler class should be a static type, or it might cause a leak. 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 the outer class it is in. To avoid revealing this external class, you should declare handler as a static nested class, and use the weak application of the external classes.
Examples of Use:
1 Static classMyHandlerextendsHandler {2Weakreference<popupactivity>mactivity;34 MyHandler (popupactivity activity) {5Mactivity =NewWeakreference<popupactivity>(activity);6 }7 8 @Override9 Public voidhandlemessage (Message msg) {TenPopupactivity theactivity =mactivity.get (); One Switch(msg.what) { A Case0: -TheActivity.popPlay.setChecked (true); - Break; the } - } - } - +MyHandler Ttshandler =NewMyHandler ( This); - PrivateCursor mcursor; + A Private voidTest () { atTtshandler.sendemptymessage (0); -}
WeakReference is similar to something that is dispensable. In the process of scanning the area of memory that the garbage collector thread governs, once an object with only a weak reference is found, it will reclaim its memory regardless of whether the current memory space is sufficient or not, and it is plainly a less strong. The garbage collector is required to keep an object in memory. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.
Reference article: http://www.cnblogs.com/jevan/p/3168828.html
Original link: http://blog.csdn.net/wuleihenbang/article/details/17126371
This Handler class should is static or leaks might occur (null) workaround