ComponentCallbacks2使用与测试

/ 0评 / 0

根据官方文档:https://developer.android.com/topic/performance/memory?hl=zh-cn#kotlin

import android.content.ComponentCallbacks2
// Other import statements.

class MainActivity : AppCompatActivity(), ComponentCallbacks2 {

    // Other activity code.

    /**
     * Release memory when the UI becomes hidden or when system resources become low.
     * @param level the memory-related event that is raised.
     */
    override fun onTrimMemory(level: Int) {

        // Determine which lifecycle or system event is raised.
        when (level) {

            ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN -> {
                /*
                   Release any UI objects that currently hold memory.

                   The user interface moves to the background.
                */
            }

            ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE,
            ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW,
            ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL -> {
                /*
                   Release any memory your app doesn't need to run.

                   The device is running low on memory while the app is running.
                   The event raised indicates the severity of the memory-related event.
                   If the event is TRIM_MEMORY_RUNNING_CRITICAL, then the system
                   begins stopping background processes.
                */
            }

            ComponentCallbacks2.TRIM_MEMORY_BACKGROUND,
            ComponentCallbacks2.TRIM_MEMORY_MODERATE,
            ComponentCallbacks2.TRIM_MEMORY_COMPLETE -> {
                /*
                   Release as much memory as the process can.

                   The app is on the LRU list and the system is running low on memory.
                   The event raised indicates where the app sits within the LRU list.
                   If the event is TRIM_MEMORY_COMPLETE, the process is one of the
                   first to be terminated.
                */
            }

            else -> {
                /*
                  Release any non-critical data structures.

                  The app receives an unrecognized memory level value
                  from the system. Treat this as a generic low-memory message.
                */
            }
        }
    }
}

测试方法

adb shell am send-trim-memory com.tinytongtong.androidstudy COMPLETE

adb shell am send-trim-memory com.tinytongtong.androidstudy MODERATE

adb shell am send-trim-memory com.tinytongtong.androidstudy BACKGROUND

adb shell am send-trim-memory com.tinytongtong.androidstudy HIDDEN

adb shell am send-trim-memory com.tinytongtong.androidstudy RUNNING_CRITICAL

adb shell am send-trim-memory com.tinytongtong.androidstudy RUNNING_LOW

adb shell am send-trim-memory com.tinytongtong.androidstudy RUNNING_MODERATE

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注