App development experience Sharing: The path to Android memory management

Source: Internet
Author: User

Abstract for mobile app development, whether it's Android or iOS, memory is always a pain. But a reasonable writing code avoids the advent of oom.

Believe that step by step of the Android practitioners, everyone will encounter oom situation. How to avoid and prevent the advent of oom, for every programmer is really a necessary ability. Today we talk about the management of memory under the Android platform, and before we begin today's topic, we'll review two concepts again.

Memory leak: The amount of space allocated by an object in the memory heap heap that cannot be recycled by GC when it is no longer in use or if no reference is pointed to it. Most appear in unreasonable coding situations, such as registering a broadcast receiver in activity, but unregister when the page is closed, there is a memory overflow phenomenon. Typically, a large amount of memory leaks can cause oom.

OOM: Outofmemoery, as the name implies, is memory overflow. A memory overflow is a memory request that the app requests to the system for exceeding the maximum threshold, and the system no longer allocates extra space, which can cause oom error. In our Android platform, most of the situation is in the picture when the improper processing load.

The way of memory management is to understand and find out the causes of memory leaks, and then based on these anti-rational coding, to prevent and then avoid excessive memory overhead situation. To learn how to manage memory reasonably, it is best to first understand the mechanism and principle of memory allocation. Only deep understanding of the internal principles, can really avoid the occurrence of oom. However, this article does not introduce the mechanism of jvm/davilk memory allocation, if interested, please review the historical news, previously did the "JVM Runtime data Region analysis" share.

What is the maximum memory size that Android app can apply for, some say 16MB, some say 24MB. This kind of thing, or in person with their own mobile phone test more reliable. The test method is also relatively simple, Java has a runtime class, mainly used as an app to interact with the operating environment, the app does not create a runtime instance for us, but Java provides us with a single case to get the way Runtime.getruntime (). The MaxMemory () method gets the maximum memory that the system can allocate for the app, and TotalMemory () Gets the amount of memory heap space currently allocated by the app. I have two mobile phones, a oppo Find7, running the color OS, measured maximum memory allocation of 192MB; a day language v9, running millet system, measured maximum memory allocation of 100MB. This can see the point, because Android is open source system, different handset manufacturers actually have the ability to modify this part of the power, so it caused the different brands and different systems of mobile phones, for the app's memory support is not the same, and iOS 100MB is different. In general, the higher the mobile phone memory configuration, the manufacturer will also increase the maximum value of the memory supported by the mobile phone, especially in the case of the flagship machine published all over the sky now. But developers have to consider the memory compatibility of the developed app, unable to guarantee the app to run on what kind of phone, only from the encoding angle to optimize memory.

Below we analyze the key points of Android memory optimization.

1, the evil of the static

Static is a good thing, declaring the invocation of an assignment to be simple and convenient, but with the accompanying performance problem. Since the life cycle of the static declaration variable is actually the same as the life cycle of the app, it is somewhat similar to application. If a large number of uses, it will occupy the memory space is not released, a few will also cause the memory of the constant overhead, until hung out. The rational use of static is generally used to modify the basic data types or lightweight objects, to avoid repairing the collection or large objects, commonly used to decorate global configuration items, tool class methods, internal classes.

2. Irrelevant references

In many cases, we need to use a pass-through reference, but we cannot ensure that the reference is passed out in a timely manner. For example, more representative of the context leaks, in many cases, when the activity is over, because the other objects are still pointing to cause the delay can not be recycled, which caused a memory leak. The third suggestion can be considered at this point.

3. Use Softreference/weakreference/lrucache

There is no such mechanism in Java, Android, when the memory is tight or GC sweep, it can be in time to release some memory, so as to allocate to the place to be allocated. The answer is yes, and Java provides us with two of solutions. If you are concerned about the memory overhead of the app, you can consider using WeakReference, when GC reclamation swept through this area of memory will be recycled, if not so concerned, you can use SoftReference, it will be automatically released in case of insufficient memory request, It can also solve the oom problem. Android since 3.0 also launched the LRUCache class, using the LRU algorithm to free memory, the same can solve oom, if compatible with 3.0 version, please import v4 package. On the question of irrelevant references to the second article, we can consider using WeakReference to wrap the message.

4, cautious handler

Handler + thread is a good choice when it comes to handling asynchronous operations. But believe that when using handler, everyone will encounter a warning situation, this is lint for the developer's reminder. Handler runs on the UI thread, constantly processes messages from MessageQueue, and if handler has a message to process but the activity page has ended, the activity's reference is not actually recycled, which creates a memory leak. Solution, one that is called in the activity's OnDestroy method

Handler.removecallbacksandmessages (NULL), cancels all processing of messages, including pending messages, and second, declares that the inner class of handler is static.

5. Bitmap Ultimate Killer

The improper handling of bitmap is likely to cause oom, most of which is due to this cause. Bitamp Bitmap is a well-deserved fat kid in Android, so be careful when it comes to operation. Since DALIVK does not take the initiative to recycle, developers need to recycle out when bitmap is not being used. In the process of use, timely release is very important. Share components, at the same time, if the requirements allow, you can also go to bitmap for a certain scale, through the Bitmapfactory.options Insamplesize property control. If you just want to get bitmap properties, you don't need to allocate memory based on bitmap pixels, just use Bitmapfactory.options's Injustdecodebounds property when parsing the BMP. Finally, we recommend that you load the network pictures, using soft references or weak references and local cache, recommended to use Android-universal-imageloader or xutils, cattle produced, will be a boutique. A few days ago in the "Custom control (c) inherit the control", also organized a, you can go to github download to see.

6. Cursor closed in time

When querying the SQLite database, will return a cursor, when the query is complete, close immediately, so that the query result set can be retrieved in a timely manner.

7. Page background and picture loading

When setting the background and picture in the layout and code, if it is a solid color, use color as much as possible, if it is a regular graphic, use shape to draw, if it is slightly more complex, you can use 9patch graph, if you cannot use 9patch, the model for several main resolutions is cut.

8. The item cache for ListView and GridView

For mobile devices, especially the hardware of the uneven Android ecosystem, page rendering is actually very time-consuming, Findviewbyid is quite slow. So do not reuse view, in the list when it is particularly significant, often the phenomenon of sliding very card. Refer to the historical article "another way of saying Viewholder"

9, Broadcastreceiver, Service

To bind broadcasts and services, be sure to remember to unbind them when they are not needed.

10. I/O flow

I/O stream operation finished, read and write end, remember to close.

11. Threads

Threads no longer need to continue to execute the time to remember to shut down, open the number of threads is not easy to too much, share to the general and their own machine core number of the best, recommended to open the thread, the use of thread pool.

12, String/stringbuffer

It is recommended to use StringBuffer when more characters are needed for stitching.

Today there is no code, plain text, pure hand hit, pretty hard. Sorting out so many optimization strategies, I believe that everyone in understanding after use, will never encounter Oom.

App development experience sharing: The way Android Memory manages

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.