Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

【原創】Android 記憶體管理:OnTrimMemory 回呼完整解析

編輯:關於 Android 開發

Application 裡有兩個與記憶體管理相關的方法:onLowMemory() 與 onTrimMemory(int level)。先看它們的源碼:

 @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); } } } } 

從源碼可以看到,Application 收到這兩個回呼時,會把它轉發給所有註冊的元件。而 Activity 與 Service 本身就實作了這些監聽介面,因此我們有兩個地方可以攔:在 Application 中覆寫,或在各個元件中覆寫。前者適合放全域的資源清理,後者適合處理自己特有的資源。

注意 onTrimMemory 裡多了一個 instanceof ComponentCallbacks2 的判斷——這是因為只有實作了 ComponentCallbacks2 的元件才接收得到這個回呼,舊版的 ComponentCallbacks 不會收到。

為什麼要實作 onTrimMemory

為了更好地管理記憶體,onTrimMemory 在 API 14 被引入,可以在所有元件中取得(Activity、Service、ContentProvider、Application)。

你應該根據當前設備的記憶體狀況覆寫 onTrimMemory(int),逐步釋放不需要的記憶體。透過這個方法釋放資源,可以幫助 App 更好地配合系統整體調度;同時因為讓你的 App 能在系統中存活更久,使用者體驗也會提升。反之,如果在系統記憶體極度緊張時你仍然不釋放記憶體,系統會優先把你的進程殺掉——使用者下次回到 App 時必須重新啟動,這對體驗的傷害遠比「少快取幾張圖」嚴重。

level 值的關鍵特性:不是線性關係

onTrimMemory(int) 的 level 值並不成線性關係,它只是提供記憶體不同狀態的線索。這句話很重要,直接影響你的判斷方式該怎麼寫。

一、回呼時機

 /** * 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);

當作業系統認為這是一個讓進程釋放無用記憶體的好時機時,就會呼叫這個方法。例如當已經沒有足夠記憶體維持目前所有後台進程,而你的進程正好在後台。

官方文件裡那句 "You should never compare to exact values of the level" 是重點:永遠不要用精確值比對,因為未來可能會新增中間層級的值。正確寫法是判斷「大於或等於你感興趣的 level」:

// 建議
if (level >= TRIM_MEMORY_BACKGROUND) { /* 清掉快取 */ }

// 不建議
if (level == TRIM_MEMORY_BACKGROUND) { /* 可能永遠不會命中 */ }

想在任何時刻取得目前進程的 trim level,可以呼叫 ActivityManager.getMyMemoryState(RunningAppProcessInfo)。

二、各 level 值的具體含義

 /** * 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; 

當你的 App 在後台時

TRIM_MEMORY_COMPLETE(80):當前進程在 LRU 列表的尾端,如果再找不到足夠記憶體,它很快會被殺死。這時應該釋放任何不影響 App 正常運行的資源。

TRIM_MEMORY_MODERATE(60):進程位於 LRU 列表中段,若系統需要更多記憶體,你的進程可能會被殺。

TRIM_MEMORY_BACKGROUND(40):進程在 LRU 列表的前段,雖然不會被優先殺掉,但系統已經開始準備清理列表中的其他進程。因此你應該盡量釋放那些「可以快速重建」的資源,確保使用者返回 App 時能迅速恢復。

當你的 App 可見性改變時

TRIM_MEMORY_UI_HIDDEN(20):進程的介面已經不可見,這是釋放 UI 相關資源的最佳時機。大塊的 Bitmap 快取、已 inflate 但用不到的 view,都可以在這裡清掉。

當你的 App 正在前台運行時

TRIM_MEMORY_RUNNING_MODERATE(5):系統進入輕度低記憶體狀態,你的進程正在運行且不會被殺,但可以釋放一些非必要資源。

TRIM_MEMORY_RUNNING_LOW(10):系統記憶體偏低,應該釋放不必要的資源以維持效能,否則會影響使用者體驗。

TRIM_MEMORY_RUNNING_CRITICAL(15):雖然你的進程不會被殺,但系統已準備清理其他後台進程。這時應盡可能釋放非關鍵資源。下一階段就會呼叫 onLowMemory(),代表連一個後台進程都留不住了——那種狀況已經會明顯影響到使用者。

再來說 onLowMemory

在 onTrimMemory 問世之前,大家用的都是 onLowMemory()。如果你的 App 跑在 API 14 以上的機器上,應該優先實作 onTrimMemory(int)。onLowMemory() 的呼叫時機大致等同於 TRIM_MEMORY_COMPLETE,也就是「已經無路可退」的最後警報。

實作上的建議

把 level 當成「該清多深」的刻度,而不是「要不要清」的開關。一個實用的分層策略是:

  • 收到 UI_HIDDEN:清掉非必要的圖片快取與動畫資源。
  • 收到 BACKGROUND 以上:清掉可重建的暫存資料、關閉不必要的連線。
  • 收到 COMPLETE 或 onLowMemory:把所有可丟的東西都丟掉,只保留能讓使用者回來時不覺得「App 掛了」的最小狀態。

切記不要在這些回呼裡做耗時運算或同步 IO。系統呼叫它是因為記憶體已經很緊,你在這裡多跑幾十毫秒,被殺的機率就更高。

另外補充一個實務判斷:Android 4.0 以上其實有另一個 API ComponentCallbacks2 搭配 onTrimMemory 使用,而 LeakCanary 這類記憶體監控工具能幫你確認洩漏點——onTrimMemory 只能「減少浪費」,它治不了洩漏。如果你的 App 在後台一陣子後記憶體持續攀升,該查的是有沒有靜態變數或 handler 持有 Activity 參考,而不是拼命在 onTrimMemory 裡清快取。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved