目录
- 为什么不能使用 Application Context 显示 Dialog?
- 谁创建了 Token?
- WMS 是如何拿到 Token 的?
- WMS 是如何校验 Token 的?
为什么不能使用 Application Context 显示 Dialog?
在上一篇文章 扒一扒 Context 中遗留了一个问题:
为什么不能使用 Application Context 显示 Dialog ?
写个简单的测试代码,如下:
Dialog dialog = new Dialog(getApplicationContext());
dialog.show();
运行时会得到这样一个错误:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window – token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:951)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:387)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:96)
at android.app.Dialog.show(Dialog.java:344)
at luyao.android.context.ContextActivity.showDialog(ContextActivity.java:31)
看到报错信息中的 token ,不知道你还记不记得上篇文章中介绍过的 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, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback) {
// 回调 attachBaseContext()
attachBaseContext(context);
…
// 创建 PhoneWindow
mWindow = new PhoneWindow(this, window, activityConfigCallback);
…
// 第二个参数是 mToken
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
…
}
Activity 被创建之后会调用 attach() 方法,做了这么几件事:
- 创建了 PhoneWindow 对象
mWondow
- 给当前 window 绑定
mToken
- …
这里的 IBinder 对象 mToken 很重要。它是一个 Binder 对象,可以在 app 进程,system_server 进程之间进行传递。和我们通常所说的 Token 一样,这里也可以把它看做是一种特殊的令牌,用来标识 Windo