dialog的Context

https://blog.csdn.net/yus201120/article/details/81634849

2020-06-23 17:05:06.160 30308-30308/com.uxin.kilanovel E/CrashReport: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:791)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
        at android.app.Dialog.show(Dialog.java:330)
        at com.uxin.novel.read.GiftDataAdapter.showBalanceLowDialog(GiftDataAdapter.java:109)
        at com.uxin.kilanovel.main.find.FindFragment.onClick(FindFragment.java:338)
        at android.view.View.performClick(View.java:6303)
        at android.view.View$PerformClick.run(View.java:24828)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6798)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

一,Context必须是Activity
dialog中windowManager的获取

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

如果上述context是Application,实际调用的是ContextImpl.getSystemService,获取的WM是new WindowManagerImpl(display);即mParentWindow为null;
如果上述context是Activity,获取的WM是new WindowManagerImpl(mDisplay, parentWindow),这个parentWindow就是Activity里的PhoneWindow,且这个PhoneWindow设置了mAppToken;
参考链接:https://blog.csdn.net/weitangzhu_2008/article/details/86706353

window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
这里设置弹窗的层级,数值越大层级就会越高,也就越会浮在最顶端。当用到的是一般的应用层级的时候,window的token,也就是我们构造Dialog时候的Context必须是Activity;如果是系统级的类型参数的时候,必须是全局的ApplicationContext才可以,同时还需要获取到系统级应用的权限。比如上面代码中就是系统级层级,需要获取到系统应用权限。

在dialogFragment中传入的context为ApplicationContext,没有报错崩溃,但是不弹出dialog

错误跟踪:

dialog.show();
image.png

addView()方法
image.png

ViewManager的实现类WindowManager中异常类
image.png

点击BadTokenException()方法查看调用处在ViewRootImpl
image.png

Dialog的getContext()
一般情况下我们是new Dialog(context),创建一个弹窗,此时getContext获取的不是我们传入的context,而是dialog自己new ContextThemeWrapper(context, themeResId);

你可能感兴趣的:(dialog的Context)