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

Android Context 選擇指南:getBaseContext() vs this vs getApplicationContext() 區別與適用場景

     編輯:程式設計綜合問答

在 OnItemSelectedListener 等匿名內部類中,this 指向監聽器實例而非 Activity,導致 Toast.makeText(this, ...) 編譯錯誤。需根據場景選擇正確 Context。

三種 Context 對比

Context 類型獲取方式生命周期適用場景
Activity Contextthis / ActivityName.this隨 Activity 銷毀UI 相關:Dialog、Toast、啟動 Activity、佈局 inflate
Application ContextgetApplicationContext()全進程存活非 UI 長期持有:Singleton、Service、資源訪問、文件路徑
Base ContextgetBaseContext()同 Activity極少直接使用,內部包裝層

匿名類中正確用法

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView parent, View view, int pos, long id) {
        // ❌ this 指向 OnItemSelectedListener 實例
        // ✅ 使用外部類 this
        Toast.makeText(MainActivity.this, "SELECTED", Toast.LENGTH_SHORT).show();
        // ✅ 或 Application Context(Toast 兩者均可)
        Toast.makeText(getApplicationContext(), "SELECTED", Toast.LENGTH_SHORT).show();
    }
    ...
});

選擇原則

  • 需附著 UI 窗口(Dialog、PopupWindow):必須用 Activity Context。
  • 長期持有、非 UI 操作(資源、數據庫、文件、網絡):用 Application Context 防洩漏。
  • Toast 兩者均可,但習慣用 getApplicationContext() 統一。

理解 Context 生命周期與作用域,告別空指針與內存洩漏。

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