Memory management mechanisms in Android and how to use them correctly

Source: Internet
Author: User

Overview

From the operating system point of view, memory is a piece of data storage area, belonging to the operating system can be scheduled resources. In modern multitasking (process) operating systems, memory management is particularly important, and the operating system needs to allocate memory resources reasonably for each process, so the memory management mechanism of the operating system can be understood in two ways.

First: the allocation mechanism. allocate a reasonable amount of memory per process to ensure that each process runs properly, not enough memory to use, or too much memory per process.

Second: recycling mechanism. when the system is running out of memory, a reasonable mechanism for recycling is needed to ensure that the new process can run properly. When recycling is about killing processes that are taking up memory, the operating system needs to provide a reasonable mechanism to kill these processes to ensure fewer side effects.

And as a multi-process operating system, the Android system of memory management, but also a set of their own methods. Unlike a PC, Android, as a mobile operating system, typically has fewer memory resources than a PC, so it requires more careful management of memory.

Memory management mechanism allocation mechanism in Android

When Android allocates memory for each process, it uses a flexible allocation method, which is not allocating a lot of memory to each process at first, but assigning a "enough" amount to each process. This amount is determined by the actual physical memory size of each device. As your app runs, you may find that your current memory may not be enough, and Android will allocate some extra memory size for each process. However, these extra sizes are not random and limited, and it is not possible for the system to allocate an unlimited size for each app.

The aim of the Android system is to maximize the number of processes in memory so that the next time the user launches the application, no need to recreate the process, just restore the existing process, reduce the application startup time and improve the user experience.

Recycling mechanism

The way Android uses memory is "maximized", which inherits the benefits of Linux. Android saves as much data as it can in memory, even though some processes are no longer in use, but its data is stored in memory, so Android does not now recommend an explicit "quit" app. Because of this, the next time the user launches the application, only need to restore the current process, no need to recreate the process, so that the application can reduce the startup time. The Android system will need to kill other processes to reclaim enough memory only when the Android system finds that the memory is not available and needs to reclaim the memory. But Android is not just killing a process, such as a process that is interacting with the user, and the consequences are terrifying. So Android will have limited cleanup of processes that are no longer in use to ensure minimal side effects.

The Android kill process has two reference conditions:

Process Priority:

Android assigns the concept of priority to each process, and the lower the priority process, the more likely it is to be killed. There are a total of 5 process priorities in Android. The specific meaning is no longer given here.

Foreground process: Normal will not be killed

Visible process: Normal will not be killed

Service process: Normal will not be killed

Background process: stored in an LRU cache list, first kill the process at the end of the list

Empty process: Normally, Android does not save these processes in order to balance the overall performance of the system

Recycling Benefits:

When the Android system starts to kill processes in the LRU cache, the system will determine the recycling benefits of each process after it has been killed. Because Android always tends to kill a process that can reclaim more memory, it can kill fewer processes to get more memory. The fewer processes killed, the smaller the impact on the user experience.

What is the official recommended app memory usage? 1. When the service completes the task, try to stop it.

Because of processes with service components, the lowest priority is also the service process, which affects the system's memory reclamation. Intentservice can do the job well.

2. When the UI is not visible, release some resources that are only used by the UI.

The system notifies the app UI that it is hidden, based on the Trim_memory_ui_hidden level of events in the Ontrimmemory () callback method.

3, when the system memory tense, as much as possible to release some non-important resources.

The system will be based on the Ontrimmemory () callback method to notify the memory tense state, the app should be based on different levels of memory tension, to reasonably release resources to ensure that the system can reclaim more memory. When the system recycles enough memory, it does not have to kill the process.

4. Check your maximum available memory size.

This is useful for some caching frameworks, because the cache pool size of the cache framework should normally be specified as a percentage of the maximum memory in order to better fit more devices. Information about the available memory size is obtained through Getmemoryclass () and Getlargememoryclass ().

5, avoid misuse of bitmap caused by memory waste.

Compressing bitmap According to the current device resolution is a good choice, after using the bitmap, remember to use recycle () to release the bitmap. Use a soft or weak reference to refer to a bitmap, and use the LRU cache to cache the bitmap.

6. Use a data container optimized for memory.

With limited memory for mobile devices, Android offers a set of memory-optimized data containers to replace the data containers provided by the JDK's native. But the disadvantage is that the complexity of time is improved. such as Sparsearray, Sparsebooleanarray, Longsparsearray,

7, aware of the excessive consumption of memory.

The enum type consumes more than twice times the memory of the constant, so avoid using enums and use constants directly.

Each Java class (including anonymous inner classes) requires 500Byte of code.

Each instance of a class has an additional memory consumption of 12-16 byte.

Note that similar to HashMap, there is a need to generate class data containers internally, which consumes more memory.

8, the abstract code will also bring more memory consumption.

If your "abstract" design does not actually bring much benefit, then don't use it.

9. Use nano Protobufs to serialize data.

A language and platform-neutral serialization protocol designed by Google is faster, smaller, and simpler than XML.

10. Avoid using the framework of dependency injection.

The dependency injection framework needs to open additional services to scan the annotation of code in the app, so additional system resources are required.

11. Use the Zip-aligned apk.

The APK is zip-aligned, compressing its internal resources, which consumes less memory at run time.

12, the use of multi-process.

What should be an app that fits the Android memory management mechanism?

An app that follows the Android memory management mechanism. Should have the following characteristics:

1, less memory consumption.

2, in the appropriate time, reasonable release of the system resources.

3, in the case of tight system memory, can release most of the non-important resources, to provide available memory for the Android system.

4, can reasonably in the special life cycle, save or restore important data, so that the system can correctly re-restore the application.

Why does the app conform to this memory management mechanism? What is the benefit of doing this?

An app that follows Android's memory management mechanism, in Android, is a good citizen, then the system is naturally inclined to protect these people, and to kill those who are not high-quality. So in line with the Android memory management mechanism, for Android systems and apps, it is a winning process. If every app follows this rule, the Android system will be smoother and better, and the app will stay in memory for longer periods of time.

How do you write apps that fit the Android memory management system in this way?

The main reference is the official recommended memory usage, to design and write apps.

Avoid creating unnecessary objects.

Manage resources wisely in the right life cycle.

Proactively free up more resources when system memory is low.

How do I use less memory resources when writing Android apps?

Avoid creating objects that you do not need.

For example, use StringBuffer instead of a number of strings added to the operation.

Using the original type instead of the wrapper type, int consumes less resources than the integer.

Two parallel array of attributes, better than an array of objects that contain these two properties. This makes sense when designing data containers, such as Class A with two attributes a (int, String), using int[] and string[] better than a[].

Use constants instead of enums.

The original type is used when the wrapper class is less used, and the original type can be used.

What if the app really needs a lot of memory? Multi-process

Move a module that consumes too much memory, or a module that needs to run in the background for a long time, to run in a separate process. Android allocates memory separately for each process, so the app can theoretically use more memory. But multi-process is a double-edged sword, the wrong use, will bring a lot of other problems, here no longer talk about this topic.

Request Large Memory

In the <application> tab, setting Largeheap to True,android system will allocate additional memory for the application. But don't misuse this method. If an app really needs big memory, such as an app that needs to open a lot of big pictures, you can use this method. Do not use this method because of oom, this time more should check the app code is unreasonable.

How should developers be aware of app memory management? Memory overflow

Memory overflow, is oom, that is, memory is not enough. There is a typical example of loading a lot of uncompressed bitmap into memory, these bitmap are large, but really in use, must be in memory, so this time the memory is not enough. At this point, the app will not be applying for more memory, and the system is going to throw oom.

Solve this problem: 1, reduce the memory occupied by each object, such as compressed pictures. 2, the application of large memory.

Memory leaks

Memory leaks, that is, memory Leak, that is, the GC has been recycled back to the system, and has not been GC. Most because of unreasonable object references, when an object is no longer in use, because of a code problem, there is no correct release of the reference, resulting in a memory leak.

Solve this problem: 1, through a variety of memory analysis tools, such as MAT, analyze the memory image file at run time, find out the code that caused the memory leak, and then modify it. 2, appropriate use of weakreference.

Memory management mechanisms in Android and how to use them correctly

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.