Android中的Context對象
相關的類
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.
就是說Context是用來處理應用級別的事務的殷绍,比如想調用resources里的圖片败潦、文字捉貌,又或是想用SharedPreferences來存取一些配置等,這些都是屬于應用級別的資源懒构,通過Context可以對它們進行調用。又比如想啟動另外一個Activity或者是一個Service瞬女,也需要通過Context來實現模她。
下面是Context的部分源碼(source code):
public abstract class Context {
...
/** 用于獲取應用的資源,如字符串扛禽,圖片等 */
public abstract Resources getResources();
/** 啟動Activity */
public abstract void startActivity(Intent intent);
/** 啟動Service */
public abstract ComponentName startService(Intent service);
/** 獲取SharedPreferences */
public abstract SharedPreferences getSharedPreferences(String name, int mode);
...
}
通過源碼可以看出锋边,Context是一個抽象類,里面定義了一堆方法编曼,但是都沒有具體的實現豆巨。按照官方文檔中所說具體實現會由android系統(tǒng)提供的,一個例子就是下面提到的ContextImpl掐场。
ContextImpl
Common implementation of Context API, which provides the base context object for Activity and other application components.
實現Context接口的類往扔,為Activity和其他組件提供了基礎的Context對象。
下面是ContextImpl的部分源碼(source code):
class ContextImpl extends Context {
...
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity) null, intent, -1, options);
}
...
}
通過源碼看出熊户,ContextImpl實現了Context接口里的方法萍膛。
ContextWrapper
Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.
ContextWrapper的所有方法的都委托給了委托給了一個Context類的實現(例如ContextImpl)。這是采用了裝飾模式嚷堡。
下面是ContextWrapper的部分源碼(source code):
public class ContextWrapper extends Context {
Context mBase;
/** 綁定一個mBase的Context對象蝗罗,調用方法時會直接委托給mBase來處理 */
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}
...
@Override
public Resources getResources() {
return mBase.getResources();
}
@Override
public void startActivity(Intent intent) {
mBase.startActivity(intent);
}
...
}
通過源碼看出,ContextWrapper持有了一個mBase的Context對象蝌戒,然后代理了mBase中的方法串塑。mBase就是一個ContextImpl的實例。
ContextThemeWrapper
A ContextWrapper that allows you to modify the theme from what is in the wrapped context.
ContextThemeWrapper包含了主題相關的一些功能北苟,Activity就是繼承自ContextThemeWrapper桩匪,而Service是繼承自ContextWrapper。
參考文檔
Android中Context詳解 ---- 你所不知道的Context
Context, What Context?
Android應用程序窗口(Activity)的運行上下文環(huán)境(Context)的創(chuàng)建過程分析