An analysis on the memory overflow of Android programming and its prevention method _android

Source: Internet
Author: User

This article describes the Android programming memory overflow and prevention methods. Share to everyone for your reference, specific as follows:

The 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, the memory mechanism of Android is equivalent to the Java memory mechanism, at the beginning of development, the memory limit problem will bring us a memory overflow and other serious problems. When we don't use some memory, we should try to avoid in the Android or other platforms when running other programs, save the necessary state, so that some dead process of memory problems, should try to close the program or save the state of the release, so as to improve the operation of the system flow.

The main features of Android memory are:

1. On the Android platform, the long-term maintenance of some resource references, resulting in some memory can not be released, resulting in a lot of memory leakage problems. For example: the context (the activity described below) is that you must first release the receiving class object before you eliminate the first class object, in some cases where you need to keep your first Class object state and pass the state into other class objects. It is important to note that, because in the Java or Android memory mechanism, the node of the vertex must be freed before it can be released by the system GC. 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 have loaded an instance of TextView into the activity we are running (context), so, through the GC recycle mechanism, we know that to release the context, we must first release some of the objects that reference him. If not, you will find a large amount of memory overflow when you release the context. So it's a very easy thing to overflow the memory when you're not careful. When you save some objects, you can also cause memory leaks. The simplest example of a bitmap (Bitmap), for example, is that when the screen rotates, it destroys an active state that is currently maintained, and then reapply for a new activity until the new activity state is saved. Let's look at a piece of code:

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 very fast and also wrong. Its memory leaks can easily be in the direction of the screen shift. Although we will find that the instance of the save context is not shown, but when we connect the drawn graph to a view, drawable will set the view as a callback, which means that in the code above, in fact, when drawing textview into activity, We have already cited this activity. Link conditions can be expressed as: Drawable->textview->context.

So when you want to release the context, you actually keep it in memory and it's not released.

How to avoid this: the main thing is. Threads are most prone to error. Don't underestimate threads, the threads in Android are the most likely to cause memory leaks. The main reason threads generate memory leaks is that the thread lifecycle is not controllable. Here's a piece of code:

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 simple, but there are new problems on Android, and when we switch the view screen, we recreate the horizontal screen or the vertical screen activity. Our image is that the activity that was established before will be recycled, but what is the truth? The Java mechanism does not give you the same feeling that before we release the activity, because the run function does not end, so that the mythread is not destroyed, so the activity that references it (Mytest) has not been destroyed, and therefore also brings about a memory leak problem.

Some people like to use Android to provide the asynctask, but in fact the asynctask problem is more serious, thread only occurs when the run function does not end this memory leak problem, However, the implementation mechanism within the asynctask is the use of threadpoolexcutor, which produces a thread object that is indeterminate in its lifecycle and is beyond the control of the application, so if Asynctask as an internal class of activity, The problem of memory leaks is more likely to occur.

The main ways to improve threading problems are:

① the inner class of the thread into the static inner class.
② in the program to save the context as much as possible with weak references.

2. The evil bitmap ...

Bitmap is a very evil object, for a memory object, if the object's memory is too large, in excess of the system's memory limit, the memory leak problem is obvious.
Solving bitmap is mainly to solve in memory as much as possible not to save it or to make the sampling rate smaller. In many cases, because our image pixel is very high, and for the mobile phone screen size We do not use so high pixel proportions of the picture to load, we can first of the picture to reduce the sample rate in the original UI operation.

If we do not need to save the bitmap object's reference, we can also use the soft reference to do the substitution. The concrete instance code is also a lot of Google.

To sum up, to avoid memory leaks, the main to follow the following points:

First: Do not hold references for the context for long periods (to refer to the context is to make the reference object consistent with its own lifecycle).

Second: If you want to use the context, try to use ApplicationContext to replace context, because the ApplicationContext life cycle is longer, the reference situation does not cause memory leakage problem

Third: Avoid using static variables in your activity without controlling the life cycle of the object. Try to use WeakReference instead of a static.

Four: The garbage collector does not guarantee accurate memory recovery, so that when you use what you need, the main lifecycle and the unwanted objects are released in a timely manner. As far as possible at the end of the activity life cycle, in the OnDestroy we do the reference to other objects to be released, 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 pictures and so on. There are a lot of details that can be worth discovering and digging up more memory problems. If we can do it, C + + for the program "who created, who release" principle, then our grasp of memory, no more than the Java or Android itself, poor GC mechanism, and better control of memory, can make our mobile phone run more smoothly.

For more information on Android-related content readers can view the site: "Android development of memory and caching skills Summary", "Android Development introduction and Advanced Course", "Android debugging techniques and common problems solution summary", " Android Multimedia How-to Summary (audio, video, audio, etc), summary of Android Basic components usage, Android View tips Summary, Android layout layout tips and a summary of Android controls usage

I hope this article will help you with the Android program.

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.