AlertDialog Unable to add window

来源:互联网 发布:win7 禁止卸载软件 编辑:程序博客网 时间:2024/05/19 13:43

在广播中启动AlertDialog报这个错误android.view.WindowManager$BadTokenException: Unable to add window — token null 。

其实解决这个问题首先要搞清楚window原理。AlertDialog 首先是一个View。在Android系统中,任何一个View都是依附Window来启动的。

FrameWork定义了三种窗口类型。
1,应用Window:一般是指该Window对应一个Activity。
2,子Window:所谓子Window指的是该Window必须要有一个父Window,父Window可以是应用Window,也可以是其他Window。
3,系统Window:系统Window不需要任何Activity,也不需要父Window,理论上应用程序无法创建系统window,但是系统进程却能够创建系统window。

由于是在广播中启动的View,广播本身没有Window。那么只要指定AlertDialog的Window为系统Window就好了。
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
并且加上权限
就可以正常的弹出了。
其他View报Unable to add window — token null 也同样适用上诉原理。

0 0
原创粉丝点击