Android Weak Handler: Handler library to avoid memory leaks

Source: Internet
Author: User

This is an application for technology developers, you can get the latest and best technical dry products in the Nuggets, not only Android knowledge, front end, back end so that the product and design are covered, want to be a friend of the whole stack of engineers do not miss!

Android uses Java as its development environment. Java's cross-platform and garbage collection mechanisms have helped us solve some of the underlying problems. But despite the garbage collection mechanism, while developing Android still occasionally encountered the problem of out of memory, this time we cannot help but ask, where is the garbage collection machine?

We mainly talk about the leakage caused by handler, and give three solutions, the last one is the library we want to introduce WeakHandler .

Handler that can cause leakage problems are generally prompted lint warnings:

Handler class should be static or leaks might occur 意思:class使用静态声明否者可能出现内存泄露。

This is a basic activity. In Handler's Post method we joined an anonymous runnable, and I deferred it for a full 80 seconds. We run this program and rotate the phone several times and then analyze the memory.

Now that there are 7 activity in memory, that's too bad, so let's study why the GC didn't clean it up. (In my query in memory Activity list with OQL (object Query Language), simple and powerful tools, PS How to use, who can tell me? )

From which we can see that one of the references to Mainactivity is from this$0 , this$0 what is it? Here is an this$0 explanation of the following:

-------What is this$0 ---------

The non-static inner class will have a this$0 field that holds its parent object. in Java, non-static (anonymous) inner classes implicitly refer to external class objects by default. Static inner classes do not reference external class objects . A compiled inner class is likely to be this:

123456789 class parent$inner{synthetic parent this$0;parent$inner(parent this$0){this.this$0 = this$0;this$0.foo();}}

-------What is this$0结束 ---------

In our code, the anonymous runnable is a non-static inner class, so he uses this$0 it to save mainactivity, and runnable will continue to be referenced by its callback, The callback is then quoted by the next series of message, so the main thread of reference is too much more than the mother. When the activity finishes, the deferred message continues to exist in the main thread message queue for 80 seconds, and then the message is processed, so handler continues to exist in memory, and handler references activity, and when we rotate the phone, the activity The constant rebuilding and finish, resulting in multiple activity references appear.

Once the runnable or message is sent into the handler, a sequence of message commands referencing the main thread (here is Mainactivity bar) is saved until the message is executed. If the send runnable set a delay time, then at least in this delay time the memory leak is positive, if it is sent directly, in the case of a larger message, it is possible to have a temporary leak.

Workaround One: Use static

Execute again while rotating the phone, analyzing the memory as follows:

It's still the same. Let's see who's still holding the activity:

At the bottom we find that the activity continues to be DoneRunnable quoted by the Mcontext inside the Mtextview. In this case, it seems that using static alone does not solve the problem. There's still a little work to do.

Static runnable plus WeakReference

Since it was caused by mtextview, we replaced the mtextview with a weak quote:

Note that since Mtextview is a weak reference, it can be null at any time, so you need to determine whether it is empty before use. Okay, keep looking at the memory situation:

All right, I think we've solved the problem perfectly. Summarize what we have done:

Using static internal classes

Use weak references for all variables in the handler/runnable.

But this is not a lot of code, and you have to be careful.

Clean out all messages in OnDestroy.

Handler has a handy way to removeCallbacksAndMessages do this: when the argument is null, you can erase all the runnable and message associated with the handler, and we will not have a memory leak if we call the secondary method in OnDestroy.

Run, rotate the phone

But if you have a higher requirement for the code, it is not convenient to use the library provided by the author. WeakHandler

WeakHandler

WeakHandlerIt works exactly the same as handler, but he is safe and WeakHandler uses the following:

You just have to replace the old handler WeakHandler .

WeakHandlerThe implementation principle

WeakHandler的思想是将Handler和Runnable做一次封装,我们使用的是封装后的WeakHandler,但其实真正起到handler作用的是封装的内部,而封装的内部对handler和runnable都是用的弱引用。

第一幅图是普通handler的引用关系图

第二幅图是使用WeakHandler的引用关系图

其实原文有对WeakHandler更多的解释,但是表述起来也挺复杂的。

Original address: https://techblog.badoo.com/blog/2014/10/09/calabash-android-query/

GitHub Project Address: Https://github.com/badoo/android-weak-handler

Android Weak Handler: Handler library to avoid memory leaks

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.