在广播接收器中调起Dialog

最近有一个需求,在后台接收到广播后需要弹出一个Dialog,然后进行设置。但当我使用receiver自带的context创建Dialog时程序却直接崩溃了。报的如下错误:

[20:37:48:712]E/AndroidRuntime( 5073): java.lang.RuntimeException: Unable to start receiver com.konka.kksystemui.funtion.SystemUIReceiver: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
[20:37:48:712]E/AndroidRuntime( 5073):        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2426)
[20:37:48:713]E/AndroidRuntime( 5073):        at android.app.ActivityThread.access$1700(ActivityThread.java:135)
[20:37:48:713]E/AndroidRuntime( 5073):        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
[20:37:48:713]E/AndroidRuntime( 5073):        at android.os.Handler.dispatchMessage(Handler.java:102)
[20:37:48:713]E/AndroidRuntime( 5073):        at android.os.Looper.loop(Looper.java:136)
[20:37:48:713]E/AndroidRuntime( 5073):        at android.app.ActivityThread.main(ActivityThread.java:5017)
[20:37:48:713]E/AndroidRuntime( 5073):        at java.lang.reflect.Method.invokeNative(Native Method)
[20:37:48:714]E/AndroidRuntime( 5073):        at java.lang.reflect.Method.invoke(Method.java:515)
[20:37:48:714]E/AndroidRuntime( 5073):        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:742)
[20:37:48:714]E/AndroidRuntime( 5073):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
[20:37:48:714]E/AndroidRuntime( 5073):        at dalvik.system.NativeStart.main(Native Method)
[20:37:48:714]E/AndroidRuntime( 5073): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
[20:37:48:715]E/AndroidRuntime( 5073):        at android.view.ViewRootImpl.setView(ViewRootImpl.java:540)
[20:37:48:715]E/AndroidRuntime( 5073):        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
[20:37:48:715]E/AndroidRuntime( 5073):        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
[20:37:48:715]E/AndroidRuntime( 5073):        at android.app.Dialog.show(Dialog.java:286)
[20:37:48:715]E/AndroidRuntime( 5073):        at com.konka.android.kkui.lib.KKDialog$Builder.show(KKDialog.java:435)
[20:37:48:716]E/AndroidRuntime( 5073):        at com.konka.kksystemui.funtion.SystemUIReceiver.onReceive(SystemUIReceiver.java:40)
[20:37:48:716]E/AndroidRuntime( 5073):        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2419)
[20:37:48:720]E/AndroidRuntime( 5073):        ... 10 more

从 log 可以看出,该问题是调起 Dialog 的是一个不正确的 Token ,也不是 Application 对应的 token ,顾名思义,我便使用了 context.getApplicationContext()进行创建,发现仍然报了以上错误。无奈之下,多方查找后发现还需要将该Dialog声明为系统级别,这样弹出的就是一个系统级别的对话框,于是将Type设置为WindowManager.LayoutParams.TYPE_SYSTEM_ALERT便可以正确调起Dialog。

具体方法如下:
mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

你可能感兴趣的:(在广播接收器中调起Dialog)