Android App Memory Leak Handler

Source: Internet
Author: User

Android App Memory Leak Handler
Handler也是造成内存泄露的一个重要的源头,主要Handler属于TLS(Thread Local Storage)变量,生命周期和Activity是不一致的,Handler引用Activity会存在内存泄露。
Take a look at the following code
/** *  * Implementation of the main functions. * @version 1.0.0  * @author Abay Zhuang <br/> *         Create at 2014-7-28 */public class Handleractivity extends Ac tivity {    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 ();}    }

Did you use it before?

No problem?

The Eclipse tool has such warning warning:

This Handler class should be static or leaks might occur (com.example.ta.HandlerActivity.1)意思:class 使用静态声明否者可能出现内存泄露。
Why is there such a problem? The life cycle of handler is inconsistent with activity
    • When the Android app starts, it creates a Looper object for the main thread of the UI, and Looper implements a simple message queue, one for processing the message object inside. The main thread Looper object exists throughout the application life cycle.
    • When handler is initialized in the main thread, the handler and the Looper message queue are associated (no association will be an error). A message sent to the queue of messages refers to the Handler object that sent the message, so that the system can call Handler#handlemessage (message) to distribute processing the message.
Handler referencing Activity prevents GC from recovering acivity
    • In Java, non-static (anonymous) inner classes implicitly refer to external class objects by default. Static inner classes do not reference external class objects.
    • If the external class is activity, it can cause activity disclosure.

      When activity finishes, the deferred message continues to exist for 1 minutes in the main thread message queue and then processes the message. The message references the activity's handler object, and the handler references the activity. These reference objects persist until the message is processed, which prevents the activity object from being recycled, causing the activity disclosure described above.

How to avoid repair?
    • Using the explicit reference, 1. Static inner class. 2. External classes
    • Use weak reference 2. WeakReference
Modify the code as follows:
 
/** * * Implementation of the main functions. * * @version 1.0.0 * @author Abay Zhuang <br/> * Create at 2014-7-28 */public class HandlerActivity2 Extend    s 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
Is that all you got?
  当Activity finish后 handler对象还是在Message中排队。 还是会处理消息,这些处理有必要?  正常Activitiy finish后,已经没有必要对消息处理,那需要怎么做呢?  解决方案也很简单,在Activity onStop或者onDestroy的时候,取消掉该Handler对象的Message和Runnable。  通过查看Handler的API,它有几个方法:removeCallbacks(Runnable r)和removeMessages(int what)等。

code is as follows:

  
/** * Everything is meant to keep mhandler from getting muddy * * @Override public void OnDestroy () {Mhandl        Er.removemessages (Message_1);        Mhandler.removemessages (message_2);        Mhandler.removemessages (Message_3);        ... mhandler.removecallbacks (mrunnable);   // ... ...    } 

If you feel the trouble above, it can also be as follows:

@Overridepublic void OnDestroy () {    //  If null, all callbacks and messages would be removed.    Mhandler.removecallbacksandmessages (null);}

Please look forward to the next chapter (^__^) hehe ...

Or you can 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.