android dialog 有关token的问题

     android中的dialog显示一般是显示在宿主context里面,但context有几种模式,我今天遇到问题就是在BroadcastReceiver广播里面构造对话框后显示出现的问题:android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application,意思就是传的token不正确,查看一下dialog的源码,追踪到在Window源码有说明,显示的View有几种Type,对话框可以通过setType设置:

    1、FIRST_APPLICATION_WINDOW~LAST_APPLICATION_WINDOW类别,也就是我们常用的对话框类别,这个类别的dialog传进去的token的解析是:the token must be  set to the token of the activity they are a part of (this will normally be done for you if token is null).,也就是说一般我们传进去的context应该是activity的,不然就会有token is  null的异常

    2、FIRST_SUB_WINDOW~ LAST_SUB_WINDOW类别,token must be the token of the window it is attached to.
    3、FIRST_SYSTEM_WINDOW~LAST_SYSTEM_WINDOW类别, They should not normally be used by applications, and a special permission is required to use them.系统类别的对话框,这次在广播里面就用了这个级别,异常就不出现了。

    还有一个PS:在广播里面新建的对话框,发现下一次广播过来时调用dismiss对话框没有关闭,断点发现每次广播都会新建一个对话框实例,然后把对话框设置为static类型就唯一了,呵呵,记录一下

     记录自己遇到的问题以及解决方法,水平有限,欢迎拍砖指正~~~

原文地址:https://www.cnblogs.com/jiankeaibiancheng/p/4667060.html