Android development-Memory leakage caused by Handler, androidhandler

Source: Internet
Author: User

Android development-Memory leakage caused by Handler, androidhandler

In Android asynchronous message processing,

    Handler mHandler = new Handler() {          @Override          public void handleMessage(Message msg) {              //        }      };

But when we write this code, the compiler will give a warning that the Handler class should be static and may cause memory leakage.

Cause:

In Java, non-static internal classes and anonymous internal classes both implicitly hold references to their external classes. Static internal classes do not hold external class references.
Here, Handler is an anonymous internal class instance that holds reference from the external Activity. Therefore, when Handler is accompanied by a time-consuming background thread, the Activity cannot be recycled, causing memory leakage.

Solution:

I. Declare Handler as a static internal class.
Because static internal classes do not hold external class references, they do not cause memory leakage of external class instances. Because Handler no longer holds external Class Object references, the program does not allow you to operate on objects in the Activity in Handler. Therefore, when calling an external Activity in a static internal class, we use WeakReference ).

private static class MyHandler extends Handler {    private final WeakReference<SampleActivity> mActivity;    public MyHandler(SampleActivity activity) {      mActivity = new WeakReference<SampleActivity>(activity);    }    @Override    public void handleMessage(Message msg) {      SampleActivity activity = mActivity.get();      if (activity != null) {        // ...      }    }  }

Ii. postDelayed (new Runnable (), 10000)

   mHandler.postDelayed(new Runnable() {      @Override      public void run() {    //     }    }, 10000);

In the post method of handler, we added an anonymous runnable, And I delayed the execution for 10 seconds.
Delayed messages are stored in the main thread message queue before being processed. At the same time, new Runnable is also implemented by anonymous internal classes, and will also hold the reference of Activity.
At this time, we also need to set Runnable to static member attributes.

private static final Runnable sRunnable = new Runnable() {      @Override      public void run() { /* ... */ }  };

At the same time, in onCreate (), mHandler. postDelayed (sRunnable, 10000 );
Another method is to remove the message object from the message queue by using the removeCallbacksAndMessages () method of Handler.
When the parameter is null, all Runnable and Message related to the next handler can be cleared, and all Messages can be cleared by calling the next method in onDestroy.

    protected void onDestroy() {        super.onDestroy();        mHandler.removeCallbacksAndMessages(null);    };
Summary:

When we use a non-static internal class, if the life cycle of the object held by the instance is greater than that of its external Class Object, memory leakage may occur. Solution:

  • Use static internal classes;
  • Weak references are used for all variables in handler/Runnable.

References:

• Strong references: such as "Object obj = new Object ()", which is the most common in Java programs. As long as strong references still exist, the garbage collector will never recycle referenced objects. • Soft reference: it is used to describe some objects that may be useful but not necessary. When the system memory is insufficient, the objects associated with such references will be reclaimed by the garbage collector. After JDK1.2, The SoftReference class is provided to implement soft reference. • Weak reference: it is also used to describe non-essential objects, but its strength is weaker than soft reference. objects associated with weak references can only survive before the next garbage collection in the island. When the spam collector is working, only objects associated with weak references will be reclaimed no matter whether the current memory is sufficient. After JDK1.2, The WeakReference class is provided to implement weak references. • Virtual Reference: the weakest reference relation, which does not affect its survival time at all, nor can it be used to obtain an object instance through virtual reference. The only purpose of setting a Virtual Reference Association for an object is to receive a system notification when the object is recycled by the Collector. After JDK1.2, The PhantomReference class is provided to implement virtual references.

Reference
Http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1123/2047.html
Http://blog.csdn.net/ns_code/article/details/18076173

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.