Issues with handler memory leaks

Source: Internet
Author: User

When using handler to update the UI, I wrote this:

publicclass SampleActivity extends Activity {  privatefinalnew Handler() {    @Override    publicvoidhandleMessage(Message msg) {      // TODO    }  }}

It looks normal, but Android Lint gives a warning:

This Handler class should is static or leaks might occur

This means: This handler must be static, otherwise it will cause a memory leak.

In fact, for this problem, Android Framework engineer Romain Guy has already explained on the Google Forum, and gave his suggestion to write:

I wrote that debugging code because of a couple of memory leaks I
Found in the Android codebase. Like your said, a Message has a
Reference to the Handler which, when it's inner and non-static, has a
Reference to the outer this (a Activity for instance.) If the Message
Lives in the "queue for a" long time, which happens fairly easily when
Posting a delayed message for instance, you keep a reference to the
Activity and "leak" all the views and resources. It gets even worse
When you obtain a Message and don ' t post it right away but keep it
Somewhere (for instance with a static structure) for later use.

The wording of his suggestion was:

class OuterClass {  class InnerClass {    privatefinal WeakReference<OuterClass> mTarget;    InnerClass(OuterClass target) {           new WeakReference<OuterClass>(target);    }    void doSomething() {           OuterClass target = mTarget.get();           ifnull) {                target.do();               }     }}

Below, let us explain further:

When the 1.Android app launches, the Android Framework creates a Looper object for the main thread that will run through the app's entire lifecycle, implementing a message queue, and opens a loop to process the message object. The main event of the framework consists of an internal message object that is added to the message queue when these events are triggered.
2. When an handler is instantiated (as in the above), it is associated with the message queue of the main thread Looper object, and the message object that is pushed into the queue of messages will hold a handler reference so that when Looper processes this message, The framework executes the handler Handlemessage (Message) method.
3. In the Java language, non-static anonymous inner classes hold an implicit reference to an external class, while static inner classes do not.

Where exactly is the memory leak happening? Take the following code as an example:

 Public  class sampleactivity extends Activity {  Private FinalHandler Mleakyhandler =NewHandler () {@Override     Public void Handlemessage(Message msg) {// ...}  }@Override  protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//Post a message and delay its execution for ten minutes.Mleakyhandler.postdelayed (NewRunnable () {@Override       Public void Run() { }    }, -*Ten* +);//Go to the previous Activity.Finish (); }}

When activity is dropped, message will be present in the message queue for up to 10 minutes before it is executed. This message holds a reference to handler, and handler also holds an implicit reference to the external class (sampleactivity), which is persisted until the message is executed. This ensures that the context of the activity is not reclaimed by the garbage collection mechanism, but also that the resources of the application are compromised.

To solve this problem, handler in the following code is a static anonymous inner class. Static anonymous inner classes do not hold an implicit reference to an external class, so activity will not be compromised. If you need to invoke the external activity method in handler, let handler hold a weakreference to the activity so that the context of the activity is not disclosed, as follows:

 Public  class sampleactivity extends Activity {  /** * Instances of static inner classes do not hold a implicit * reference to their outer class. */  Private Static  class myhandler extends Handler {    Private FinalWeakreference<sampleactivity> mactivity; Public MyHandler(sampleactivity activity) {mactivity =NewWeakreference<sampleactivity> (activity); }@Override     Public void Handlemessage(Message msg) {Sampleactivity activity = mactivity.get ();if(Activity! =NULL) {// ...}    }  }Private FinalMyHandler Mhandler =NewMyHandler ( This);/** * Instances of anonymous classes do not hold a implicit * reference to their outer class when they is "Stati   C ". */  Private Static FinalRunnable srunnable =NewRunnable () {@Override       Public void Run() { }  };@Override  protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//Post a message and delay its execution for ten minutes.Mhandler.postdelayed (Srunnable, -*Ten* +);//Go to the previous Activity.Finish (); }}

Summarize:
In real-world development, if the life cycle of an internal class is inconsistent with the activity's life cycle (for example, after the activity finish () is waiting for 10 minutes, the instance of the inner class executes), then the non-static inner class is avoided in the activity, in which case, A static inner class is used, while holding a weakreference to the activity.

Issues with handler memory leaks

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.