首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 工具類接收 Activity 參數:傳遞 Context 的正確姿勢與內存洩漏避坑

     編輯:程式設計綜合問答

典型場景

工具類需訪問資源、啟動 Activity、彈 Toast、獲取系統服務等,需 `Context`。

推薦做法:方法參數傳遞

public class Utils {
    public static void showToast(Context context, String msg) {
        if (context != null) Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    public static void startActivity(Context context, Class clazz) {
        if (context != null) {
            Intent intent = new Intent(context, clazz);
            context.startActivity(intent);
        }
    }
}

// 調用
Utils.showToast(MainActivity.this, "Hello");
Utils.startActivity(this, SecondActivity.class);

不推薦:靜態持有 Context

// 危險!導致 Activity 無法被 GC 回收 → 內存洩漏
public class BadUtils {
    private static Context sContext;
    public static void init(Context context) { sContext = context; }
}

若必須長期持有:Application Context

public class App extends Application {
    private static Context sAppContext;
    public static Context getAppContext() { return sAppContext; }
    @Override public void onCreate() { super.onCreate(); sAppContext = this; }
}
// 工具類用 App.getAppContext(),生命周期隨進程,不洩漏

內存洩漏檢測

  • Android Studio Profiler → Heap Dump → 分析 `Activity` 實例數 > 1。
  • LeakCanary 自動檢測並通知。

總結

能傳就傳,不能存。優先方法參數傳 `Context`,長期持有只存 `Application Context`,嚴禁靜態字段持有 `Activity Context`。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved