Analysis and resolution of memory leaks caused by using handler in Android

Source: Internet
Author: User

What is a memory leak?
Java uses the forward graph mechanism to automatically check objects in memory through GC (when the check is determined by the virtual machine), and if the GC discovers that one or a group of objects is unreachable, the object is reclaimed from memory. That is, an object is not pointed to by any reference, and the object is recycled when it is discovered by the GC, and if a set of objects contains only references to each other, and no references from outside them (for example, two objects A and B hold references to each other, but no external objects hold references to a or b), This is still not reachable and will be recycled by GC.

Reasons for memory leaks in Android using handler

?
123456 < Code class= "Java plain" >handler Mhandler = new Handler () { &NBSP;&NBSP;&NBSP;&NBSP; @Override &NBSP;&NBSP;&NBSP;&NBSP; public void handlemessage (Message msg) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; mimageview.setimagebitmap (mbitmap); &NBSP;&NBSP;&NBSP;&NBSP; } }

The above is a simple use of handler. When using an inner class (including an anonymous class) to create a handler, the handler object implicitly holds a reference to an external class object (usually an activity) (otherwise how can you manipulate the view in activity by handler?). )。 Handler usually comes along with a time-consuming background thread (for example, pulling pictures from the web), which notifies handler via a message mechanism after the task has finished executing (the sample is downloaded), and then handler updates the image to the interface. However, if the user shuts down the activity during a network request, and normally the activity is no longer used, it may be reclaimed during GC checking, but since the thread has not finished executing, the thread holds the handler reference (otherwise how does it send a message to handler?). This handler also holds the activity reference, causing the activity to not be recycled (i.e. memory leaks) until the end of the network request (the sample download is complete). Also, if you execute the handler postdelayed () method, the method will load your handler into a message and push the message into the MessageQueue, before the delay you set arrives, There will be a chain of activity, MessageQueue, message, Handler, which causes your activity to be referenced and not recycled.

Damage to memory leaks
Only one, that is, the virtual machine consumes too much memory, causing oom (memory overflow), the program error. For Android apps, it's your user who opens an activity, closes it after use, leaks it, turns it off and leaks it, and then, after a few times, the program consumes more memory than the system limits, FC.

Workarounds for memory leaks using handler
Method One: Through the program logic to protect.
1. Stop your background thread while the activity is closed. When the thread is stopped, it is equivalent to cutting off the handler and externally connected lines, and the activity will naturally be recycled at the right time.
2. If your handler is a message with a delay, then use the corresponding handler Removecallbacks () method to remove the messaging object from the message queue.
Method Two: Declare the handler as a static class.
Static classes do not hold objects from external classes, so your activity can be recycled at will. The code is as follows:

?
123456 < Code class= "Java keyword" >static class myhandler extends handler { &NBSP;&NBSP;&NBSP;&NBSP; @Override &NBSP;&NBSP;&NBSP;&NBSP; public void handlemessage (Message msg) {           mimageview.setimagebitmap (mbitmap); &NBSP;&NBSP;&NBSP;&NBSP; } }

But it's not so simple. Using the above code, you will find that because handler no longer holds references to external class objects, the program does not allow you to manipulate objects in the activity in handler. So you need to add a weak reference to activity in handler (WeakReference):

?
123456789101112131415 static class MyHandler extends Handler {    WeakReference<Activity > mActivityReference;    MyHandler(Activity activity) {        mActivityReference= new WeakReference<Activity>(activity);    }    @Override    public void handleMessage(Message msg) {        final Activity activity = mActivityReference.get();        if (activity != null) {            mImageView.setImageBitmap(mBitmap);        }    }}

After changing the code to the form above, it is done.

Extension: What is WeakReference?
WeakReference a weak reference, as opposed to a strong reference (which we often refer to), is characterized by the fact that the GC ignores weak references when it recycles, that is, even if a weak reference points to an object, as long as the object is not pointed to by a strong reference (and most often requires no soft reference. But the concept of soft references here can be ignored, and the object is reclaimed when it is checked by the GC. For the above code, after the user has closed the activity, even though the background thread is not finished, the GC will still recycle the activity while checking because only one weak reference from handler points to activity. In this way, the problem of memory leaks will not occur.

Analysis and resolution of memory leaks caused by using handler in Android

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.