所以我看到了错误

23  android.view.WindowManager$BadTokenException: Unable to add window --
            token android.os.BinderProxy@3970aa84 is not valid; is your activity running?
24  at android.view.ViewRootImpl.setView(ViewRootImpl.java:562)
25  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
26  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
27  at android.app.Dialog.show(Dialog.java:298)
28  at com.redacted.timerapp.TimerActivity.u(TimerActivity.java:1177)
29  at com.redacted.timerapp.TimerActivity.onStart(TimerActivity.java:271)


据报道可能有0.1%的案例(每天约10个案例),但我无法复制。该方法的代码如下:

private void showDonePrompt() {
    if (isFinishing()) return;
    Dialog donePrompt = new Dialog(this, R.style.darkDialogDone);
    donePrompt.requestWindowFeature(Window.FEATURE_NO_TITLE);
    donePrompt.setContentView(R.layout.dialog_dark_done);
    donePrompt.setCancelable(false);

    Button btnRepeat = (Button)donePrompt.findViewById(R.id.btnRepeat);
    btnRepeat.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // some DB operations, etc
            donePrompt.dismiss();
        }
    }
    Button btnStop = (Button)donePrompt.findViewById(R.id.btnStop);
    btnStop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // some DB operations, etc
            donePrompt.dismiss();
        }
    }

    donePrompt.show(); // this is line 1177 which presumably causes it
}


为什么会这样呢?我检查活动isFinishing()是否不应该尝试在活动未运行时显示提示,对吗?

最佳答案

您是isFinishing的来源。

/**
 * Check to see whether this activity is in the process of finishing,
 * either because you called {@link #finish} on it or someone else
 * has requested that it finished.  This is often used in
 * {@link #onPause} to determine whether the activity is simply pausing or
 * completely finishing.
 *
 * @return If the activity is finishing, returns true; else returns false.
 *
 * @see #finish
 */
public boolean isFinishing() {
    return mFinished;
}


因此,如果isFinishing为true,则Activity被销毁。

你可以试试看。

if(!isFinishing()){
    donePrompt.show();
}


要么

if(!hasWindowFocus()){
    donePrompt.show();
}

关于android - BadTokenException:无法添加窗口,您的 Activity 正在运行吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47341137/

10-10 13:59