你真的了解Context嗎

引言

很多人應(yīng)該知道Activity,Service中的Context和ApplicationContext的區(qū)別,而且也知道Context,ContextImpl,ContextWrapper,Activity,Service,Application構(gòu)成的體系,在異步任務(wù)需要Context時(shí),也知道為了防止內(nèi)存泄露需要傳遞ApplicationContext而不是Activity的Context,但是這樣的場(chǎng)景并不萬(wàn)能,因?yàn)椴⒉皇撬行枰狝ctivity的Context的地方都可以用ApplicationContext來(lái)代替。

注:簡(jiǎn)書(shū)對(duì)于Markdown的支持還不是很好,希望有更好的代碼閱讀效果的童鞋,可以直接移步我的Blog:?http://blog.imallen.wang/blog/2017/02/20/ni-zhen-de-liao-jie-contextma/

1.Context繼承體系


context_hierarchy

2.Activity的startActivity()和Application的startActivity()的區(qū)別

```

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);

}

```

可以看到這里對(duì)Intent的flag進(jìn)行了檢查,如果沒(méi)有FLAG_ACTIVITY_NEW_TASK屬性,就會(huì)拋出異常。

那為什么Activity中就不需要做這樣的檢查了?

根本原因在于Application中的Context并沒(méi)有所謂的任務(wù)棧,所以待啟動(dòng)的Activity就找不到task了,這樣的話(huà)要啟動(dòng)Activity就必須將它放到一個(gè)新的task中,即使用singleTask的方式啟動(dòng)。

3.Dialog的創(chuàng)建

如下示例:

```

AlertDialog imageDialog = new AlertDialog.Builder(context).setTitle("狀態(tài)操作").setItems(items, listener).create();

imageDialog.show();

```

如果其中的context是Application Context,那么會(huì)拋出以下異常:

```

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

```

這個(gè)異常是在ViewRoogImpl的setView()中拋出的。

而拋出這個(gè)異常的原因是與WMS進(jìn)行Binder IPC(res=mWindowSession.addToDisplay())的結(jié)果,而這個(gè)結(jié)果是執(zhí)行WMS中addWindow()的結(jié)果,該方法如下:

```

public int addWindow(Session session,IWindow client,int seq,WindowManager.LayoutParams attrs,int viewVisibility,int displayId,Rect outContentInsets, InputChannel outInputChannel){

if(token==null){

...

} else if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {

AppWindowToken atoken = token.appWindowToken;

if (atoken == null) {

Slog.w(TAG, "Attempted to add window with non-application token "

+ token + ".? Aborting.");

return WindowManagerGlobal.ADD_NOT_APP_TOKEN;

}

...

}

}

```

顯然,這是由于AppWindowToken==null導(dǎo)致的,這個(gè)AppWindowToken對(duì)應(yīng)client端中Window的IBinder mAppToken這個(gè)成員。

由于AlertDialog中的super()會(huì)調(diào)用Dialog的構(gòu)造方法,所以我們先看一下Dialog的構(gòu)造方法:

```

Dialog(Context context, int theme, boolean createContextThemeWrapper) {

if (createContextThemeWrapper) {

if (theme == 0) {

TypedValue outValue = new TypedValue();

context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme,

outValue, true);

theme = outValue.resourceId;

}

mContext = new ContextThemeWrapper(context, theme);

} else {

mContext = context;

}

mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);

Window w = PolicyManager.makeNewWindow(mContext);

mWindow = w;

w.setCallback(this);

w.setOnWindowDismissedCallback(this);

w.setWindowManager(mWindowManager, null, null);

w.setGravity(Gravity.CENTER);

mListenersHandler = new ListenersHandler(this);

}

```

注意其中的w.setWindowManager(),顯然,傳遞的appToken為null.這也是Dialog和Activity窗口的一個(gè)區(qū)別,Activity會(huì)將這個(gè)appToken設(shè)置為ActivityThread傳過(guò)來(lái)的token.

在Dialog的show()方法中:

```

public void show() {

if (mShowing) {

if (mDecor != null) {

if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {

mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);

}

mDecor.setVisibility(View.VISIBLE);

}

return;

}

mCanceled = false;

if (!mCreated) {

dispatchOnCreate(null);

}

onStart();

mDecor = mWindow.getDecorView();

if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {

final ApplicationInfo info = mContext.getApplicationInfo();

mWindow.setDefaultIcon(info.icon);

mWindow.setDefaultLogo(info.logo);

mActionBar = new WindowDecorActionBar(this);

}

WindowManager.LayoutParams l = mWindow.getAttributes();

if ((l.softInputMode

& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {

WindowManager.LayoutParams nl = new WindowManager.LayoutParams();

nl.copyFrom(l);

nl.softInputMode |=

WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;

l = nl;

}

try {

mWindowManager.addView(mDecor, l);

mShowing = true;

sendShowMessage();

} finally {

}

}

```

其中mWindow是PhoneWindow類(lèi)型,mWindow.getAttributes()獲取到的Type為T(mén)YPE_APPLICATION.

Dialog也是通過(guò)WindowManager把自己的Window添加到WMS上,但是這里在addView()之前,mWindow的token為null(前面已經(jīng)分析了,w.setWindowManager的第二個(gè)參數(shù)為null).而WMS要求TYPE_APPLICATION的窗口的token不能為null.

而如果用Application或者Service的Context區(qū)獲取這個(gè)WindowManager服務(wù)的話(huà),會(huì)得到一個(gè)WindowManagerImpl對(duì)象,這個(gè)實(shí)例中token也是空的。

那為什么Activity就可以呢?

原來(lái)是Activity重寫(xiě)了getSystemService()方法:

```

@Override

public Object getSystemService(@ServiceName @NonNull String name) {

if (getBaseContext() == null) {

throw new IllegalStateException("System services not available to Activities before onCreate()");

}

if (WINDOW_SERVICE.equals(name)) {

return mWindowManager;

} else if (SEARCH_SERVICE.equals(name)) {

ensureSearchManager();

return mSearchManager;

}

return super.getSystemService(name);

}

```

顯然,對(duì)于WINDOW_SERVICE,返回的是mWindowManager對(duì)象,而這個(gè)對(duì)象的創(chuàng)建是在Activity的attach()方法中:

```

final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token, int ident,

Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent, String id,

NonConfigurationInstances lastNonConfigurationInstances, Configuration config,

IVoiceInteractor voiceInteractor) {

attachBaseContext(context);

mFragments.attachActivity(this, mContainer, null);

mWindow = PolicyManager.makeNewWindow(this);

mWindow.setCallback(this);

mWindow.setOnWindowDismissedCallback(this);

mWindow.getLayoutInflater().setPrivateFactory(this);

if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {

mWindow.setSoftInputMode(info.softInputMode);

}

if (info.uiOptions != 0) {

mWindow.setUiOptions(info.uiOptions);

}

mUiThread = Thread.currentThread();

mMainThread = aThread;

mInstrumentation = instr;

mToken = token;

mIdent = ident;

mApplication = application;

mIntent = intent;

mComponent = intent.getComponent();

mActivityInfo = info;

mTitle = title;

mParent = parent;

mEmbeddedID = id;

mLastNonConfigurationInstances = lastNonConfigurationInstances;

if (voiceInteractor != null) {

if (lastNonConfigurationInstances != null) {

mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;

} else {

mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this, Looper.myLooper());

}

}

mWindow.setWindowManager((WindowManager) context.getSystemService(Context.WINDOW_SERVICE), mToken,

mComponent.flattenToString(), (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);

if (mParent != null) {

mWindow.setContainer(mParent.getWindow());

}

mWindowManager = mWindow.getWindowManager();

mCurrentConfig = config;

}

```

注意其中的mWindow.setWindowManager(),在這里將Activity的mToken給了mWindow,所以這就是Activity中的mWindow和Dialog中的mWindow的區(qū)別。

所以不能通過(guò)Application和Service的Context來(lái)創(chuàng)建Dialog,只能通過(guò)Activity的Context來(lái)創(chuàng)建Dialog.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容