什么属于项目类的BadTokenException

问题描述 投票:3回答:2

我试图在API 25中运行我的应用程序,但当我点击按钮时出现此错误:

E/ACRA: ACRA caught a BadTokenException for com.safa.visit.ts.debug
    android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@2fc535e is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:922)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:377)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:105)
        at android.widget.Toast$TN.handleShow(Toast.java:747)
        at android.widget.Toast$TN$2.handleMessage(Toast.java:622)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6823)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'

我搜索过,我发现这个问题是Toast。因为toast上下文可能是NULL。为此我在显示上下文之前检查了上下文。这是我的方法:

    private void toastError(Context ctx,final String msg) {
    if (ctx != null)
    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}

我的问题是,我不知道这个错误是针对什么页面或类,因为那个地方,我点击了按钮并出现了这个错误,我把我的方法放在那里并且使用了我的方法而不是Toast但我仍然得到了这个错误。

你有什么建议我的?

android android-studio
2个回答
2
投票

尝试:

if(!((Activity) context).isFinishing())
{
     Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}

6
投票

我创建了一个库来钩住并修复这个BadTokenException

https://github.com/drakeet/ToastCompat

只需使用:

ToastCompat.makeText(context, "hello world!", Toast.LENGTH_SHORT).show();

或者与BadTokenListener#onBadTokenCaught(@NonNull Toast toast)

ToastCompat.makeText(this, "hello", Toast.LENGTH_SHORT)
    .setBadTokenListener(toast -> {
        ...
    }).show();

为什么例外:https://github.com/drakeet/ToastCompat#why

© www.soinside.com 2019 - 2024. All rights reserved.