Android- Unable to add window -- token is not valid; is your activity running

Fatal Exception: android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@4272a800 is not valid; is your activity running?
       at android.view.ViewRootImpl.setView(ViewRootImpl.java:697)
       at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
       at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
       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:6165)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
This crash happens when an background thread completes its processing and trying to show dialog at the same time the context(Activity) is finishing or destroying. For example if Activity is being destroyed while user presses back button and at the same time dialog.show() called then, the dialog will not find any context as activity not available and app crashes. You should wrap .show() calls in a try/catch anyhow which handles the BadTokenException.
try {
        alertDialog.show()
    }
catch (WindowManager.BadTokenException e) {
     e.printStackTrace();
    }
From (Fabric)Crash-analytics I found the Crash Details:
This crash is usually caused by your app trying to display a dialog using a previously-finished Activity as a context. For example, this can happen if an Activity triggers an AsyncTask that tries to display a dialog when it is finished, but the user navigates back from the Activity before the task is completed.

Put the dialog.show( ) in the if condition as below::
if(!((Activity) context).isFinishing())
{
    //show dialog
}

For more: Error : BinderProxy@45d459c0 is not valid; is your activity running?  
    Android – Displaying Dialogs From Background Threads

No comments:

Post a Comment

Popular Posts