Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android Context 與記憶體洩漏:一次搞懂 Application 與 Activity 的差別

Context 幾乎無所不能,但最核心的功能其實只有一個:載入與存取資源。正因為它被傳來傳去,稍不留意就會成為記憶體洩漏的源頭。

兩種 Context

Android 裡有兩種 Context:Application Context 與 Activity Context。日常在各類與方法之間傳遞的,通常是 Activity Context。例如:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mGameView = new GameView(this);
    setContentView(mGameView);
}

把 Activity Context 交給 View,意味著 View 持有一個指向 Activity 的引用,進而牽連 Activity 所佔用的資源:子 View、Resource、SensorManager 等等。一旦這個 Context 發生洩漏,GC 就無法回收 Activity 的記憶體(無論它是正在活動中,還是已 finish 但尚未回收),牽連的範圍會相當可觀。

洩漏整個 Activity 有多容易

螢幕旋轉時,系統會銷毀當前 Activity、保存狀態資訊,再建立一個新的。假如你的應用要載入一張大圖,又不希望每次旋轉都重新解碼,最直覺的想法是宣告一個靜態的 Drawable,讓它在 Activity 反覆建立與銷毀之間長存記憶體,取用速度也快。

public class myactivity extends Activity {
    private static Drawable sBackground;

    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); // drawable attached to a view

        setContentView(label);
    }
}

程式看起來人畜無害,問題卻很大:旋轉螢幕就會洩漏。

原因在引用鏈上。Drawable 一旦與 View 關聯,就保存了 View 的 reference,也就是 sBackground 持有 label,而 label 又持有 Activity。既然靜態的 Drawable 不會被銷毀,它所引用與間接引用的物件也全都無法回收,系統自然沒辦法銷毀當前 Activity。這種洩漏,GC 完全無能為力。

怎麼避免

核心原則只有一句:不要讓 Activity 中的任何物件,生命週期長過 Activity 本身。

另一個好用的工具是 Application Context。它伴隨 Application 的一生,與 Activity 的生命週期無關,可以透過 Context.getApplicationContext() 或 Activity.getApplication() 取得。

要使用自訂的 Application,需在 AndroidManifest.xml 中以 android:name 註冊:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".GApplication">

    <activity
        android:name=".WordSearch"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        android:screenOrientation="portrait"
        android:configChanges="keyboardHidden|orientation|keyboard|screenLayout">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

三條可以立刻用上的規則

  1. 不要讓生命週期長的物件引用 Activity Context;換言之,持有 Activity 的物件,其生命週期應與 Activity 一致。
  2. 確實需要長壽命物件時,改用 Application Context(例如 public class GApplication extends Application)。
  3. 優先使用靜態類(全局),避免非靜態內部類;內部類對外部物件的隱含引用,往往就是生命週期被拉長的元兇。

記住這三點,多數 Context 相關的洩漏都能在設計階段就被擋掉。

Copyright © Linux教程網 All Rights Reserved