为什么dialog.show()会导致我的应用崩溃?

时间:2016-04-28 08:04:27

标签: java android

我一直试图在android上运行一个对话框消息,当应用程序到达“dialog.show();”时,应用程序总是崩溃。

public class Logic extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
    dialogBuilder.setTitle("Alarm");
    dialogBuilder.setMessage(messageActivity.getMes());
    dialogBuilder.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    AlertDialog dialog = dialogBuilder.create();
    dialog.show();
}
}

这是我的logcat:

FATAL EXCEPTION: main

Process: it226.myapplicationit226androidapp, PID: 19598
java.lang.RuntimeException: Unable to start receiver it226.myapplicationit226androidapp.Logic: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2732)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
    at android.app.Dialog.show(Dialog.java:319)
    at it226.myapplicationit226androidapp.Logic.onReceive(Logic.java:65)
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2725)
    at android.app.ActivityThread.-wrap14(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 

2 个答案:

答案 0 :(得分:3)

您无法从接收器创建对话框。 只允许从UI组件(具有looper)创建对话框。

您可以使用对话框启动透明活动,对用户来说也是如此。

答案 1 :(得分:0)

您无法使用dialog的{​​{1}}创建context,您有两个选项来解决此问题:

第一个是创建一个常规的Activity,其中只有对话框的大小作为显示的部分,而完整的剩余部分是透明的:

BroadcastReceiver

第二个是保存您的Activity上下文,然后在创建对话框时使用它,但是在这种方法中,您必须确保当前打开的活动是什么:

Intent newIntent = new Intent(context, Displayer.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);