Android App Memory leakage Handler

Source: Internet
Author: User

Android App Memory leakage Handler
Android App Memory leakage Handler

Handler is also an important source of Memory leakage. Handler mainly belongs to the TLS (Thread Local Storage) variable, and its lifecycle is inconsistent with that of the Activity. If Handler references the Activity, memory leakage occurs.
Take a look at the following code:
/***** Main functions. * @ Version 1.0.0 * @ author Abay Zhuang
* Create at 2014-7-28 */public class HandlerActivity extends Activity {private final Handler mHandler = new Handler () {@ Override public void handleMessage (Message msg ){//...}}; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mHandler. sendMessageDelayed (Message. obtain (), 60000); // just finish this activity finish ();}}

Are you using this method before.

No problem?

The Eclipse tool has the following warning:

This Handler class shocould be static or leaks might occur (com. example. ta. HandlerActivity.1) means: class may cause memory leakage when using static statements.
Why is there such a problem? Handler's lifecycle is inconsistent with Activity
  • When the Android Application is started, a logoff object of the UI main thread is created first. logoff implements a simple Message queue to process the Message objects one by one. The logoff object of the main thread exists throughout the application lifecycle.
  • When a Handler is initialized in the main thread, the Handler is associated with the logoff Message Queue (if there is no association, an error is returned ). The Message sent to the Message Queue references the Handler object that sends the Message, so that the system can call Handler # handleMessage (Message) to distribute and process the Message. Handler references Activity to prevent GC from recycling Acivity
    • In Java, non-static (anonymous) Internal classes reference external class objects implicitly by default. Static internal classes do not reference external class objects.
    • If the external class is Activity, it will cause Activity leakage.

      After the Activity is finished, the delayed message will continue to exist in the main thread message queue for one minute, and then process the message. The message references the Handler object of the Activity, and then the Handler references the Activity. These referenced objects are retained until the message is processed. As a result, the Activity object cannot be recycled, leading to Activity leakage.

      How to Avoid repair?
      • Use explicit references. 1. static internal class. 2. External class
      • Use Weak Reference 2. WeakReference to modify the Code as follows:
        /***** Main functions. ** @ Version 1.0.0 * @ author Abay Zhuang
        * Create at 2014-7-28 */public class HandlerActivity2 extends Activity {private static final int MESSAGE_1 = 1; private static final int MESSAGE_2 = 2; private static final int MESSAGE_3 = 3; private final Handler mHandler = new MyHandler (this); @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mHandler. sendMessageDelayed (Message. obtain (), 60000); // just finish this activity finish ();} public void todo () {}; private static class MyHandler extends Handler {private final WeakReference MActivity; public MyHandler (HandlerActivity2 activity) {mActivity = new WeakReference (Activity) ;}@ Override public void handleMessage (Message msg) {System. out. println (msg); if (mActivity. get () = null) {return;} mActivity. get (). todo ();}}

        Can this be done?
        After the Activity is finished, the handler object is still queued in Message. Messages are still processed. Are these processed necessary? After the normal Activitiy is finished, there is no need to process the message. What should I do? The solution is also very simple. When Activity onStop or onDestroy, cancel the Message and Runnable of the Handler object. By viewing the Handler API, there are several methods: removeCallbacks (Runnable r) and removeMessages (int what.

        The Code is as follows:

         
        /*** It's all for the sake of not letting mHandler drag Water */@ Override public void onDestroy () {mHandler. removeMessages (MESSAGE_1); mHandler. removeMessages (MESSAGE_2); mHandler. removeMessages (MESSAGE_3 );//...... mHandler. removeCallbacks (mRunnable );//......}

        If you feel the trouble above, you can also see the following:

        @Overridepublic void onDestroy() {    //  If null, all callbacks and messages will be removed.    mHandler.removeCallbacksAndMessages(null);}

        Please wait for the next chapter (^__ ^ ......

        You can also follow my github


Related Article

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.