Android Code memory optimization recommended-ontrimmemory optimization

Source: Internet
Author: User

Original http://androidperformance.com/2015/07/20/Android code memory optimization recommended-ontrimmemory optimization/

The Ontrimmemory callback is an API provided after Android 4.0, which is provided to developers, and its main purpose is to prompt the developer to free up memory by processing some of the resources when the system is out of memory, thus avoiding being killed by the Android system. This applies at the next boot time, the speed will be relatively fast.

This paper explains the use process and effect of ontrimmemory callback from various aspects by way of question and answer. To develop high-performance and user-friendly Android apps, you shouldn't miss this article.

0. What is the function of Ontrimmemory callback?

Ontrimmemory is a callback that Android added after 4.0, and any class that implements the ComponentCallbacks2 interface can override this callback method. The main function of Ontrimmemory is to instruct the application to release its own memory in different situations to avoid being killed directly by the system and to improve the user experience of the application.

The Android system will call this function according to different levels of memory usage, and pass in the corresponding level:

    • Trim_memory_ui_hidden indicates that all UI interfaces of the application are hidden, that is, the user clicked the home key or the back key to make the UI interface of the app invisible. Some resources should be released at this time.

      Trim_memory_ui_hidden This grade is more commonly used, and the following six relationships are not very strong, so say alone.

The following three levels are callbacks when our application really runs:

    • Trim_memory_running_moderate indicates that the application is functioning properly and will not be killed. But now that the phone's memory is a bit low, the system may start to kill the process according to the LRU cache rules.
    • Trim_memory_running_low indicates that the application is functioning properly and will not be killed. But now that the phone's memory is very low, we should release some unnecessary resources to improve the performance of the system, and this will directly affect the performance of our application.
    • Trim_memory_running_critical indicates that the application is still working, but the system has killed most of the cached processes according to the LRU cache rules. At this time we should try to release any unnecessary resources, otherwise the system may continue to kill all the processes in the cache, and start to kill some of the processes that should be kept running, such as services running in the background.

When the application is cached, you receive the following types of callbacks:

    • Trim_memory_background says the phone is currently low on memory and the system is ready to start cleaning up the process based on the LRU cache. This time our program in the LRU cache list of the nearest location, is not likely to be cleaned out, but then to release some of the more easily recovered resources can make the phone's memory more abundant, so that our program is kept in the cache for a longer time, so that when the user returned to our program will feel very smooth, Instead of going through a reboot process.
    • Trim_memory_moderate said the phone is currently low in memory, and our program is in the middle of the LRU cache list, if the phone memory is not further released, then our program has been killed by the system risk.
    • Trim_memory_complete said the phone is currently low in memory, and our program is at the very edge of the LRU cache list, the system will give the highest priority to kill our application, at this time should be as much as possible to release everything that can be released.
1. What components can implement Ontrimmemory callbacks?
    • Application.ontrimmemory ()
    • Activity.ontrimmemory ()
    • Fragement.ontrimmemory ()
    • Service.ontrimmemory ()
    • Contentprovider.ontrimmemory ()
2. What resources can be released in the Ontrimmemory callback?

Usually in the architecture phase it is necessary to think clearly about what we have to live in memory, and what are the accompanying interfaces. In general, there are several resources that need to be released:

    • The cache cache includes some file caches, image caches, and so on, which are useful when users are working properly, but when your application UI is not visible, these caches can be erased to reduce memory usage. such as the caching of third-party picture libraries.
    • Some dynamically generated view that is dynamically added. These dynamically generated and added view, which is used only in a few cases, can be released and then dynamically generated the next time you use it. Native desktops, for example, release all Appscustomizepagedview resources in the Ontrimmemory trim_memory_moderate hierarchy to ensure that the desktop is not easily killed when memory is low.
2.1 Example: Releasing a view that is not commonly used.

Code Source: Launcher

Launcher.java:

?
1234567 @Overridepublicvoid onTrimMemory(int level) {    super.onTrimMemory(level);    if(level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {        mAppsCustomizeTabHost.onTrimMemory();    }}


Appscustomizetabhost.java:

?
123456 publicvoidonTrimMemory() {    mContent.setVisibility(GONE);    // Clear the widget pages of all their subviews - this will trigger the widget previews    // to delete their bitmaps    mPagedView.clearAllWidgetPages();}


Appscustomizepagedview.java:

?
1234567891011 public void clearAllWidgetPages() {    cancelAllTasks();    int count = getChildCount();    for (int i = 0; i < count; i++) {        View v = getPageAt(i);        if (v instanceof PagedViewGridLayout) {            ((PagedViewGridLayout) v).removeAllViewsOnPage();            mDirtyPageContent.set(i, true);        }    }}


Pagedviewgridlayout.java

?
123456 @OverridepublicvoidremoveAllViewsOnPage() {    removeAllViews();    mOnLayoutListener = null;    setLayerType(LAYER_TYPE_NONE, null);}

2.2 Example: Clearing the cache

Code Source: Contact

?
12345678910111213 @Overridepublic void onTrimMemory(int level) {    if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {        // Clear the caches.  Note all pending requests will be removed too.        clear();    }}public void clear() {    mPendingRequests.clear();    mBitmapHolderCache.evictAll();    mBitmapCache.evictAll();}

3. The relationship between Ontrimmemory and OnStop?

The Trim_memory_ui_hidden callback in the Ontrimmemory () method is only triggered when all UI components in our program are not visible, which is quite different from the OnStop () method, because OnStop () The method is only called when an activity is completely invisible, such as when the user opens another activity in our program.

Therefore, we can release some activity-related resources in the OnStop () method, such as canceling the network connection or unregistering the broadcast receiver, but the UI-related resources should wait until ontrimmemory (Trim_memory_ui_hidden) This callback is then released, which ensures that if the user only returns from one activity of our program to another activity, the interface-related resources do not need to be reloaded, thereby increasing the response speed.

It is important to note that the Trim_memory_ui_hidden level of the ontrimmemory is called before the OnStop method.

4. The relationship between Ontrimmemory and onlowmemory?

Use the onlowmemory callback before introducing Ontrimmemory, and you need to know that onlowmemory is probably the same trim_memory_complete level in ontrimmemory if you want to be compatible api< 14 of the machine, then you can use onlowmemory to achieve, otherwise you can ignore Onlowmemory, directly use ontrimmemory can.

5. Why do I call ontrimmemory?

Although the system kills the process in low memory, the sequence is lower to highest in the LRU cache, but it also considers killing applications that use high memory to get more memory faster.

So if your application occupies less memory, you can increase the chance of not being killed, so that quickly recover (if not killed, the start is hot start, or cold start, its speed is less than a few times the difference).

So releasing your UI resources in several different ontrimmemory callbacks can effectively improve the user experience.

6. What are the typical usage scenarios? 6.1 Application of Resident memory

Some resident memory applications, such as launcher, Security Center, telephone, etc., when the user used to exit, need to call Ontrimmemory to release the user when the use of unnecessary memory resources: such as dynamically generated view, picture cache, fragment and so on.

Back to top 6.2 apps with background service running

These applications are not resident memory, meaning they can be killed by the task manager, but in some scenarios the user will not kill them. Such applications include: music, downloads, etc. After the user exits the UI, the music continues to play, and the download program is still running. At this point the music should release some UI resources and cache.

Android Code memory optimization recommended-ontrimmemory optimization

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.