Android Memory Overflow Analysis

Source: Internet
Author: User

Android virtual machine is a register-based Dalvik, and its maximum heap size is typically 16M. But android is written in the Java language, so to a large extent,Android 's memory mechanism is equivalent to Java memory mechanism, at the beginning of the development, the memory limit problem will bring us a memory overflow and other serious problems. When we do not use some memory, we should try to avoid on Android or other platforms when running other programs, save the necessary state, so that some of the dead process caused by memory problems, Should try to close the program or save the state when the release, so that the system can improve the smoothness of the operation.

the memory of Android is mainly shown in:

1. on the Android platform, long-term maintenance of some resource references, resulting in some memory can not be released, resulting in a lot of memory leaks. For example:context(the Activity described below is context), in some you need to keep your first class object state, And when you pass the state into another class object, you must first release the receiving class object before removing the first class object. One thing to note: Because in Java or Android memory mechanism, vertex nodes must be guaranteed not to be called before they are released. GC Recovery release. Let's look at a piece of code:

@Override protected void OnCreate (Bundle state) {super.oncreate (state);        Textviewlabel = new TextView (this);        Label.settext ("Leaksare bad");  Setcontentview (label); }

The meaning of this code is that we put aTextViewis loaded into the instance we are running .Activity(Context), therefore, byGCrecycling mechanism, we know that to releaseContext, you must first release some of the objects that refer to him. If not, it's going to be released.Context, you will find that there will be a lot of memory overflow. So a memory overflow is a very easy thing to do when you're not careful. When you save some objects, it also causes a memory leak. The simplest example is the bitmap (Bitmap), such as: when the screen rotates, it destroys the currentActivitystatus, and re-apply to generate a newActivity, until the newActivityThe state is saved. Let's look at another piece of code:

privatestatic drawable sbackground;   @Override   protected void OnCreate (Bundle state) {  super.oncreate [State];   textview label = new TextView (this);   label.settext ("Leaks is Bad");   if (sbackground = = null) {         Sbackground =getdrawable (R.drawable.large_bitmap);   }  label.setbackgrounddrawable ( Sbackground);   setcontentview (label);   }   

This code is very fast and also wrong. Its memory leaks easily in the direction of the screen transfer. While we will find that there is no display of the save Context instance, when we connect the drawing to a view,thedrawable will be is set to callback, which means that in the code above, actually drawing the TextView At the time of the event, we have quoted this Activity . The link situation can be expressed as:drawable->textview->context.

So when you want to release the Context , it's still in memory, and it's not being released.

android Inside the thread most likely to cause memory leaks. The main reason for a thread's memory leak is that the thread life cycle is not controllable. Here's a code:

Publicclass MyTest extends Activity {@Override publicvoid onCreate (bundlesavedinstancestate) {Supe           R.oncreate (savedinstancestate);           Setcontentview (R.layout.main);       New MyThread (). Start ();              } privateclass MyThread extends thread{@Override public void Run () {super.run (); Do somthing}}}

The code is simple, but on Android There are new problems, when we switch the view screen (horizontal screen), we will re-establish the screen or vertical screen Activity. We figure that the Activity that was created before is recycled, but what is the truth? the Java mechanism does not give you the same feeling, before we release the Activity , because the run function is not finished, so MyThread has not been destroyed, so the Activity(Mytest) referencing it hasnot been destroyed, Therefore also brings the memory leak problem.

Some people like to useAndroidprovided byAsynctask, but in factAsynctaskthe problem is even more serious,Threadonly inRunThis memory leak problem occurs when the function does not end, howeverAsynctaskthe internal implementation mechanism is the use ofThreadpoolexcutor,This class produces aThreadThe life cycle of an object is indeterminate and is beyond the control of the application, so ifAsynctaskas aActivityinternal classes, the problem of memory leaks is more likely to occur.

The main ways to improve threading problems are:

L Change the internal class of the thread to a static inner class.

L Save the Context as much as possible with weak references in the program .

2. the evil bitmap...

Bitmap is a very evil object, for a memory object, if the object occupied memory is too large, when the memory limit of the system is exceeded, the memory leak problem is obvious.

The solution to bitmap is primarily to address the memory as much as possible without saving it or to make the sampling rate smaller. In many cases, because we have high image pixels, and for mobile phone screen size We do not use so high pixel proportions of the picture to load, we can first reduce the image sample rate in the original UI operation.

If we don't need to save A reference to the bitmap object, we can also replace it with a soft reference. Specific example code Google also has a lot of.

In summary, to avoid memory leaks, mainly to follow the following points:

First: Do not save references for the context for a long time (to reference the context to make the reference object consistent with its own life cycle).

Second: If you want to use the context, try to use applicationcontext to replace the context, because ApplicationContext has a longer life cycle and does not cause memory leaks in the case of references

Third: Avoid using static variables in your activity when you do not control the life cycle of the object . Try to use weakreference instead of a static.

IV: The garbage collector does not guarantee the accurate recovery of memory, so that the main life cycle and the timely release of unwanted objects when using what you need. As far as possible at the end of the Activity 's life cycle, Release the other objects we reference in OnDestroy, such as:cursor.close ().

In fact, we can use less code to complete the program in many ways. For example: We can use more 9patch images and so on. There are many details that can be worth discovering and digging into more memory problems. If we can do it for the program " who created, who releases " principle, then our grasp of memory, not more than the Java or Android itself, the GC mechanism is poor, and better control of memory, can make our phone run more smoothly.



Android Memory Overflow Analysis

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.