Android performance optimization tips for avoiding memory leaks

Source: Internet
Author: User

In the development of Android program , memory leak problem is a more common problem, I believe that there are some programs of Android programming apes have encountered a variety of memory leaks. Memory leaks are one of the main causes of application Oom and are issues that must be avoided in programming. The following small series to gather a few memory leaks to avoid the suggestion, share to everyone, come together to see it.

1, for the life cycle of objects longer than the activity, if necessary should use ApplicationContext;

2, in the context of the first consideration of ApplicationContext, of course, it is not omnipotent, for some places must use the context of activity, for Application,service, The context scenario for activity three is as follows:

* * Where: **no1 indicates that application and service can initiate an activity, but a new task queue will need to be created. For dialog, it can only be created in activity.

3. For non-static external member variables (such as: Context, View) that need to be used in static internal classes, you can use weak references in static inner classes to refer to variables of external classes to avoid memory leaks.

4. For an internal class object with a longer life cycle than the activity, and the internal class uses the member variables of the outer class, you can do this to avoid a memory leak:

1) Change the inner class to a static inner class

2) Use weak references in static inner classes to refer to member variables of external classes

5. For objects that are no longer required to be used, the display assigns them null, such as calling recycle () before using bitmap, and then assigning null.

6, keep the object life cycle sensitive, pay special attention to the life cycle of single case, static object, global collection and so on.

Related article: "Android program ape must warn 13 pits"

Android performance optimization tips for avoiding 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.