編輯:關於 Android 程式設計
之前在上一家公司做 TV 與盒子相關開發時,好幾個同事都問過我同一個問題:Android 的 Context 到底是什麼?我們平常開發 App 時其實一直在用它——存取當前應用的資源、啟動一個 Activity 等等都離不開 Context——但很少有人真正關注它是什麼,也很少人搞得清 getApplication() 與 getApplicationContext() 的差別,甚至一個 App 到底有多少個 Context。
更麻煩的是,Context 用得不當還會造成記憶體洩漏。所以實在有必要拿出來單獨分析(本文基於 Android 5.1.1,API 22 源碼)。
先看源碼裡 Context 類別的定義:
/**
* 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.
*/
public abstract class Context { ...... }
從註解可以看出,Context 提供了關於應用環境全域資訊的介面。它是一個抽象類別,具體實作由 Android 系統提供,允許我們取得應用相關的資源與類別,並執行應用層級的操作(例如啟動 Activity、發送與接收廣播 Intent 等)。換句話說,它描述了應用程式的環境資訊(也就是「上下文」),是統整應用程式環境變數等資源的入口。
既然 Context 是抽象類別,那它一定有實作類別。透過 IDE 查看會發現它的子類多達 700 多個,但歸根究柢主要就下面這幾條繼承線:


從這裡可以發現:Service 與 Application 的繼承結構類似,而 Activity 繼承的是 ContextThemeWrapper。原因在於 Activity 有主題(它要負責顯示 UI,自然需要主題),而 Service 是沒有界面的服務。
抽象類別 Context 定義了一組通用 API;它的實作類別是 ContextImpl,把 Context 的所有功能真正落地。
/** Common implementation of Context API, which provides the base context object for Activity and other application components. */
class ContextImpl extends Context { private Context mOuterContext; ...... }
ContextWrapper 則是一個包裝類別,它內部持有真正的 Context 參照(也就是 ContextImpl 物件),本質上是 ContextImpl 的裝飾者模式。
public class ContextWrapper extends Context {
Context mBase;
public ContextWrapper(Context base) { mBase = base; }
protected void attachBaseContext(Context base) {
if (mBase != null) { throw new IllegalStateException("Base context already set"); }
mBase = base;
}
...... }
再往下的 ContextThemeWrapper 繼承自 ContextWrapper,內部多了主題(Theme)相關的介面,也就是 android:theme 屬性所指定的東西。最後:
public class Activity extends ContextThemeWrapper implements ... { ...... }
public abstract class Service extends ContextWrapper implements ComponentCallbacks2 { ...... }
public class Application extends ContextWrapper implements ComponentCallbacks2 { ...... }
完全符合上面推導出的結構圖。
Android 應用只有四大組件,其中 Activity 與 Service 都繼承自 Context,此外每個應用還有一個全域的 Application 物件。所以 Context 總數就是:
APP Context 總數 = Application 數(1) + Activity 數(自訂) + Service 數(自訂);
Context 的實作是 ContextImpl,而 Activity、Application、Service 的創建都在 ActivityThread 中完成。
透過 startActivity 啟動新 Activity 時,系統會回呼 ActivityThread 的 handleLaunchActivity(),它內部再呼叫 performLaunchActivity() 創建 Activity 實例並回呼 onCreate() 等方法。ContextImpl 的實例化就在這裡:
private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) {
// 實質就是 new 一個 ContextImpl 物件
ContextImpl appContext = ContextImpl.createActivityContext(this, r.packageInfo, r.token);
// 讓 ContextImpl 內部持有這個 Activity
appContext.setOuterContext(activity);
return appContext;
}
接著在 Activity 的 attach 方法中,透過 ContextWrapper 的 attachBaseContext 把剛才的 ContextImpl 傳進 mBase:
final void attach(Context context, ...) {
// 把 ContextImpl 存入 ContextWrapper 的 mBase
attachBaseContext(context);
...... }
由此可見:Activity 透過 ContextWrapper 的成員 mBase 參照了一個 ContextImpl;而 ContextImpl 又透過自己的 mOuterContext 參照回 Activity。兩者互相持有。所以一個 Activity 就有一個 Context,且生命週期與 Activity 相同——記住這句話,就能避免不少低級的記憶體洩漏。
透過 startService 或 bindService 創建 Service 時,會回呼 ActivityThread 的 handleCreateService(),流程與 Activity 幾乎一致:
private void handleCreateService(CreateServiceData data) {
...... // 創建 Service 實例
ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
context.setOuterContext(service); // ContextImpl 持有 Service
service.attach(context, this, data.info.name, data.token, app, ActivityManagerNative.getDefault());
service.onCreate();
...... }
結論同樣成立:一個 Service 就有一個 Context,生命週期與 Service 相同。
每次 App 重啟都會先創建 Application 物件(每個 App 只有一個全域 Application,生命週期等同整個 App)。它在 ActivityThread 的 handleBindApplication() 中,透過 LoadedApk 的 makeApplication 完成:
public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
if (mApplication != null) { return mApplication; }
Application app = null;
...
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
appContext.setOuterContext(app); // ContextImpl 持有 Application
...
return app;
}
最終在 Application 的 attach 方法中,同樣把 ContextImpl 存入 mBase。結論:一個 Application 有一個 Context,生命週期與 Application 相同。
你可能會疑惑:這麼多不同實例的 Context,透過 context.getResources() 拿到的資源難道不是同一份嗎?看源碼:
class ContextImpl extends Context {
private final ResourcesManager mResourcesManager;
private final Resources mResources;
@Override public Resources getResources() { return mResources; }
}
getResources() 回傳的就是 ContextImpl 的成員 mResources,而它的賦值過程如下:
mResourcesManager = ResourcesManager.getInstance(); // 單例 Resources resources = packageInfo.getResources(mainThread); // 同一個 App 只有一份 mResources = resources;
由此可見,在設備條件不變的情況下,透過不同 Context 實例拿到的 Resources 是同一套資源。同理,Context 的 packageInfo 對一個應用來說也只有一份。
先說 getApplication():Context 與 Application 本身都沒有這個方法,它其實是由 Activity 與 Service 各自提供的,回傳型別是 Application:
public final Application getApplication() { return mApplication; }
這個 mApplication 是在各自 attach 時傳入的,也就是 ActivityThread 實例化時 makeApplication 的回傳值。所以不同 Activity/Service 回傳的 Application 都是同一個全域物件。
再看 getApplicationContext(),它是 Context 的方法,回傳型別是 Context:
@Override public Context getApplicationContext() {
return (mPackageInfo != null) ? mPackageInfo.getApplication() : mMainThread.getApplication();
}
對第三方應用來說,兩者回傳的其實是同一個物件,只是回傳型別不同、依附的對象不同而已。
Application 的 Context 生命週期與整個應用相同;Activity 或 Service 的 Context 則與各自類別的生命週期相同。所以 Context 用錯就會引起記憶體洩漏。
舉個典型例子:一個用單例模式實作的自訂資料庫管理工具類需要傳入 Context,而它又要在 Activity 中使用——如果你傳的是 Activity 的 Context,就可能造成洩漏,這時應該傳 Application 的 Context。
到這裡,Android 應用中 Context 的種種疑惑就完全解開了:它是什麼、繼承關係如何、一個 App 有多少個、如何實例化、資源是否共用,以及開發時該如何避開記憶體洩漏。理解了這些,之後在 App 裡使用 Context 就不再迷茫。
一個 TextView 裡塞兩種顏色:SpannableString 與 Html 兩種解法
「上次里程:23023Km」這種介面很常見——標籤用灰色,數值用綠色,全在一行裡。直覺的做法是用好幾層 LinearLayout 把文字拆開排版,這可行,但布局層數一多,
Android ViewPager 學習筆記:Fragment 頁面與資料載入
ViewPager 常用於實作可左右滑動的頁面切換效果。搭配 Fragment 與 PagerAdapter,可以輕鬆建立多頁式介面。 基本架構 在 MainActivi
Android 4.4 NotificationManagerService 原理剖析:NotificationListenerService 的啟動、回調與失效陷阱
前言 上一篇已經把 NotificationListenerService(以下簡稱 NLS)的使用方式與常見問題整理過,本篇要往下挖一層:它到底是怎麼跑起來的,那些惱人
Android Studio 常用快捷鍵整理
終於把卡頓到令人心煩的 Eclipse 丟掉了。用了一個月 Android Studio 之後,我對它的設計實在佩服——即便當時版本還停留在 0.4.5,功能已經相當完整