[Original] Android memory management-OnTrimMemory, androidontrimmemory

Source: Internet
Author: User

[Original] Android memory management-OnTrimMemory, androidontrimmemory

The Application has two methods related to memory management: onLowMemory () and onTrimMemory (int level). The source code is as follows:

  @CallSuper    public void onLowMemory() {        Object[] callbacks = collectComponentCallbacks();        if (callbacks != null) {            for (int i=0; i<callbacks.length; i++) {                ((ComponentCallbacks)callbacks[i]).onLowMemory();            }        }    }    @CallSuper    public void onTrimMemory(int level) {        Object[] callbacks = collectComponentCallbacks();        if (callbacks != null) {            for (int i=0; i<callbacks.length; i++) {                Object c = callbacks[i];                if (c instanceof ComponentCallbacks2) {                    ((ComponentCallbacks2)c).onTrimMemory(level);                }            }        }    }

From the source code, we can see that when the Application receives these two callbacks, it will notify its listener, and both the Activity and Service have registered the listener,

Therefore, we can override the two methods in the Application or in the component.

 

First, focus on onTrimMemory.

To better manage memory, the OnTrimMemory method is introduced in the API-14. This callback can be obtained from all components (Activity,Service,ContentProvider, AndApplication).

You should rewrite according to the restrictions of the Current DeviceOnTrimMemory (int) to gradually release the memory. Releasing resources through rewriting can help your app better respond to the overall system and make your app

To improve user experience. If you still do not release the memory when the system memory is low, the system will first kill your processes. In this way, when the user returns to the app, the user experience needs to be affected by the restart..

 

The level value of onTrimMemory (int) is not linear. It only provides clues about different states of memory.

1. callback time

  /**     * Called when the operating system has determined that it is a good     * time for a process to trim unneeded memory from its process.  This will     * happen for example when it goes in the background and there is not enough     * memory to keep as many background processes running as desired.  You     * should never compare to exact values of the level, since new intermediate     * values may be added -- you will typically want to compare if the value     * is greater or equal to a level you are interested in.     *     * <p>To retrieve the processes current trim level at any point, you can     * use {@link android.app.ActivityManager#getMyMemoryState     * ActivityManager.getMyMemoryState(RunningAppProcessInfo)}.     *     * @param level The context of the trim, giving a hint of the amount of     * trimming the application may like to perform.  May be     * {@link #TRIM_MEMORY_COMPLETE}, {@link #TRIM_MEMORY_MODERATE},     * {@link #TRIM_MEMORY_BACKGROUND}, {@link #TRIM_MEMORY_UI_HIDDEN},     * {@link #TRIM_MEMORY_RUNNING_CRITICAL}, {@link #TRIM_MEMORY_RUNNING_LOW},     * or {@link #TRIM_MEMORY_RUNNING_MODERATE}.     */    void onTrimMemory(int level);

This method is called when the operating system deems it a good time for a process to release useless memory. For example, if there is not enough memory to maintain all the background processes, the process is in the background.
We do not recommend that you use a precise value for comparison with level because it may increase the difference. We recommend that you determine whether a value is greater than or equal to the level you are interested in.

To obtain the current level of all processes, you can call {@ link android. app. ActivityManager # getMyMemoryState * ActivityManager. getMyMemoryState (RunningAppProcessInfo )}

 

2. Specific meanings of level values

 

 /**     * Level for {@link #onTrimMemory(int)}: the process is nearing the end     * of the background LRU list, and if more memory isn't found soon it will     * be killed.     */    static final int TRIM_MEMORY_COMPLETE = 80;        /**     * Level for {@link #onTrimMemory(int)}: the process is around the middle     * of the background LRU list; freeing memory can help the system keep     * other processes running later in the list for better overall performance.     */    static final int TRIM_MEMORY_MODERATE = 60;        /**     * Level for {@link #onTrimMemory(int)}: the process has gone on to the     * LRU list.  This is a good opportunity to clean up resources that can     * efficiently and quickly be re-built if the user returns to the app.     */    static final int TRIM_MEMORY_BACKGROUND = 40;        /**     * Level for {@link #onTrimMemory(int)}: the process had been showing     * a user interface, and is no longer doing so.  Large allocations with     * the UI should be released at this point to allow memory to be better     * managed.     */    static final int TRIM_MEMORY_UI_HIDDEN = 20;    /**     * Level for {@link #onTrimMemory(int)}: the process is not an expendable     * background process, but the device is running extremely low on memory     * and is about to not be able to keep any background processes running.     * Your running process should free up as many non-critical resources as it     * can to allow that memory to be used elsewhere.  The next thing that     * will happen after this is {@link #onLowMemory()} called to report that     * nothing at all can be kept in the background, a situation that can start     * to notably impact the user.     */    static final int TRIM_MEMORY_RUNNING_CRITICAL = 15;    /**     * Level for {@link #onTrimMemory(int)}: the process is not an expendable     * background process, but the device is running low on memory.     * Your running process should free up unneeded resources to allow that     * memory to be used elsewhere.     */    static final int TRIM_MEMORY_RUNNING_LOW = 10;    /**     * Level for {@link #onTrimMemory(int)}: the process is not an expendable     * background process, but the device is running moderately low on memory.     * Your running process may want to release some unneeded resources for     * use elsewhere.     */    static final int TRIM_MEMORY_RUNNING_MODERATE = 5;

 

When your app is in the background:

TRIM_MEMORY_COMPLETE: the current process is at the end of the LRU list. If there is not enough memory, it will soon be killed. At this time, you should release any resources that do not affect app operation.

TRIM_MEMORY_MODERATE: the current process is in the middle of the LRU list. If the system requires memory further, your process may be killed.

TRIM_MEMORY_BACKGROUND: the current process is in the header of the LRU list. Although your process will not be killed by the high-performance killer, the system has begun to prepare to kill other processes in the LRU list,

Therefore, you should try to release the resources that can be quickly replied to ensure that the resources can be quickly restored when the user returns your app. .

 

When the visibility of your app changes:

TRIM_MEMORY_UI_HIDDEN: the interface of the current process is invisible. This is a good time to release resources related to the UI.

 

When your app is running:

TRIM_MEMORY_RUNNING_CRITICAL: although your process will not be killed, the system is ready to kill other background processes. At this time, you should release useless resources to prevent performance degradation.

The next stage is to call "onLowMemory ()" to report and kill the background process. In particular, the situation has begun to affect users.

TRIM_MEMORY_RUNNING_LOW: although your process will not be killed, the system is ready to kill other background processes. You should release unnecessary resources to provide system performance. Otherwise

Affects user experience.

TRIM_MEMORY_RUNNING_MODERATE: The system is in a low-memory state. Your process is running but will not be killed.

 

Let's talk about onLowMemory.

The OnLowMemory method is used before OnTrimMemory is introduced. If your app runs on a API-14 + machine, you should use OnTrimMemory (int), and The OnLowMemory call time is probably equivalent to TRIM_MEMORY_COMPLETE.

 

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.