Context Memory leakage: Handler & amp; internal class, contexthandler

Source: Internet
Author: User

Context Memory leakage: Handler & Internal class, contexthandler

In the previous code, I often use Thread to process time-consuming operations, and then use Handler to return to the main Thread, which involves memory leakage, only then can we know that there is a big risk-Memory leakage.

Previously, I thought the chance of Memory leakage in Context was very small, so I didn't agree. But when Android Lint gives the following warning, I can't hide it.

In Android, Handler classes should be static or leaks might occur.

Here is my code:

public class WallPaperActivity extends Activity {   //....  private final Handler mHandler = new Handler() {    @Override    public void handleMessage(Message msg) {      // ...     }  }  //....}

Android Lint indicates that the Handler class should be a static class, otherwise it may cause memory leakage.

Why does Hanlder cause memory leakage?

Let's take a look at what is done in the Code:

public class WallPaperActivity extends Activity { //...  private final Handler mHandler = new Handler() {    @Override    public void handleMessage(Message msg) {      // ...      imageview.setImagebitmap(bitmap);    }  }}

Here, the main task is to pull the network image from the background thread, and then update the interface in the main thread.

Here, we want to know: When an Android Application is started for the first time, the Android framework createsLogoffObject. A logoff implements a simple message queue for processing in a loopMessageObject. All major application framework events (such as calling the activity life cycle method, clicking the button, and so on) are included in the Message object, which is added to the logoff Message queue and processed one by one. The logoff of the main thread exists throughout the life cycle of the application. When a Handle is instantiated in the main thread, it isMessage Queue associated with Logoff. A message sent to the message queue will holdHandler IntroductionSo that the Android framework can call Handler. handleMessage (Message) When logoff finally processes the Message ).In java, non-static internal classes and anonymous classes implicitly hold a reference to the current external class. However, static internal classes do not.(From translation)

Therefore, when handler is created in the above Code, in fact, this object has implicitly held the reference of WallPaperActivity. Because the background is downloading and pulling images, it may be very fast and it may be as slow as a dog, before the interface is closed, the image is loaded and displayed on the interface. That is, after the hanlder completes processing the message, everything is fine. However, when the network is poor, the Activity is closed when the image is half downloaded. In this case, the Handler in the thread holds the reference of WallPaperActivity because the thread is not finished, and the Activity cannot be recycled, this is the source of the leak.

I searched for the solutions provided by network experts. There are two solutions in total:
1. Restrict threads containing Hanlder according to the interface requirements: Stop the thread before closing Activity (onDestroy. Obviously, this is a method, but it is not suitable for me. After all, I hope the image can be downloaded.

2. Declare the Handler class as a static class:

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

Here, the handler class is defined as static according to Android Lint, and the external Activity object is maintained through WeakReference (weak reference.

Obviously, the latter one is what I need!

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

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.