Prevent Memory leakage of Android applications

Source: Internet
Author: User

Prevent Memory leakage of Android applications


Android applications generally -- at least T-Mobile G1 -- are limited to 16 MB of heap memory. It may be more than enough for a mobile phone, but it is not enough for some developers. Although you are not planning to use all the memory, you still need to consider taking up as little memory as possible for your own applications, so that other applications that run concurrently with your applications will not be killed by the system due to memory shortage-otherwise, our applications will be immoral and generous. Therefore, in my usual development process, an important task is to check whether your code has caused your android application.Memory leakage(Memory leaks ).After summing up, I found that a majority of Android app memory leaks are caused by one reason: the context object remains referenced for a long time.In Android, a context is not used for many things, but the most common function is to index Resources in the context. This is why every widget (textview, button) transmits context in its constructor when a new instance is generated. Generally, in an android application, we have two types of Context: Activity and application. The method or class that developers often pass in to the context variable is the reference of the former-an activity example:

@ Override
Protected VoidOncreate (bundle state ){
Super. Oncreate (State );

Textview label =NewTextview (This);
Label. settext ("leaks are bad ");

Setcontentview (Label );
} This means that the view stores a reference to the activity in which it is located (which can be inferred to be, the same applies to other objects stored in the activity, including the overall view level and related resources of the activity ). From this point of view, if an activity-type context is leaked in the memory, the amount of memory involved will be considerable and predictable. But the terrible thing is that if you don't pay attention to it, it is very easy to leak a whole activity. When the orientation of the screen changes, by default, the system will destroy the current activity and generate a new one. In this case, Android will obtain the UI information of the activity from the resource again. Now suppose you have a large bitmap, and you don't want it to be read again every time the screen direction changes. You may save it in a static code segment:

Private StaticDrawable sbackground: @ override
Protected VoidOncreate (bundle state ){
Super. Oncreate (State );

Textview label =NewTextview (This);
Label. settext ("leaks are bad ");

If(Sbackground = NULL ){
Sbackground = getdrawable (R. drawable. large_bitmap );
}
Label. setbackgrounddrawable (sbackground );

Setcontentview (Label );
}

This code is very lightweight, but it is also very wrong: writing this code will cause memory leakage of the activity that is re-constructed for the first time after the screen direction changes. This is because when a drawable object is attached to a view, this view will be set as a callback for the drawable. In the code just now, in this case, drawable has a reference to textview, and textview has a reference to its activity (that is, the context we just mentioned ), in this way, this activity is unable to be recycled because there is always a reference. If your activity References and saves some other resources at the same time, the memory leakage will be even more unfortunate. That piece of code is a simple example of leaking context objects. We have two methods to prevent the occurrence of the tragedy that exposes context. One thing we all know is that we refuse to let the activity-type context out of its own scope, so as to prevent garbage collection from being caused by reference that cannot be eliminated as shown in the code just now. The second method is to use the context object of the application type. This context object will always exist during the period when your application exists-as its name implies-it will not be affected by the activity lifecycle. If you want to keep an object that requires context objects for a long time, do not forget to use application context. You can simply callContext. getapplicationcontext () orActivity. getapplication () to obtain the application context object.To avoid Memory leakage of the context type, remember the following items:

          • 1. Do not bind an object that exceeds the lifecycle of an activity to an activity type context by referencing and saving it. To bind, the bound object must have the same lifecycle as the activity.

2. Try to use application context to replace activity context when saving objects with a long life cycle.

3. avoid using a non-static internal class in an activity that you do not control its lifecycle, but use a static internal class, then use the weak reference of the external activity where context is needed (rather than the strong reference in the Code ).

4. Remember: The garbage collection mechanism is not a superstitious guarantee for Memory leakage.

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.