android.view.WindowManager$BadTokenException on custom dialo



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

*_ 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$3.onFinish (QuickMath.java:252)
  at android.os.CountDownTimer$1.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();

我怀疑自定义对话框的初始化。 我使用上下文作为"这个"是否正确?

android.view.WindowManager$BadTokenException:

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

不要

final Dialog customDialog = new Dialog(this);

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