Android高工面试(难度,flutter开发工具

目录

  • 为什么不能使用 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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值