至少在 T-Mobile G1 的年代,Android 應用堆上可用記憶體被限制在 16MB 以內。對手機而言這不算小,但遠遠不夠一些應用塞。即使你打算省著用,也應該盡量少佔,好讓其他應用能繼續留在記憶體裡而不是被殺掉——系統能同時保住的應用越多,使用者切換應用就越順手。
我在做 Android 開發時也掉進過記憶體洩漏的坑,而大多數時候原因都相同:長期持有了一個 Context 的引用。
Context 幾乎無所不能,最常用的是載入與取用資源,這也是所有 widget 的 constructor 都要收一個 Context 的原因。一般應用裡有兩種 Context:Activity 與 Application。而我們在需要 Context 時,通常傳的是 Activity:
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this);
label.setText("Leaks are bad");
setContentView(label);
}
這意味著 View 持有對整個 Activity 的引用,也就是連帶引用了它擁有的一切——完整的視圖層級結構與所有資源。因此洩漏一個 Context,等於洩漏了一大片記憶體。而「洩漏」的意思就是:你留著它的引用,讓垃圾回收器永遠不敢碰它。
當螢幕方向改變時,系統預設會銷毀目前的 Activity 並建立一個新的,同時保留原有狀態,UI 則從資源重新載入。若你的應用有一張很大的 bitmap,不想每次旋轉都重讀,最直覺的做法是把它放進 static 欄位:
private static Drawable sBackground;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this);
label.setText("Leaks are bad");
if (sBackground == null) {
sBackground = getDrawable(R.drawable.large_bitmap);
}
label.setBackgroundDrawable(sBackground);
setContentView(label);
}
看起來很快,但錯得很嚴重:它洩漏了第一次建立的那個 Activity。原因在於 Drawable 綁到 View 上時,View 會被設為 Drawable 的 callback;於是這條引用鏈變成 Drawable → TextView → Activity(Context)→ 幾乎所有東西。
結論很樸素:static 欄位不該持有任何與 Context 相關的物件。若真要跨旋轉保留昂貴資源,就改用 Application 的 Context,或把資料(而非 View、Drawable)交給 ViewModel、Fragment 的 setRetainInstance 或 onSaveInstanceState 來保存。