Analysis on Android memory overflow prevention

Source: Internet
Author: User

The Android virtual machine is a register-based Dalvik, and its maximum heap size is generally 16 Mb. However, Android uses the Java language, so to a large extent, the memory mechanism of Android is equivalent to the memory mechanism of Java. At the beginning of development, memory restrictions can cause serious problems such as memory overflow. When we do not use some memory, we should try to avoid saving the necessary status when running other programs on Android or other platforms, so that some memory problems caused by dead processes are caused, release the program when it is closed or saved as much as possible to improve the smoothness of the system.

 

Android memory is mainly manifested in:

1. On the Android platform, some resource references are maintained for a long time, resulting in some memory not being released, resulting in many memory leaks. For example, Context (the activities mentioned below are all Context). When you need to maintain the state of your first class object and pass the State to other class objects, before removing the first class object, you must release the receiving Class Object. Note that in the Java or Android memory mechanism, before the vertex node is released, it must ensure that other objects are not called before they can be recycled and released by the system GC. Let's look at a piece of code:

 

[Java] @ Override
Protected void onCreate (Bundle state ){
Super. onCreate (state );
TextViewlabel = new TextView (this );
Label. setText ("Leaksare bad ");
SetContentView (label );
}
@ Override
Protected void onCreate (Bundle state ){
Super. onCreate (state );
TextViewlabel = new TextView (this );
Label. setText ("Leaksare bad ");
SetContentView (label );
}

 

 

This code loads a TextView instance to the running Activity (Context). Therefore, through the GC collection mechanism, we know that we want to release the Context, you must release some objects that reference them first. If no, you will find a large amount of memory overflow when releasing the Context. Therefore, it is very easy to overflow memory when you are not careful. When you save some objects, it also causes memory leakage. The simplest example is Bitmap. For example, when the screen is rotated, the Activity state that is currently maintained will be damaged and a new Activity will be generated, until the new Activity status is saved. Let's look at another piece of code:

 

[Java] privatestatic Drawable sBackground;
@ Override
Protected void onCreate (Bundle state ){
Super. onCreate (state );
TextView label = new TextView (this );
Label. setText ("Leaks are bad ");
 
If (sBackground = null ){
SBackground = getDrawable (R. drawable. large_bitmap );
}
Label. setBackgroundDrawable (sBackground );
SetContentView (label );
}
Privatestatic Drawable sBackground;
@ Override
Protected void onCreate (Bundle state ){
Super. onCreate (state );
TextView label = new TextView (this );
Label. setText ("Leaks are bad ");

If (sBackground = null ){
SBackground = getDrawable (R. drawable. large_bitmap );
}
Label. setBackgroundDrawable (sBackground );
SetContentView (label );
}

 

 

This code is fast and incorrect. Its memory leakage is easily caused by screen transfer. Although we will find the example of saving the Context that is not displayed, when we connect the drawn graph to a View, the Drawable will be set as a callback by the View, in the above Code, we have referenced this Activity when drawing TextView to the Activity. The link can be: Drawable-> TextView-> Context.

Therefore, when you want to release the Context, it is actually stored in the memory and has not been released.

How to avoid this situation: mainly. The thread is the most prone to errors. Don't underestimate the threads. In Android, threads are most likely to cause memory leakage. The main cause of thread Memory leakage is the uncontrollable thread lifecycle. The following code is provided:

 

[Java] publicclass MyTest extends Activity {
@ Override
Publicvoid onCreate (BundlesavedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
New MyThread (). start ();
}

Privateclass MyThread extends Thread {
@ Override
Public void run (){
Super. run ();
// Do somthing
}
}
}
Publicclass MyTest extends Activity {
@ Override
Publicvoid onCreate (BundlesavedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
New MyThread (). start ();
}
 
Privateclass MyThread extends Thread {
@ Override
Public void run (){
Super. run ();
// Do somthing
}
}
}

 

 

The code is very simple, but there are new problems on Android. When we switch the view screen (landscape screen), we will re-create the landscape or landscape Activity. We think that the previously created Activity will be recycled, but what is the truth? The Java mechanism won't give you the same feeling. Before we release the Activity, MyThread is not destroyed because the run function is not finished. Therefore, the Activity (Mytest) referenced by it is also destroyed, therefore, memory leakage is also caused.

Some people like to use AsyncTask provided by Android, but in fact AsyncTask is more serious. This memory leakage problem occurs only when the run function does not end, however, the internal implementation mechanism of AsyncTask is to use ThreadPoolExcutor. the life cycle of the Thread object generated by this class is uncertain and cannot be controlled by the application. Therefore, if AsyncTask is used as the internal class of the Activity, it is more prone to memory leakage.

The main ways to improve thread problems are:

L change the internal class of the thread to the static internal class.

L use weak references to save Context in the program.

 

2. bitmap...

Bitmap is a very evil object. For a memory object, if the memory occupied by this object is too large, the memory leakage problem becomes obvious when the system memory limit is exceeded ..

To solve bitmap, try not to save it in the memory or reduce the sampling rate. In many cases, because our images are very high in pixels, and for mobile phone screen sizes, we do not use images with such a high pixel ratio for loading, we can first reduce the image sampling rate in the original UI operation.

If we do not need to save the reference of the bitmap object, we can also replace it with soft references. There are also a lot of specific instance code on google.

 

To sum up, to avoid Memory leakage, we should mainly follow the following points:

First, do not save references for Context for a long time (to reference Context, make the referenced object consistent with its own lifecycle ).

Second, if you want to use Context, try to use ApplicationContext instead of Context. Because the lifecycle of ApplicationContext is long, the reference will not cause memory leakage.

Third, avoid using static variables in your Activity without controlling the object lifecycle. Try to use WeakReference instead of static.

Fourth, the garbage collector does not guarantee that the memory can be accurately recycled, so that when you use the content you need, the main life cycle and timely release of unwanted objects. Try to release other referenced objects in onDestroy at the end of the Activity lifecycle, for example, cursor. close ().

 

In fact, we can use less code to complete the program in many ways. For example, we can use 9patch images. We can find and mine more memory problems in many details. If we can achieve the C/C ++ principle of "who creates and who releases" the program, we have no better grasp of the memory than the GC mechanism of Java or Android itself, moreover, better memory control can make our mobile phones run smoothly.

 

 

From Peking University-Google Android lab

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.