Memory Management for Android Development

Source: Internet
Author: User

Memory Management for Android Development

I believe that every Android practitioner who has come through step by step will encounter OOM. How to avoid and prevent the emergence of OOM is indeed an essential capability for every programmer. Today, let's talk about memory management on the Android platform. Before starting today's theme, let's review the two concepts.

Memory leakage: The space allocated by the object in the heap in the memory. GC cannot recycle normally if it is no longer used or referenced. In most cases, the memory overflow occurs when a broadcast receiver is registered in the Activity but unRegister is disabled on the page. Usually, a large amount of memory leakage will cause OOM.

OOM: OutOfMemoery, as its name implies, refers to memory overflow. Memory overflow refers to the memory request from the APP to the system that exceeds the maximum threshold value. The system will not allocate extra space and cause OOM error. On our Android platform, most cases occur when images are improperly loaded.

Memory Management is nothing more than understanding and finding out the cause of Memory leakage, and then using reasonable Encoding Based on these transcodes to prevent memory overhead. To learn how to manage the memory properly, it is best to first understand the mechanism and principle of memory allocation. Only by deeply understanding the Internal principles can we truly avoid OOM. However, this article does not introduce the Jvm/Davilk memory allocation mechanism. If you are interested, please check the history and share the previous article titled "Regional Analysis of JVM runtime data.

What is the maximum memory size that the Android APP can apply for? Some say 16 MB, others say 24 MB. This kind of thing is more reliable with your own mobile phone testing. The test method is also relatively simple. Java has a Runtime class, which is mainly used for interaction between the APP and the Runtime environment. The APP does not create a Runtime instance for us, however, Java provides the Runtime method for obtaining a single instance. getRuntime (). Use the maxMemory () method to obtain the maximum memory that the system can allocate to the APP. Use totalMemory () to obtain the heap space allocated by the APP. I have two mobile phones in my hand, one Oppo find7 and a Color OS. The maximum memory size is 192 MB. The other is Tianyu v9 and the maximum memory size is 100 MB when I run the Xiaomi system. As Android is an open-source system, different mobile phone manufacturers actually have the ability to modify this part of permissions, which leads to mobile phones of different brands and systems, the APP's memory support is also different, and IOS's persistent MB is different. Generally, the higher the phone memory configuration, the manufacturer will increase the maximum memory threshold supported by the phone, especially when the flagship machine is released all over the day. However, in order to consider the compatibility of the developed APP's memory, developers cannot guarantee the mobile phone on which the APP runs. They can only optimize the memory from the encoding perspective.

Next we will analyze the key points of Android memory optimization one by one.

1. static

Static is a good thing. Declaring a value assignment call is so simple and convenient, but there are also performance problems. Because the life cycle of static declared variables is similar to that of the APP, it is a bit similar to that of the Application. If a large amount of memory is used, it will occupy the memory space and will not be released. Otherwise, memory overhead will occur until it is suspended. Rational use of static is generally used to modify basic data types or lightweight objects. It is often used to modify global configuration items, tool methods, and internal classes.

2. Unrelated references

In many cases, we need to transfer references, but we cannot ensure that the references can be recycled in a timely manner. For example, a typical Context leakage occurs. In many cases, when the Activity ends, it is unable to recycle because it is still pointed to by other objects, resulting in Memory leakage. In this case, you can consider the third suggestion.

3. Use SoftReference/WeakReference/LruCache

Is there such a mechanism in Java and Android? When the memory is tight or the GC is swept away, some memory usage can be promptly released and allocated to the areas to be allocated. The answer is yes. java provides us with two solutions. If the APP pays more attention to memory overhead, you can use WeakReference. This will be recycled when GC recycle sweeps through this memory area. If not, you can use SoftReference, it will be automatically released when the memory application is insufficient, and can also solve the OOM problem. At the same time, the LruCache class has also been released for Android 3.0 and later versions. The LRU algorithm is used to release the memory. The same solution can solve OOM. If it is compatible with version 3.0, Please import the v4 package. For the second irrelevant reference, we can use WeakReference to wrap the parameter.

4. Careful handler

Handler + thread is a good choice when processing asynchronous operations. However, I believe that when using handler, everyone will encounter a warning. This is a reminder from lint for developers. Handler runs on the UI thread and constantly processes messages from MessageQueue. If handler still has messages to be processed but the Activity page has ended, the reference of the Activity will not be recycled, this causes memory leakage. Solution: Call the onDestroy method of the Activity

Handler. removeCallbacksAndMessages (null); cancels the processing of all messages, including the messages to be processed; second, declares that the internal class of handler is static.

5. Bitmap ultimate killer

The improper processing of Bitmap is very likely to cause OOM, which is the cause in most cases. Bitamp bitmap is a well-deserved fat boy in Android, so you should be very careful when operating. Because Dalivk does not take the initiative to recycle, developers need to recycle when Bitmap is not used. Timely release is very important during use. At the same time, if the demand permits, you can also zoom in and out of BItmap and control through the inSampleSize attribute of BitmapFactory. Options. If you only want to obtain the Bitmap attribute, you do not need to allocate memory based on the BItmap pixel. You only need to use the inJustDecodeBounds attribute of BitmapFactory. Options when parsing and reading Bmp. We recommend that you use soft references or weak references for local caching when loading network images. We recommend that you use android-universal-imageloader or xUtils, which must be a high-quality product. When I talked about "Custom Control 3) Inheritance control" a few days ago, I also sorted it out. You can download it from Github.

6. Close Cursor in time

When you query the SQLite database, a Cursor is returned. When the query is completed, it is closed in time, so that the query result set can be collected in time.

7. Page background and image loading

When setting the background and image in the layout and code, if it is solid color, use color as much as possible; if it is a rule image, use shape drawing as much as possible; if it is a little complex, use 9patch graph; if nine patches cannot be used, the image is cut for several mainstream resolution models.

8. ListView and GridView item Cache

For mobile devices, especially the android ecosystem with uneven hardware, page rendering is actually very time-consuming, and findViewById is also quite slow. Therefore, you do not need to reuse the View, which is especially significant when you have a list. sliding is often quite slow. For details, refer to the historical article "another way of writing ViewHolder".

9. BroadCastReceiver and Service

To bind a broadcast or service, remember to unbind it when you do not need it.

10. I/O Stream

The I/O Stream operation is complete, and the read/write process is complete. Remember to close it.

11. threads

When the thread no longer needs to continue execution, remember to close it in time. It is not easy to enable too many threads. It is generally the best as the number of kernels on your machine. We recommend that you use the thread pool when enabling the thread.

12. String/StringBuffer

StringBuffer is recommended when many characters need to be spliced.

Today, there is no code, pure text, and pure hands. It is very hard. After sorting out so many optimization strategies, I believe that we will never encounter OOM again after understanding them.

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.