【问题标题】:WindowManager$BadTokenException on toast and activity changeToast 和活动更改时出现 WindowManager$BadTokenException
【发布时间】:2019-06-06 09:07:48
【问题描述】:

我正在为我的 utils 文件中已处理的项目显示祝酒词。

我面临的情况是,如果我扫描 10 个项目,然后我改变了我的屏幕,toasts 仍在进行中,我的应用程序崩溃了

Fatal Exception: android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@321daf0 is not valid; is your activity running?

下面是我正在使用的代码。

活动中

UtilityMethods.showToast(ActivityName.this, "message"));

在 UtilityMethods 中

public static void showToast(Context c, String s) {
    Toast.makeText(c, s, Toast.LENGTH_SHORT).show();
}

我尝试了什么

我尝试像这样添加一个 try catch 块:

public static void showToast(Context c, String s) {
    try {
        Toast.makeText(c, s, Toast.LENGTH_SHORT).show();
    }
    catch (WindowManager.BadTokenException e){
        e.printStackTrace();
    }
}

但它仍然崩溃。

完整的例外如下:

Fatal Exception: android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@321daf0 is not valid; is your activity running?
   at android.view.ViewRootImpl.setView(ViewRootImpl.java:720)
   at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
   at android.widget.Toast$TN.handleShow(Toast.java:459)
   at android.widget.Toast$TN$2.handleMessage(Toast.java:342)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6123)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

我还找到了一些关于 SO 的其他解决方案,但没有奏效。

请建议在我的情况下可以做什么,提前谢谢。

【问题讨论】:

  • 它在说明问题...is your activity running? 所以请确定它在问什么
  • 我知道问题所在,只是不知道如何解决。我已经提到了我尝试过的内容。 :(
  • 您在活动中的哪个位置调用showToast 方法?
  • 不要使用 toast 向用户显示数据,而是使用通知。如果您尝试连续显示很多内容,toasts 将使您的应用崩溃。

标签: android exception android-intent android-activity android-toast


【解决方案1】:

您仅使用this 来指向您的活动。确保 this 指的是您的活动上下文,而不是其他任何内容,因为 Toast 需要来自活动上下文的信息。尝试使用其上下文时使用全名引用您的活动,尝试使用以下代码。

UtilityMethods.showToast(YourActivityName.this, "message"));

【讨论】:

  • 我只使用了ActivityName.this,但它不起作用。我已经更新了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多