Android Handler Usage Summary to avoid memory leaks

Source: Internet
Author: User

Android development often uses Handler, but we find that every use of Handler appears: This Handler class should be static or leaks might occur (null). Android Lint is intended to prompt us, so using handler can easily cause memory leaks. But you will find it useless to change to static. Because it doesn't solve the problem at all.

First, we have to confirm why there is a memory leak? Because the handler is message-based. Each time new handler, a message queue is created to handle the messages you send using handler, such as: Handler.send***message. Because the message will always have a first served difference (if only this is OK, after all, not too slow, after all, can run, may delay a few seconds), but if you are using sendmessagedelayed (Message msg, long Delaymillis ) or postdelayed (Runnable R, Long Delaymillis) to send a delay message, the probability that the underlying memory leak occurred is above 90% .

The usual example is that we use handler in the activity to update the UI controls, which is more common.

 Public class extends Activity {    private  Handler mhandler;      protected void onCreate (Bundle savedinstancestate) {        new  Handler ();
Mhandler.postdelayed (New Runnable () {
LOG.I ("Wytings", "-----------postdelayed-------"); View.setvisibility (View.gone); }, 50000);
        ...    }
... }

If we are frantically switching the activity horizontally and vertically, then the activity will be destroyed and rebuilt continuously. In theory, the activity that is closed should be recycled at a specific time, that is, our memory will be up and down in a certain range, but in fact, the memory consumed will gradually increase with the number of transitions across the screen. This has actually indicated that our memory leaks, if you will look at the memory, you will find that there are piles of demoactivity instances there is no way to recycle.

  This is because the context used in the view is the current activity, and once the runnable is post, it will remain in the queue until the time is up and executed. This means that during this time the activity has been destroy, but this object is still not recoverable, you will find 50 seconds good, there will be a bunch of "-----------postdelayed-------" Log print out, Although you have been turned off by this app and you think that even printing should be printed only once ...

How to avoid this problem, if you search online you will see a lot of weak references to the article. This is indeed a solution. The idea is to have all the objects used in the handler become weak references, so that they can be recycled when Android reclaims the memory. I really think that if only the person who writes this method, definitely belongs to the copy party, because this is completely the case. If you think about it, we'll write this handler because we're going to use it. How can such a weak citation be used to deal with such problems? Get the JVM to recycle it?! If so, then we also need to use Bitmap, recycle (), why, rather than directly into a soft reference.

Here's a few more things to know about Java references:

knowledge of Java references
Strong References (Strong Reference) The default reference. If an object has a strong reference, it will never be reclaimed by the garbage collector. In the case of insufficient memory space, the Java virtual machine prefers to throw outofmemory errors, cause the program to terminate abnormally, and not strongly reference objects to resolve out-of-memory issues.
Soft references (SoftReference) If the memory space is sufficient, the garbage collector does not reclaim it, and if the memory space is insufficient, the memory of those objects is reclaimed.
Weak references (WeakReference) Once the garbage collector finds an object with only a weak reference, its memory is reclaimed regardless of the current memory space.
Virtual Reference (Phantomreference) If an object holds only virtual references, it can be garbage collected at any time, just as there are no references.

  If you're lucky, you'll run into something. In addition to writing weak references, there is a handler.removecallbacksandmessages (null), which removes all messages and callbacks, A simple sentence is to empty the message queue. Be careful not to think that you post a runnable or just a sendemptymessage. You can take a look at the source code, in the handler will be converted into the orthodox message, put into the messages queue inside, so empty queue means that this handler directly into the prototype, of course, can be recycled.

So, I think the best way is when you use handler, in the outside activity or fragment in the closing method, such as OnDestroy call Handler.removecallbacksandmessages (null); It should not be changed to a soft reference.

Android Handler Usage Summary to avoid memory leaks

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.