如何修复在 Android 中使用对话框时无法添加 window

How to fix Unable to add window when use Dialog in Android

在我的应用程序中,我想使用 dialog,为此我应该 将自定义视图 设置为 dialog
我写了下面的代码,但是当 运行 应用程序在 LogCat.
[ 上显示 ForceClose 错误时=16=]

我的代码:

   if (!isPremium) {
        count = prefsUtils.getFromShared_INT(PrefsKeys.TRIAL_COUNT.name());
        prefsUtils.setToShared_INT(PrefsKeys.TRIAL_COUNT.name(), count + 1);
        if (count > 10) {
            final Dialog dialog = new Dialog(getApplicationContext());
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.dialog_end_trial);
            TextView dialogEndCount_premiumTxt = dialog.findViewById(R.id.dialogEndCount_premiumTxt);
            dialogEndCount_premiumTxt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, MainActivity2.class);
                    startActivity(intent);
                    finish();
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

LogCat 上的错误消息:

 Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:702)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
    at android.app.Dialog.show(Dialog.java:337)
    at com.mcc.wpnews.activity.PostDetailsActivity.initView(PostDetailsActivity.java:176)
    at com.mcc.wpnews.activity.PostDetailsActivity.onCreate(PostDetailsActivity.java:104)
    at android.app.Activity.performCreate(Activity.java:6754)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6247) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 

我该如何解决?

不要使用 getApplicationContext() 除非你知道 为什么 你正在使用 getApplicationContext().

您无法使用 Application 显示 Dialog。所以,把new Dialog(getApplicationContext())换成new Dialog(this),你的运气应该会更好。

有关何时使用不同类型 Context 的更多信息,请参阅 this classic blog post from Dave Smith