android.view.WindowManager自定义对话框出现$BadTokenException

android.view.WindowManager$BadTokenException on custom dialog

我的应用程序在特定 android 版本和设备上崩溃并出现以下错误堆栈(VIVO android 5.1 和 Oneplus one Android 7.1)

*_ android.view.WindowManager$BadTokenException:
  at android.view.ViewRootImpl.setView (ViewRootImpl.java:679)
  at android.view.WindowManagerGlobal.addView (WindowManagerGlobal.java:342)
  at android.view.WindowManagerImpl.addView (WindowManagerImpl.java:94)
  at android.app.Dialog.show (Dialog.java:329)
  at com.yathirajjp.brainstimuli.QuickMath.showCustomDialog (QuickMath.java:193)
  at com.yathirajjp.brainstimuli.QuickMath.onFinish (QuickMath.java:252)
  at android.os.CountDownTimer.handleMessage (CountDownTimer.java:127)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6186)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:889)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:779) _*

来自QuickMath.java的代码片段如下

final Dialog customDialog = new Dialog(**this**);
customDialog.setContentView(R.layout.custom_dialog_layout);

waitTimer.cancel();  // Cancelling the CountDownTimer before calling the show custom dialog

customDialog.show();

我怀疑customDialog的初始化。我将上下文用作 'this' 是否正确?

android.view.WindowManager$BadTokenException:

你应该调用 YourActivity.this 而不是 this.

不要

final Dialog customDialog = new Dialog(this);

final Dialog customDialog = new Dialog(QuickMath.this);