为什么不能使用-Application-Context-显示-Dialog?

  1. 为什么不能使用 Application Context 显示 Dialog?

本文永久更新地址: xiaozhuanlan.com/topic/39581…

目录

  • 为什么不能使用 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 一样,这里也可以把它看做是一种特殊的令牌,用来标识 Window ,在对 Window 进行视图操作的时候就可以做一些校验工作。

所以,Activity 对应的 Window/WMS 都是持有这个 mToken 的。结合之前 Application 创建 Dialog 的报错信息,我们可以大胆猜测 Application Context 创建 Dialog 的过程中,并没有实例化类似的 token。

回到 Dialog 的构造函数中,

Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {

// 获取 WindowManager
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

final Window w = new PhoneWindow(mContext);
mWindow = w;

}
复制代码

根据传入的 Context 调用 getSystemService(Context.WINDOW_SERVICE) 方法来得到 WindowManager 对象 mWindowManager ,最终会通过 mWindowManager.addWindow() 来显示 dialog 。

如果传入的 Context 是 Activity,返回的是在 Activity.attach() 方法中创建的 mWindowManager 对象,这个时候 mToken 也已经绑定。

Activity.java

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

if (WINDOW_SERVICE.equals(name)) {
return mWindowManager; // 在 attach() 方法中已经实例化
} else if (SEARCH_SERVICE.equals(name)) {
ensureSearchManager();
return mSearchManager;
}
return super.getSystemService(name);
}
复制代码

如果传入的 Context 是 Application,最终调用的是父类 ContextImpl 的方法。

@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
复制代码

SystemServiceRegistry.getSystemService(this, name) 拿到的是已经提前初始化完成并缓存下来的系统服务,并没有携带任何的 Token。

registerService(Context.WINDOW_SERVICE, WindowManager.class,
new CachedServiceFetcher() {
@Override
public WindowManager createService(ContextImpl ctx) {
return new WindowManagerImpl(ctx);
}});
复制代码

所以,Android 不允许 Activity 以外的 Context 来创建和显示普通的 Dialog 。 这里的 普通 指的是文章开头示例代码中的普通 Dialog,并非 Toast,System Dialog 等等。Android 系统为了安全考虑,不想在 App 进入后台之后仍然可以弹出 Dialog,这样就会产生可以在其他 App 中弹窗的场景,造成一定的安全隐患。虽然通过 Dialog Theme 的 Activity 仍然可以实现这一需求,但是 Google 也在加强 对后台启动 Activity 的限制

写到这里,问题似乎已经得到了解答。但是其实我们对于整个 Token 流程还是一片雾水的。试着想一下下面几个问题。

  • mToken 是在什么时机,什么地方创建的?
  • WMS 是如何拿到 mToken 的?
  • WMS 是如何校验 token 的?

真正掌握了这些问题之后,才能形成一个完整的知识闭环,但伴随而来的,是逃避不了的,枯燥乏味的 Read the fucking AOSP 。

谁创建了 Token?

先来看看 Token 到底是个什么样的类。

ActivityRecord.java

static class Token extends IApplicationToken.Stub {
private final WeakReference weakActivity;
private final String name;

Token(ActivityRecord activity, Intent intent) {
weakActivity = new WeakReference<>(activity);
name = intent.getComponent().flattenToShortString();
}


}
复制代码

TokenActivityRecord 的静态内部类,它持有外部 ActivityRecord 的弱引用。继承自 IApplicationToken.Stub ,是一个 Binder 对象。它在 ActivityRecord 的构造函数中初始化。

ActivityRecord.java

ActivityRecord(ActivityManagerService _service, ProcessRecord _caller, int _launchedFromPid,
int _launchedFromUid, String _launchedFromPackage, Intent _intent, String _resolvedType,
ActivityInfo aInfo, Configuration _configuration,
ActivityRecord _resultTo, String _resultWho, int _reqCode,
boolean _componentSpecified, boolean _rootVoiceInteraction,
ActivityStackSupervisor supervisor, ActivityOptions options,
ActivityRecord sourceRecord) {
service = _service;
// 初始化 appToken
appToken = new Token(this, _intent);

}
复制代码

一个 ActivtyRecord 代表一个 Activity 实例, 它包含了 Activity 的所有信息。在 Activity 的启动过程中,当执行到 ActivityStarter.startActivity() 时,会创建待启动的 ActivityRecord 对象,也间接创建了 Token 对象。

ActivityStarter.java

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
SafeActivityOptions options,
boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
PendingIntentRecord originatingPendingIntent) {

// 构建 ActivityRecord,其中会初始化 token
ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
mSupervisor, checkedOptions, sourceRecord);


return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
}
复制代码

到这里, ActivityRecord.appToken 已经被赋值。所以 Token 是在 AMS 的 startActivity 流程中创建的。但是 Token 的校验显然是发生在 WMS 中的,所以 AMS 还得把 Token 交到 WMS 。

WMS 是如何拿到 Token 的?

继续跟下去,startActivity() 最后会调用到 ActivityStack.startActivityLocked(),这个方法就是把 Token 给到 WMS 的关键。

ActivityStack.java

void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
boolean newTask, boolean keepCurTransition, ActivityOptions options) {

if (r.getWindowContainerController() == null) {
// 创建 AppWindowContainerController 对象,其中包含 token 对象
r.createWindowContainer();

}
复制代码

其他代码都省略了,重点关注 r.createWindowContainer(),这里的 r 就是一开始创建的 ActivityRecord 对象。

ActivityRecord.java

void createWindowContainer() {
if (mWindowContainerController != null) {
throw new IllegalArgumentException(“Window container=” + mWindowContainerController

  • " already created for r=" + this);
    }

inHistory = true;

final TaskWindowContainerController taskController = task.getWindowContainerController();

// 构造函数中会调用 createAppWindow() 创建 AppWindowToken 对象
mWindowContainerController = new AppWindowContainerController(taskController, appToken,
this, Integer.MAX_VALUE /* add on top */, info.screenOrientation, fullscreen,
(info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0, info.configChanges,
task.voiceSession != null, mLaunchTaskBehind, isAlwaysFocusable(),
appInfo.targetSdkVersion, mRotationAnimationHint,
ActivityManagerService.getInputDispatchingTimeoutLocked(this) * 1000000L);

task.addActivityToTop(this);


}
复制代码

AppWindowContainerController 的构造函数中传入了之前已经初始化过的 appToken

AppWindowContainerController.java

public AppWindowContainerController(TaskWindowContainerController taskController,
IApplicationToken token, AppWindowContainerListener listener, int index,
int requestedOrientation, boolean fullscreen, boolean showForAllUsers, int configChanges,
boolean voiceInteraction, boolean launchTaskBehind, boolean alwaysFocusable,
int targetSdkVersion, int rotationAnimationHint, long inputDispatchingTimeoutNanos,
WindowManagerService service) {
super(listener, service);
mHandler = new H(service.mH.getLooper());
mToken = token;
synchronized(mWindowMap) {

atoken = createAppWindow(mService, token, voiceInteraction, task.getDisplayContent(),
inputDispatchingTimeoutNanos, fullscreen, showForAllUsers, targetSdkVersion,
requestedOrientation, rotationAnimationHint, configChanges, launchTaskBehind,
alwaysFocusable, this);

}
}
复制代码

createAppWindow() 方法中会创建 AppWindowToken 对象,注意传入的 token 参数。

AppWindowContainerController.java

AppWindowToken createAppWindow(WindowManagerService service, IApplicationToken token,
boolean voiceInteraction, DisplayContent dc, long inputDispatchingTimeoutNanos,
boolean fullscreen, boolean showForAllUsers, int targetSdk, int orientation,
int rotationAnimationHint, int configChanges, boolean launchTaskBehind,
boolean alwaysFocusable, AppWindowContainerController controller) {
return new AppWindowToken(service, token, voiceInteraction, dc,
inputDispatchingTimeoutNanos, fullscreen, showForAllUsers, targetSdk, orientation,
rotationAnimationHint, configChanges, launchTaskBehind, alwaysFocusable,
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

最后

这里附上上述的技术体系图相关的几十套腾讯、头条、阿里、美团等公司2021年的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

相信它会给大家带来很多收获:

img

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

  • 无论你现在水平怎么样一定要 持续学习 没有鸡汤,别人看起来的毫不费力,其实费了很大力,这四个字就是我的建议!!!
  • 我希望每一个努力生活的IT工程师,都会得到自己想要的,因为我们很辛苦,我们应得的。

当我们在抱怨环境,抱怨怀才不遇的时候,没有别的原因,一定是你做的还不够好!

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

  • 无论你现在水平怎么样一定要 持续学习 没有鸡汤,别人看起来的毫不费力,其实费了很大力,这四个字就是我的建议!!!
  • 我希望每一个努力生活的IT工程师,都会得到自己想要的,因为我们很辛苦,我们应得的。

当我们在抱怨环境,抱怨怀才不遇的时候,没有别的原因,一定是你做的还不够好!

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值