Android Memory management mechanism

Source: Internet
Author: User
Tags sqlite database

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.

Android app can apply for the maximum memory size, 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 static static is a good thing, declaring the assignment call is so simple and convenient, but accompanied by a 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 to pass the reference, but we can not ensure that the reference passed out after the timely recovery. 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, the use of Softreference/weakreference/lrucache Java, Android, there is no such a mechanism, when the memory is tight or GC sweep of the case, you can timely some memory consumption to release, 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 in the handling of asynchronous operations, Handler + thread is a good choice. 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 is to call handler.removecallbacksandmessages (null) in the OnDestroy method of the activity, and cancel the processing of all messages, including pending messages;The second is to declare that the inner class of handler is static. 5, Bitmap Ultimate Killer bitmap improper handling is likely to cause oom, most of the situation is due to this reason. 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. 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)   inheritance control", also organized a, you can go to github download to see. 6, cursor timely close in the query 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 in the layout and code to set the background and picture, if it is a solid color, try to use color, if it is a regular graphic, as far as possible to use shape drawing, if a little more complex point, you can use the 9patch diagram, if you cannot use the 9patch case, For several mainstream resolutions of the model for the cut. 8, ListView and GridView Item cache 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 binding broadcast and services, be sure to remember when not needed to unbind. 10, I/O stream I/O flow operation completed, read and write end, remember to close. 11, thread thread no longer need to continue to carry out the time to remember to shut down, open the number of threads is not easy to too much, generally and their machine core number as the best, recommended to open the thread, the use of thread pool. 12, String/stringBuffer when there are more characters need splicing, we recommend the use of StringBuffer.

No code today, 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.

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.