Android Memory Management Overview

Source: Internet
Author: User
Tags thread

It is believed that the Android practitioner who walks over the steps, everyone will encounter oom situation. How to avoid and prevent the emergence of oom, for each programmer is indeed an essential ability. Let's talk today about the management of memory under the Android platform, and review the two concepts again before starting today's topic.

Memory leak: The space allocated by an object in the memory heap heap, and cannot be properly reclaimed by GC when it is no longer used or is not referenced. Most appear in irrational coding situations, such as registering a broadcast receiver in an activity, but unregister when the page is closed, a memory overflow occurs. In general, a large amount of memory leaks can cause oom.

OOM: That is, Outofmemoery, as the name implies is the memory overflow. Memory overflow refers to the app to the system to request more than the maximum threshold of memory requests, the system will not allocate extra space, will cause oom error. In our Android platform, most of the time it happens when the image is improperly processed and loaded.

The way of memory management, it is simply to understand and find out the reasons for the memory leak, and then based on these back to reasonable coding, to prevent the memory overhead and avoid the situation. To learn how to manage memory properly, it is best to understand the mechanism and principle of memory allocation first. Only a deep understanding of the internal principles, can really avoid oom. However, this article does not introduce the Jvm/davilk memory allocation mechanism, if interested, please check the historical message, previously done in the JVM Runtime Data Zone analysis of the sharing.

The maximum amount of memory the Android app can claim is 16MB, some say 24MB. This kind of thing, or personally use their own mobile phone test more reliable. The test method is also relatively simple, Java has a runtime class, mainly used for the app and the running environment interaction, the app does not create a runtime for us, but Java provides us with a single example of how to obtain Runtime.getruntime (). The MaxMemory () method gets the maximum memory that the system can allocate for the app, TotalMemory () Gets the amount of memory heap space that the app is currently allocating. I have two mobile phones, a oppo Find7, run the color OS, measured maximum memory allocation of 192MB; a language v9, running millet system, measured maximum memory allocation of 100MB. See the point of view, because Android is open source system, different handset manufacturers actually have the ability to modify this part of the authority, so it creates different brands and different systems of mobile phones, the app's memory support is not the same, and iOS 100MB is different. In general, the higher the configuration of mobile phone memory, manufacturers will also adjust the largest mobile phone support memory maximum threshold, especially now the flagship of the Sky released in the case. But developers in order to consider the development of the app's memory compatibility, can not guarantee the app running on the phone, only from the coding angle to optimize the memory.

Here's a key point to analyze the Android memory optimization.

1, the evil of the static

Static is a good thing, it is so easy to declare assignment calls, but there are also performance problems associated with them. Because the lifecycle of the static declaration variable is actually the same as the app lifecycle, it is somewhat similar to the application. If a large number of uses, it will occupy the memory space does not release, add up will also cause the constant cost of memory, until the hang off. The rational use of static is generally used to modify the basic data types or lightweight objects, as far as possible to avoid repairing collections or large objects, often used as cosmetic global configuration items, tool class methods, internal classes.

2. Irrelevant references

In many cases, we need to use a pass-through reference, but we are not sure whether the reference will be recycled in time. For example, more representative of the context of the leak, in many cases when the activity ended, because the other object is still pointing to the delay can not be recycled, which caused a memory leak. Consider the third suggestion at this point.

3. Use Softreference/weakreference/lrucache

Java, Android There is no such a mechanism, when the memory is tight or GC sweep, you can put some memory in time to release, and thus allocated to the need to allocate the place. The answer is yes, Java provides us with two solutions. If the cost of memory is more concerned about the app, you can consider using WeakReference, which is recycled when GC recycle sweeps through the area of memory, and if it is not so concerned, you can use SoftReference, which will automatically release if the memory request is insufficient. can also solve the problem of oom. At the same time Android since 3.0 also launched the LRUCache class, the use of LRU algorithm to release the memory, the same can be resolved oom, if compatible with the version of 3.0, please import v4 package. For the question of irrelevant references to the second article, we can consider using WeakReference to wrap it.

4. Cautious handler

Handler + thread is a good choice when dealing with asynchronous operations. But believe that when using handler, everyone will encounter a warning situation, this is lint for developers to remind. Handler runs on the UI thread, processing messages from MessageQueue, and if handler has a message to deal with but the activity page is over, the activity references are not recycled, causing a memory leak. Solution, one is to call in the OnDestroy method of the activity

Handler.removecallbacksandmessages (null); Cancels the processing of all messages, including pending messages, and declares that the inner class of the handler is static.

5. Bitmap Ultimate Killer

The improper handling of bitmap is likely to cause oom, most of which arise for this reason. Bitamp Bitmap is the weight of Android in the Fat Kid, so in the operation of course is very careful. 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. At the same time, if the requirements allow, you can also go to bitmap for a certain scale, through the Bitmapfactory.options insamplesize properties to control. If you just want to get the attributes of bitmap, you do not need to allocate the memory according to bitmap pixels, just use the Bitmapfactory.options injustdecodebounds attribute when parsing the BMP. Finally, we suggest that when loading network pictures, use soft references or weak references and local caching, recommend the use of Android-universal-imageloader or xutils, cattle produced, must be fine. A few days ago in the "Custom Control (iii) Inheritance control", also tidy up a, we can go to github download to see.

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/

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.