How to optimize memory for Android Development

Source: Internet
Author: User

How to optimize memory for Android Development

Editor's note: some content in this article may be controversial, such as comments). You can learn useful content and read it in an attitude of learning and communicating, rather than reading it with an attitude of criticism.

Many people think that there should be no memory leakage due to the garbage collection mechanism of JAVA programs. In fact, if we no longer use an object in a program, but because there are still references pointing to it, the garbage collector cannot recycle it. Of course, the memory occupied by this object cannot be used, this causes memory leakage. If we have been running java for a long time, and this memory leakage keeps occurring, the memory will not be available at the end. Of course, the memory leakage in java is different from that in C/C ++. If the java program ends completely, all its objects will be inaccessible, and the system will be able to recycle them. Its memory leakage is limited to itself, it does not affect the entire system. The memory leakage of C/C ++ is worse. Its memory leakage is a system level, even if the C/C ++ program exits, its leaked memory cannot be recycled by the system and will never be used unless the machine is restarted.

Memory leakage of an Android app has little impact on other apps. To ensure secure and fast running of Android applications, each Android application uses a proprietary Dalvik Virtual Machine instance to run. It is incubated by the Zygote service process, that is to say, each application runs in its own process. Android allocates different memory usage ceilings for different types of processes. If the program suffers a memory leak during running, the memory usage of the application process exceeds this limit, the system will regard it as a memory leak and kill it. This will kill only its own processes, without affecting other processes. If there is a problem with system processes such as system_process, will cause the system to restart ).

1. Memory leakage caused by reference not released

1.1 Memory leakage caused by registration not canceled

This kind of Android Memory leakage is more serious than pure java Memory leakage, because some other Android programs may reference the objects of our Anroid program, such as the registration system ). Even though our Android program has ended, other reference programs still reference an object of our Android program, and the leaked memory cannot be recycled.

Example 1:

Suppose we want to listen to the telephone service in the system in the LockScreen interface to obtain some information (such as signal strength), we can define a PhoneStateListener object in LockScreen, register it with the TelephonyManager service. For LockScreen objects, a LockScreen object is created when the screen lock interface needs to be displayed. When the screen lock interface disappears, the LockScreen object is released.

However, if you forget to cancel the previously registered PhoneStateListener object when releasing the LockScreen object, LockScreen cannot be reclaimed. If the screen lock interface is constantly displayed and disappears, a large number of LockScreen objects cannot be recycled, causing OutOfMemory and causing the system_process process to crash.

Although some system programs seem to be able to automatically cancel registration, of course, they are not timely), but we should explicitly cancel registration in our program, when the program ends, all registration should be canceled.

Memory leakage caused by not clearing objects in the 1.2 collection

We usually add some object references to the collection. When we don't need this object, we didn't clear its references from the collection, so this set will become larger and larger. If the set is static, the situation is more serious.

Ii. Memory leakage caused by resource objects not being closed

Resource objects such as Cursor and File files usually use some buffer. When we do not use them, we should close them in time so that their buffer can be recycled in time. Their buffering not only exists in the Java virtual machine, but also exists outside the Java Virtual Machine. If we only set its reference to null without shutting them down, it will often cause memory leakage. Because some resource objects, such as SQLiteCursor In The Destructor finalize), if we didn't close it, it will call close () to close it. If we didn't close it, the system also disables it when it is recycled, but this is too inefficient. Therefore, when the resource object is not used, it should call its close () function, close it, and then set it to null. make sure that our resource object is closed when our program exits.

The program usually queries the database, but it often does not close after using the Cursor. If our query result set is small, memory consumption is not easy to find. Memory problems can be reproduced only when a large number of operations are performed at a regular time, this will cause difficulties and risks for future testing and troubleshooting.

Iii. Some bad codes turn into memory pressure

Some codes do not cause memory leakage, but they, or do not effectively release unused memory in a timely manner, or do not effectively use existing objects, but frequently apply for new memory, this has a great impact on memory recovery and allocation. It is easy to force the virtual machine to allocate more memory to the application process, resulting in unnecessary memory expenses.

3.1 Bitmap does not call recycle ()

When a Bitmap object is not in use, we should call recycle () to release the memory before setting it to null. although recycle () is from the source code, calling it should be able to immediately release the main memory of Bitmap, but the test results show that it does not immediately release the memory. However, I should be able to greatly accelerate the release of the main memory of Bitmap.

3.2. when constructing the Adapter, the cached convertView is not used

Taking the BaseAdapter used to construct the ListView as an example, the methods in BaseAdapter are described as follows:

Public View getView (int position, View convertView, ViewGroup parent) to provide ListView with the view object required for each item. Initially, the ListView will instantiate a certain number of view objects from the BaseAdapter based on the current screen layout, and the ListView will cache these view objects. When you scroll up the ListView, the view object originally located in the top list item will be recycled and then used to construct the bottom list item that appears. This construction process is completed by the getView () method, getView () the second View convertView parameter is the view object of the cached list item. (convertView is null if no view object is cached during initialization ).

It can be seen that if we do not use convertView, but re-instantiate a View object in getView () every time, it will be a waste of time and cause memory compaction, it puts more pressure on garbage collection. If garbage collection is too late, the virtual machine will have to allocate more memory to the application process, causing unnecessary memory consumption. You can view the process when ListView recycles the view object of list item:

View plaincopy to clipboardprint?

Android. widget. AbsListView. java-> void addScrapView (View scrap) method.

In android development, the primary memory allocation and garbage collection are required at all times, because the system allocates limited memory for each dalvik Virtual Machine. in google's G1, the allocated maximum heap size is only 16 MB, and later machines are generally 24 MB, which is really poor. In this way, we need to pay attention to it during the development process. Do not cause OOM errors because of your code problems.

JAVA memory management:

As we all know, the android Application layer is developed by java. The davlik Virtual Machine of android is similar to that of jvm, except that it is based on registers. Therefore, to understand the memory management of android, you must understand the memory allocation and garbage collection mechanism of java.

In java, memory is allocated to objects through the new Keyword, and the memory is released by the garbage collector GC). During the development process, engineers, you do not need to explicitly manage the memory. However, this may cause a lot of memory to be wasted without knowing it. In the end, the Java Virtual Machine will spend a lot of time garbage collection, and the more serious is the jvm oom. Therefore, it is necessary for java engineers to Understand JAVA's memory allocation and garbage collection mechanisms.

The following lists the existing problems. Click detail to go in. The detailed code may be problematic:

File: // C:/example E ~ 1/ADMINI ~ 1/LOCALS ~ 1/Temp/ksohtml/wps_clip_image-32625.png

File: // C:/example E ~ 1/ADMINI ~ 1/LOCALS ~ 1/Temp/ksohtml/wps_clip_image-21158.png

For the use of MAT can refer to: http://www.blogjava.net/rosen... . Html

This brother wrote in detail.

Summary

Both java and android should understand the memory allocation and garbage collection mechanisms. It is difficult for engineers to write code without bad code, the key is how to troubleshoot Android memory optimization when a problem occurs.

I. Android memory mechanism

Android programs are written in Java, so the memory management of Android is similar to that of Java. The programmer allocates memory for the object through new, and all objects are allocated space in the java heap. However, the release of the object is done by the garbage collector. In C/C ++, the memory mechanism is "Who is polluted and who is responsible for governance". java is more user-friendly and we have a dedicated garbage collector ).

How can GC check whether an object has been deprecated? Java adopts the principle of Directed Graphs. Java considers the reference relationship as directed edges of a graph, and directed the directed edge from the quotor to the referenced object. A thread object can be used as the starting vertex of a directed graph. This graph is a tree starting from the starting vertex. All objects that can be reached by the root vertex are valid objects and GC will not recycle these objects. If an object (connected subgraph) is inaccessible to this root vertex (note that this graph is a directed graph), we think this (these) object is no longer referenced and can be recycled by GC.

Ii. Android memory overflow

How does Android memory overflow occur?

The Android virtual machine is a register-based Dalvik. Its maximum heap size is generally 16 M, and some machines are 24 M. Therefore, the memory space we can use is limited. If our memory usage exceeds a certain level, an OutOfMemory error occurs.

Why is memory insufficient? I think there are two main reasons:

Due to program errors, some resources such as Context are always referenced, resulting in Memory leakage and unreleased resources.

Saves multiple objects that consume too much memory, such as Bitmap), resulting in memory exceeding the limit.

3. static

Static is a keyword in Java. When it is used to modify a member variable, the variable belongs to the class, rather than the instance of the class. Therefore, the life cycle of a variable modified with static is very long. If you use it to reference some instances with excessive resource consumption, you must be cautious.

SBackground is a static variable, but we found that we did not explicitly Save the reference of Contex. However, when Drawable is connected to View, drawable sets the View as a callback. Because the View contains the reference of Context, we still save the reference of Context. The reference chain is as follows:

Drawable-> TextView-> Context

Therefore, the Context is not released, and memory leakage occurs.

How can we effectively avoid such a reference?

Avoid using static member variables to reference instances that consume too much resources, such as Context.

Use the Application Context whenever possible. Because the Application Context has a long life cycle, it will not cause memory leakage if referenced.

Use WeakReference instead of strong reference. For example, you can use WeakReference <Context> mContextRef;

For details about this part, refer to the Article in the Android document.

4. Thread-caused fault

Threads are also an important source of Memory leakage. The main cause of thread Memory leakage is the uncontrollable thread lifecycle. Let's consider the following code.

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.

In fact, the thread problem is not only the memory leakage, but also some catastrophic problems.

5. Unusual Cursor

Cursor Is a class used to manage data sets after data is queried by Android. Normally, if the queried data volume is small, there will be no memory problems, moreover, the virtual machine can ensure that the Cusor will be released eventually.

However, if the data size of the Cursor table is large, especially if Blob information exists, the memory occupied by the Cursor should be promptly released, rather than waiting for GC to process. In addition, Android obviously prefers programmers to manually close the Cursor, because in the source code, we find that if the garbage collector is used for collection, an error will be prompted to the user.

In one case, we cannot directly close Cursor, which is applied in CursorAdapter. But note that CursorAdapter does not automatically close Cursor at the end of Acivity, therefore, you need to manually disable it in the onDestroy function.

Reprinted, please note: how to optimize the memory for android Development

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.