Solutions for handler warnings in Android

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.