On memory optimization of Android application and memory leakage of handler

1、 Android memory basic physical memory and process memory physical memory is the ram on the mobile device. When an Android program is started, a Dalvik VM process will be started, and the system will allocate a fixed memory space (16m, 32m, uncertain). This memory space will be mapped to an area on the ram. Then the Android program will run in this space. Java will divide this space into stack memory and heap memory. Stack stores the reference of the object, and heap stores the actual object data. Objects will be created during program operation. If memory is not properly managed, such as not reclaiming invalid space in time, memory leakage will be caused. If it is serious, the memory used may exceed the memory allocated by the system, that is, memory overflow oom, causing the program to get stuck or even exit directly.

Memory leak JAVA memory leak means that some objects (garbage objects) in the process have no use value, but they can be directly or indirectly referenced to GC roots, so they cannot be recycled by GC. The GC mechanism (garbage collection mechanism) of Dalvik VM will automatically recycle when too much memory is occupied, which will cause memory overflow oom in severe cases.

Memory overflow oom overflow occurs when the Java heap space requested by the application exceeds the Dalvik VM heapgrowthlimit. Note: oom does not mean insufficient memory. As long as the requested heap exceeds the Dalvik VM heapgrowthlimit, even if the memory is sufficient, it will overflow. The effect is that more processes can be resident in memory.

What will the system do if ram is insufficient? Android's memory killer will kill lower priority processes and let higher priority processes get more memory.

Default memory recycling mechanism of Android system

Process priority: foregroup process, visible process, service process, background process and empty process; If the user presses the home key to return to the desktop, the app becomes a background process; If you press back to return, it becomes an empty process, and activitymanagerservice directly manages the memory resource allocation of all processes. All processes need to apply for or release memory through the activitymanagerservice object. Garbage collection is performed irregularly. When there is not enough memory, it will traverse the heap space and delete the garbage object. The larger the heap memory, the longer the GC takes

2、 Optimizing bitmap optimizing bitmap consumes a lot of memory, and in Android, when reading bitmap, the picture stack allocated to the virtual machine is generally only 8m, so it often causes oom problems. Therefore, it is necessary to optimize the use of bitmap:

Picture display: load pictures of appropriate size. For example, do not load large pictures where thumbnails are displayed. Image recycling: after using bitmap, use bitmap. Recycle() to recycle it in time. Question: doesn't Android have its own garbage collection mechanism? Why recycle manually here. Bitmap objects are not generated by new, but are produced by bitmapfactory. Moreover, through the source code, it can be found that the bitmap object is generated by calling JNI (methods such as nativedecodestream()). Therefore, loading bitmap into memory includes two parts, Dalvik memory and Linux kernel memory. The former will be automatically recycled by the virtual machine. The latter must call nativecrecycle () internally through the recycle () method to make the Linux kernel recycle. Catch oom exception: set the emergency handling method in case of oom in the program. Image cache: image compression such as memory cache and hard disk cache: directly using ImageView to display bitmap will occupy a lot of resources, especially when the image is large, oom is easy to occur. You can use bitmapfactory.options to compress pictures. Picture pixel: Android default color mode is ARGB_ 8888, with the highest display quality and the largest memory consumption. If the requirements are not high, RGB can be used_ 565 and other modes. Picture size: picture length * width * bytes occupied by unit pixel ARGB_ 4444: each pixel occupies 2byte memory ARGB_ 8888: each pixel occupies 4 bytes of memory (default) RGB_ 565: each pixel occupies 2byte memory object reference type

Strong reference strong: object object = new object(). When the memory is insufficient, the Java virtual machine would rather throw an oom memory overflow exception than easily recycle strong reference objects to solve the problem of insufficient memory; Soft reference: the memory will be recycled only when it reaches a certain threshold, which is often used for caching; Weak reference: as long as it is scanned by the GC thread, it will be recycled; Virtual reference if you want to avoid oom, use soft reference objects, that is, recycle when memory is fast enough; If you want to recycle some objects that occupy a large amount of memory as soon as possible, such as bitmap, you can use weak references, which can be recycled quickly. However, if you want to cache the bitmap, do not use weak references, because it will soon be recycled by the GC, resulting in cache failure. For Java object reference types, please refer to my other article pool

Object pool: if an object needs large resource overhead when it is created, it can be put into the object pool, that is, the object can be saved and directly taken out for use when needed next time, instead of creating the object again. Of course, maintaining the object pool also requires some overhead, so it should be measured. Thread pool: similar to the object pool, thread objects are placed in the pool for repeated use to reduce the overhead of repeatedly creating threads.

3、 Analysis and solution of handler memory leak 1. Introduction first, please browse the following handler code:

This is a very common piece of code when using handler. However, it can cause serious memory leakage. In actual writing, we often get the following warnings:

In Android, handler classes should be static or leaks might occur?

2. Analysis (1). From the Android perspective, when an Android application is started, the framework will create a looper object for the main thread of the application. This looper object contains a simple message queue, message queue, and can process the messages in the queue circularly. These messages include most application framework events, such as activity life cycle method calls, button clicks, etc. these messages will be added to the message queue and processed one by one. In addition, the looper object of the main thread will accompany the whole life cycle of the application.

Then, when a handler object is instantiated in the main thread, it will be automatically associated with the message queue of the main thread looper. All messages sent to the message queue will have a reference to the handler, so when the looper processes the message, it will call back [handler #handlemessage (message)]( http://developer.android.com/reference/android/os/Handler.html#handleMessage (Android. OS. Message) method to process messages.

(2) From the perspective of Java, in Java, non static internal classes and anonymous classes will potentially reference their external classes. However, static inner classes do not.

(3) Please browse the following code for the source of leakage:

When the activity is finished, the delayed message will be kept in the message queue of the main thread for 10 minutes until it is processed. Moreover, as can be seen from the above, this message holds a reference to the handler, and the handler holds a potential reference to its external class (here, sampleactivity). This reference relationship will remain until the message is processed, which prevents the sampleactivity from being recycled by the garbage collector and causes the application to leak. Note that the runnable class in the above code -- a non static anonymous class -- also holds a reference to its external class. This also leads to leakage.

3. Leak solution first, the source of memory leak has been identified above:

As long as there is an unprocessed message, the message will reference the handler, and the non static handler will reference the external class, i.e. activity, so that the activity cannot be recycled, resulting in leakage; Runnable class is a non static anonymous class, which also references external classes. In order to solve the problems encountered, we should make it clear that static internal classes do not hold references to external classes. Therefore, we can put the handler class in a separate class file, or use a static inner class to avoid leakage. In addition, if you want to call the external class activity inside the handler, you can use a weak reference to point to the activity inside the handler, so that unification will not lead to memory leakage. The anonymous class runnable can also be set as a static class. Because static anonymous classes do not hold references to external classes.

4. Summary although the difference between static and non static classes is not big, it must be understood by Android developers. At least we should be clear that if the life cycle of an internal class instance is longer than that of an activity, we should never use non static internal classes. The best approach is to use a static inner class, and then use a weak reference in the class to point to the activity.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>