你真的了解Context吗

引言

很多人应该知道Activity,Service中的Context和ApplicationContext的区别,而且也知道Context,ContextImpl,ContextWrapper,Activity,Service,Application构成的体系,在异步任务需要Context时,也知道为了防止内存泄露需要传递ApplicationContext而不是Activity的Context,但是这样的场景并不万能,因为并不是所有需要Activity的Context的地方都可以用ApplicationContext来代替。

注:简书对于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()的区别

```

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

}

```

可以看到这里对Intent的flag进行了检查,如果没有FLAG_ACTIVITY_NEW_TASK属性,就会抛出异常。

那为什么Activity中就不需要做这样的检查了?

根本原因在于Application中的Context并没有所谓的任务栈,所以待启动的Activity就找不到task了,这样的话要启动Activity就必须将它放到一个新的task中,即使用singleTask的方式启动。

3.Dialog的创建

如下示例:

```

AlertDialog imageDialog = new AlertDialog.Builder(context).setTitle("状态操作").setItems(items, listener).create();

imageDialog.show();

```

如果其中的context是Application Context,那么会抛出以下异常:

```

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

```

这个异常是在ViewRoogImpl的setView()中抛出的。

而抛出这个异常的原因是与WMS进行Binder IPC(res=mWindowSession.addToDisplay())的结果,而这个结果是执行WMS中addWindow()的结果,该方法如下:

```

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导致的,这个AppWindowToken对应client端中Window的IBinder mAppToken这个成员。

由于AlertDialog中的super()会调用Dialog的构造方法,所以我们先看一下Dialog的构造方法:

```

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窗口的一个区别,Activity会将这个appToken设置为ActivityThread传过来的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类型,mWindow.getAttributes()获取到的Type为TYPE_APPLICATION.

Dialog也是通过WindowManager把自己的Window添加到WMS上,但是这里在addView()之前,mWindow的token为null(前面已经分析了,w.setWindowManager的第二个参数为null).而WMS要求TYPE_APPLICATION的窗口的token不能为null.

而如果用Application或者Service的Context区获取这个WindowManager服务的话,会得到一个WindowManagerImpl对象,这个实例中token也是空的。

那为什么Activity就可以呢?

原来是Activity重写了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);

}

```

显然,对于WINDOW_SERVICE,返回的是mWindowManager对象,而这个对象的创建是在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的区别。

所以不能通过Application和Service的Context来创建Dialog,只能通过Activity的Context来创建Dialog.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,980评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,422评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,130评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,553评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,408评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,326评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,720评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,373评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,678评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,722评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,486评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,335评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,738评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,283评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,692评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,893评论 2 335

推荐阅读更多精彩内容