Android: avoiding memory leaks

Source: Internet
Author: User
Tags home screen

This is the first article in articles. As a matter of fact, I have noticed this question for a long time. Since I didn't understand it at the beginning, I have a deep impression today: it causes memory leakage due to incorrect use of context.

Android applications (at least T-Mobile G1) are limited to 16 Mb in heap size. The device has a lot of memory, but developers only want to get it. Even if you don't want to use all the memory on the device, you should use the least memory without killing other applications ). The more programs in the memory, the faster the user switches the program. In some of my work, I encountered some memory problems, most of which were due to an error: Keep the context referenced for a long time (in short, context leakage ).

In the Android system, context is often used to add and use resources. This is also why many widgets can accept a context parameter in the search function. In a common android application, you can often use two contexts (activity and application ). Developers usually pass the context parameter to a class and a method:

1 @Override
2 protected void onCreate(Bundle state) {
3 super.onCreate(state);
4
5 TextView label = new TextView(this);
6 label.setText("Leaks are bad");
7
8 setContentView(label);
9 }

Passing the context of the activity to the view means that the view has a reference to the entire activity, and then referencing any resources occupied by the activity: Usually the entire view structure and all resources. Therefore, if the context memory leaks, a lot of memory will be leaked. If you are not careful, you can easily disclose the entire activity.

When the screen method direction changes, by default, the current activity will be destroyed and a new one will be created. Then, the android System adds the UI and resources of the application again. For example, if you do not want to add a large image to an application every time you rotate it, the simplest way is to set it as a static variable:

 1 private static Drawable sBackground;
2
3 @Override
4 protected void onCreate(Bundle state) {
5 super.onCreate(state);
6
7 TextView label = new TextView(this);
8 label.setText("Leaks are bad");
9
10 if (sBackground == null) {
11 sBackground = getDrawable(R.drawable.large_bitmap);
12 }
13 label.setBackgroundDrawable(sBackground);
14
15 setContentView(label);
16 }

The above code is very incorrect. When the orientation of the first screen changes, the first activity is leaked. When an image is attached to a view, the drawable callback function callback () references the view (in fact, sbackgroud. setcallback (Label) occurs in the setbackgrounddrawable function )). In the entire code snippet, this drawable object is referenced by a textview containing the reference of the activity object.

This example is the simplest example of leaking context. You can go to the home screen's source code and check that when the activity is destroyed, set the callbacks of the stored drawable to null. interestingly, many of the leaked context that you have created a chain are very bad. They make you consume memory quite quickly.

There are two ways to avoid Memory leakage related to context. The most common method is to avoid referencing context outside the scope. The above example shows an error example. The second solution is to use the context of the application. The lifecycle of this context is as long as that of your application and does not depend on the lifecycle of activities. If you need context to save an object with a long life cycle, remember to use context of application. You can use context. getapplicationcontext () or activity. getapplication () to get it easily.

In general, to avoid Memory leakage related to context, remember the following points:

1. Do not allow long-lived objects to reference the context of the activity. (The reference of an activity should have the same lifecycle as its own)

2. Use application-context instead of activity-context whenever possible.

3. If you cannot control their lifecycles, avoid using high non-static internal classes. Use static internal classes and make weak references to them in the activity. Because objects of non-static internal classes are referenced by their external classes by default during instantiation.

4. Does your garbage collection mechanism handle memory leaks. (This is usually not considered)

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.