編輯:關於 Android 程式設計
Context 在 Android 中的地位不言而喻。當我們要存取當前應用的資源、啟動一個新的 Activity 時,都必須提供 Context。那麼 Context 究竟是什麼?這個問題看似好答,卻又不易說清。從字面看,Context 意為「上下文」,也可理解為環境或場景,但這樣的解釋仍顯抽象。
從類的繼承來看,Context 是一個抽象基類,其實現子類主要有三種:Application、Activity 與 Service。那麼這三者有何差異?為何透過任意 Context 存取資源,得到的都是同一套資源?getApplication 與 getApplicationContext 又有何不同?一個應用中究竟存在多少個 Context?本文將逐一探討這些問題,所用源碼版本為 Android 4.4。
Context 是一個抽象基類,我們透過它能夠存取當前 App 的資源(getResources、getAssets)、啟動其他元件(Activity、Service、Broadcast),以及取得各類系統服務(getSystemService)。可以這樣理解:Context 為應用提供了一個運行環境,只有在這個環境中,應用才能存取資源、與其他元件和服務互動。它定義了一套基本的功能介面,可視為一種規範;而 Activity 與 Service 則是實作這套規範的子類。不過更精確地說,這套規範其實是由 ContextImpl 類統一的實作,Activity 與 Service 只是繼承並有選擇性地覆寫了部分方法。
三者的共同點在於:它們都(間接)繼承自 Context。不同之處可從繼承關係說起。
Activity 的繼承關係

Service 與 Application 的繼承關係
對比不難發現,Service 與 Application 的繼承結構較為相似,而 Activity 則多了一層 ContextThemeWrapper。這是因為 Activity 具有「主題」的概念,而 Service 是沒有介面的後台服務,Application 更偏向抽象的整體存在。
Context 的真正實作都在 ContextImpl 中,也就是說,Context 的大部分方法呼叫最終都會轉交給 ContextImpl 處理。而三者的建立都在 ActivityThread 中完成。
Activity 中 ContextImpl 的建立
對應 ActivityThread 的 performLaunchActivity 方法:
if (activity != null) {
Context appContext = createBaseContextForActivity(r, activity);
// createBaseContextForActivity 內部:
// ContextImpl appContext = new ContextImpl();
// appContext.init(r.packageInfo, r.token, this);
// appContext.setOuterContext(activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
...
activity.attach(appContext, this, getInstrumentation(), r.token, ...);
}
可見,Activity 建立時會 new 一個 ContextImpl,並在 attach 方法中與之關聯。值得注意的是,建立 Activity 所使用的資料結構是 ActivityClientRecord。
Application 中 ContextImpl 的建立
對應 ActivityThread 的 handleBindApplication 方法,其內部會呼叫 makeApplication:
public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
if (mApplication != null) { return mApplication; }
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
try {
java.lang.ClassLoader cl = getClassLoader();
ContextImpl appContext = new ContextImpl();
appContext.init(this, null, mActivityThread);
app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) { ... }
...
}
可見其做法與 Activity 中的 ContextImpl 建立方式相同。Service 的情況也與前兩者一致。
那麼三者的 Context 到底有何差異?一些細節值得注意:彈出 Dialog 需要 Activity 類型的 Context,在桌面應用程式中使用 Application 的 Context 是無法彈出對話框的;此外,從桌面啟動新 Activity 時,必須為 Intent 設定 FLAG_ACTIVITY_NEW_TASK 標誌,否則無法啟動。這些都說明了 Application 與 Activity 的 Context 確有區別。
很明確,不同的 Context 取得的都是同一份資源。取得資源的方式為 context.getResources,真正的實作位於 ContextImpl 的 getResources 方法。ContextImpl 中有一個成員 private Resources mResources,即該方法回傳的結果,其賦值為:
mResources = mResourcesManager.getTopLevelResources(mPackageInfo.getResDir(),
Display.DEFAULT_DISPLAY, null, compatInfo, activityToken);
ResourcesManager 的 getTopLevelResources 方法思路如下:所有資源物件都儲存在一個 ArrayMap 中,先依當前請求參數查詢,命中則直接回傳,否則建立新的資源物件再放入。
之所以會有多個資源物件,是因為 res 目錄下可能存在適配不同設備、解析度與系統版本的多個子目錄。依照 Android 的設計,不同設備存取同一應用時取得的資源可以不同,例如 drawable-hdpi 與 drawable-xhdpi 就是典型案例。
public Resources getTopLevelResources(String resDir, int displayId,
Configuration overrideConfiguration, CompatibilityInfo compatInfo, IBinder token) {
final float scale = compatInfo.applicationScale;
ResourcesKey key = new ResourcesKey(resDir, displayId, overrideConfiguration, scale, token);
Resources r;
synchronized (this) {
WeakReference<Resources> wr = mActiveResources.get(key);
r = wr != null ? wr.get() : null;
if (r != null && r.getAssets().isUpToDate()) {
return r; // 命中快取
}
}
AssetManager assets = new AssetManager();
if (assets.addAssetPath(resDir) == 0) { return null; }
DisplayMetrics dm = getDisplayMetricsLocked(displayId);
Configuration config = ...;
r = new Resources(assets, dm, config, compatInfo, token);
synchronized (this) {
WeakReference<Resources> wr = mActiveResources.get(key);
Resources existing = wr != null ? wr.get() : null;
if (existing != null && existing.getAssets().isUpToDate()) {
r.getAssets().close();
return existing;
}
mActiveResources.put(key, new WeakReference<Resources>(r));
return r;
}
}
由於 ResourcesManager 採用單例模式,再加上上述請求機制,就保證了不同的 ContextImpl 存取的其實是同一套資源。也就是說,雖然 Application、Activity、Service 各自擁有 ContextImpl,每個 ContextImpl 也都有自己的 mResources 成員,但因為它們的 mResources 都來自唯一的 ResourcesManager 實例,所以這些 mResources 實際指向同一個物件(在設備參數與顯示參數不變的前提下)。而在橫豎屏切換且專案提供了不同資源的情況下,橫屏與豎屏狀態下的 ContextImpl 存取的資源則是不同物件。
單例模式的 ResourcesManager:
public static ResourcesManager getInstance() {
synchronized (ResourcesManager.class) {
if (sResourcesManager == null) {
sResourcesManager = new ResourcesManager();
}
return sResourcesManager;
}
}
getApplication 回傳的是 Application 物件,且不同 Activity、Service 取得的都是同一個全域物件;ActivityThread 內部有一個清單專門維護所有 Application:
final ArrayList mAllApplications = new ArrayList();
getApplicationContext 回傳的也是 Application 物件,只是回傳型別為 Context,其實作如下:
@Override
public Context getApplicationContext() {
return (mPackageInfo != null) ? mPackageInfo.getApplication() : mMainThread.getApplication();
}
其中 mPackageInfo 包含當前應用的套件資訊(套件名、安裝目錄等)。一般來說,第三方應用的 mPackageInfo 不會為空,此時 getApplicationContext 與 getApplication 回傳的是同一個物件,兩者差異僅在回傳型別。因此對第三方應用而言,一個應用只存在一個 Application 物件。
至此已很清晰:一個應用中 Context 的數量 = Activity 數量 + Service 數量 + 1,這裡的 1 即 Application。
Android ListView 單選效果實作:以 ImageView 模擬單選按鈕
做 Android 開發到現在有段時間了,技術也慢慢有了些積累,剛好把自己實現過的一個小功能記錄下來,若也能幫到路上的其他開發者,那也算是件好事。廢話不多說,先上圖。
「開心學成語」App 實作全記錄:從建庫到 TabHost 介面
成語類 App 的特點是資料量大、結構固定,很適合用預置 SQLite 資料庫的方式來做。本文記錄一個成語學習應用的完整實作過程,包含資料庫打包、DAO 封裝、單元測試以
Android App 耗電優化實戰指南
可能造成耗電的一些原因 網絡請求耗電,而且用手機數據網絡發 HTTP 請求比用無線網更耗電,因為數據網絡會調用一些底層硬件模塊,就像 GPS 一樣,一旦開啟就會啟動硬件模
Android L 關機流程解析
Android 的關機流程從 Java 層一路延伸到 kernel。理解這個流程,有助於排查關機動畫、服務結束、電源管理與低層驅動相關問題。 Java 層:Shutdo