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

Context 到底是什麼?一篇講清 Android 的「萬用上下文」

編輯:關於 Android 程式設計

在 Android 開發裡,Context 是個熟悉又陌生的角色。啟動 Activity 要它,彈 Dialog 要它,取資源、開 Service、讀 SharedPreferences 也都要它。但如果被問一句「Context 究竟是何物」,很多人會卡住。

官方 API 的描述是這樣的:

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

換成白話:Context 是應用運行環境資訊的對外接口,是一個由 Android 系統實作的抽象類;透過它能取得應用專屬的資源與類別,也能執行啟動 Activity、發送與接收廣播這類應用層級的操作。

一、誰是 Context 的實作?

抽象類一定會有實作。最常見的三個是 Activity、Service 與 Application,牠們的繼承鏈略有不同:

Activity 的繼承關係

Service 與 Application 的繼承關係

也就是說,我們每天在用的 Activity、Service、Application,本身就是 Context。實務上最容易混淆的一對,是 Activity 的 Context 與 Application 的 Context。

二、Context 提供了哪些能力

把 API 文件翻開,會發現很多我們以為是「Activity 的方法」,其實源頭都在 Context。

啟動頁面

abstract void startActivity(Intent intent)
abstract void startActivity(Intent intent, Bundle options)

Activity 裡的 startActivity() 其實是對 Context 同名方法的重寫。

取得資源與設定

abstract Resources getResources()
abstract SharedPreferences getSharedPreferences(String name, int mode)
final String getString(int resId)
final String getString(int resId, Object... formatArgs)

控制 Service

abstract ComponentName startService(Intent service)
abstract boolean stopService(Intent service)

除此之外,Context 上還掛著大量與資源存取、元件通訊相關的方法。可以這樣理解:Context 是整個應用的「手與腳」,負責把資源取回來,也負責代為執行 Activity 與 Service 的操作,是讓程式保持通暢的樞紐。

用 Toast 的原始碼看 Context 的流向

想知道 Context 實際上被拿去做什麼,跟著 Toast.makeText() 走一遍最清楚。它接收到的 Context 被用在這一行:

View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);

這裡透過 Context 取得 LayoutInflater 服務,再載入系統預先寫好的 Toast 布局;接著又透過同一個 Context 去讀取字串與圖示等资源。結論很清楚:Toast 的外觀與顯示,都是靠 Context 向系統調用資源完成的。

三、Activity 的 Context 和 Application 的 Context 差在哪

差別只有一個字:壽命。

Activity 的 Context 依附在該 Activity 的生命週期上,頁面一關,它就失效;Application 的 Context 則與整個應用同生共死。實務上的結論是:如果一個長壽命的物件(例如單例、靜態變數、長時間存在的管理員類別)需要 Context,傳 Application 的 Context 進去,否則很容易因為間接持有已銷毀的 Activity 而造成記憶體洩漏。反之,若只是當前畫面內的 Dialog、Toast,用 Activity 的 Context 才能拿到正確的主題與視窗樣式。

把 Context 想成「應用環境的把手」,而不是某個頁面專屬的東西,很多設計上的猶豫就會自動消失。

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