Search code examples
androidhandlerdelayandroid-alertdialog

Handler not closes before the activity finishes?


I have an app that finish with a handler to show a delayed dialog, this is to make a delayed post of the dialog after some seconds. My problem is that logcat it is show me the next error:

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@416b42d8 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:567)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at victor.martin.syncro.Finish$1.run(Finish.java:85)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)

I think that it is because, the app closes before the handler finishes.

This is the code, what can I do?

private Runnable alertDialog = new Runnable() {
    public void run() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Finish.this);

    // set the title of the Alert Dialog
alertDialogBuilder.setTitle(getResources().getString(R.string.rebootTitleAlert));

    // set dialog message
    alertDialogBuilder.setMessage(getResources().getString(R.string.rebootMessageAlert)).setCancelable(false).setPositiveButton(getResources().getString(R.string.rebootButtonAlert),new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            RootTools.restartAndroid();
            Finish.this.finish();
        }
    }).setNegativeButton(getResources().getString(R.string.laterButtonAlert), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
            Finish.this.finish();
        }
    });

AlertDialog alertDialog = alertDialogBuilder.create();

    alertDialog.show();

    }
};

How I can do to solve this?


Solution

  • You could check that your activity still exists before attempting to show the dialog.

    The error is thrown when you attempt to show the dialog (which is trying to attach itself to the activity) but the activity is no longer available.