Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?
Asked Answered
L

18

146

I try to connect to Facebook throught Facebook API, I follow this example: https://github.com/facebook/facebook-android-sdk/tree/master/examples/simple

Everything is ok, but when I try to edit some code, I mean I want to display the dialog post message after the login is successful like this:

public void onAuthSucceed() {
        mText.setText("You have logged in! ");   
        //This is the code to call the post message dialog.                     
        mFacebook.dialog(Example.this, "feed",new SampleDialogListener());   
    }

I receive this error in the logcat:

03-02 13:32:08.629: E/AndroidRuntime(14991): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@405180f8 is not valid; is your activity running?
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.view.ViewRoot.setView(ViewRoot.java:532)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.view.Window$LocalWindowManager.addView(Window.java:424)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.app.Dialog.show(Dialog.java:241)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Facebook.dialog(Facebook.java:780)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Facebook.dialog(Facebook.java:737)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Example$SampleAuthListener.onAuthSucceed(Example.java:113)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.SessionEvents.onLoginSuccess(SessionEvents.java:78)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Example$LoginDialogListener.onComplete(Example.java:88)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.Facebook$1.onComplete(Facebook.java:320)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.facebook.android.FbDialog$FbWebViewClient.shouldOverrideUrlLoading(FbDialog.java:144)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:218)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:337)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.os.Looper.loop(Looper.java:130)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at android.app.ActivityThread.main(ActivityThread.java:3687)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at java.lang.reflect.Method.invokeNative(Native Method)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at java.lang.reflect.Method.invoke(Method.java:507)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
03-02 13:32:08.629: E/AndroidRuntime(14991):    at dalvik.system.NativeStart.main(Native Method)

Any idea?

Largish answered 2/3, 2012 at 7:23 Comment(7)
possible duplicate of Error : BinderProxy@45d459c0 is not valid; is your activity running?Kingston
Check the answer below. I've mark it's correct :)Largish
Just because you've marked the answer doesn't change the fact that this is a duplicate question. The other was asked first and is an identical issue with an essentially identical answer.Kingston
Did you see that my question is 2 years ago?Largish
Yes I did. And the other was asked 3 years ago. Its really not a big deal, that is how the forum works. We try to consolidate duplicated questions.Kingston
So look like others Moderator has mistake but you :)) Anw, thanks!Largish
This can be caused by a bug in Android 7.1. See answer at https://mcmap.net/q/145908/-fatal-exception-android-view-windowmanager-badtokenexception-unable-to-add-window-token-is-not-valid-is-your-activity-running using github.com/drakeet/ToastCompat.Exemplify
V
143

This can occur when you are showing the dialog for a context that no longer exists. A common case - if the 'show dialog' operation is after an asynchronous operation, and during that operation the original activity (that is to be the parent of your dialog) is destroyed. For a good description, see this blog post and comments:

http://dimitar.me/android-displaying-dialogs-from-background-threads/

From the stack trace above, it appears that the facebook library spins off the auth operation asynchronously, and you have a Handler - Callback mechanism (onComplete called on a listener) that could easily create this scenario.

When I've seen this reported in my app, its pretty rare and matches the experience in the blog post. Something went wrong for the activity/it was destroyed during the work of the the AsyncTask. I don't know how your modification could result in this every time, but perhaps you are referencing an Activity as the context for the dialog that is always destroyed by the time your code executes?

Also, while I'm not sure if this is the best way to tell if your activity is running, see this answer for one method of doing so:

Check whether activity is active

Vulcanology answered 9/5, 2012 at 4:27 Comment(2)
Not calling dialog.show() solves the problem but what is the work around to it to be able to still show my dialog?Starling
For me, I'm calling Fragment.getContext(), which works for APIs above 21. But on Lollipop it crashesDeportation
R
186

I was seeing this error reported once in a while from some of my apps, and here's what solved it for me:

if(!((Activity) context).isFinishing())
{
    //show dialog
}

All the other answers out there seem to be doing weird things like iterating through the list of running activities, but this is much simpler and seems to do the trick.

Reclamation answered 23/1, 2013 at 20:17 Comment(6)
it doesn't solve the problem, it prevents crash and showing dialog as wellBall
Just remember you should check context instanceof Activity or you may get an Exception !Maharashtra
or you can use getActivity().isFinishing() instead of contextVang
I am using API-23 . When i try to use this in my MainActivity which extends AppCompatActivity. It shows me a error like Caused by: java.lang.ClassCastException: com.creativeapp.hindihdvideosongs.AppController cannot be cast to android.app.Activity at com.creativeapp.hindihdvideosongs.MainActivity.onCreate(MainActivity.java:145) AppController is added into my AndroidMenifestFootfall
I am not using any dialogue and getting this error.Eleventh
Well, it's android. There is no solid steady solution on anything. 2+2 can equal 4 and 5 and 6. Sometimes we just have to pray to have fewer crashes.Fitton
V
143

This can occur when you are showing the dialog for a context that no longer exists. A common case - if the 'show dialog' operation is after an asynchronous operation, and during that operation the original activity (that is to be the parent of your dialog) is destroyed. For a good description, see this blog post and comments:

http://dimitar.me/android-displaying-dialogs-from-background-threads/

From the stack trace above, it appears that the facebook library spins off the auth operation asynchronously, and you have a Handler - Callback mechanism (onComplete called on a listener) that could easily create this scenario.

When I've seen this reported in my app, its pretty rare and matches the experience in the blog post. Something went wrong for the activity/it was destroyed during the work of the the AsyncTask. I don't know how your modification could result in this every time, but perhaps you are referencing an Activity as the context for the dialog that is always destroyed by the time your code executes?

Also, while I'm not sure if this is the best way to tell if your activity is running, see this answer for one method of doing so:

Check whether activity is active

Vulcanology answered 9/5, 2012 at 4:27 Comment(2)
Not calling dialog.show() solves the problem but what is the work around to it to be able to still show my dialog?Starling
For me, I'm calling Fragment.getContext(), which works for APIs above 21. But on Lollipop it crashesDeportation
Q
24

one simple workaround is to catch the exception :

try {
        alertDialog.show()
    }
catch (WindowManager.BadTokenException e) {
        //use a log message
    }

It's not elegant but sometimes easy when you have to manage async operations and you are not sure wether activity is up or not when you want to show the dialog.

Quesada answered 15/7, 2018 at 17:23 Comment(1)
so ugly yet so beautiful!Armenia
M
13
  • In my case the issue is occurred because of am trying to open/show dialog box in onPostExecute AsyncTask

  • However its an wrong method of showing dialog or Ui changes in onPostExecute.

  • For that, we need to check the activity is in active Eg : !isFinishing() , if the activity is not finished then only able to show our dialog box or ui change.

    @Override
    protected void onPostExecute(String response_str) {
    
       getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!((Activity) mContext).isFinishing()) {
                            try {
                                ShowAgilDialog();
                            } catch (WindowManager.BadTokenException e) {
                                Log.e("WindowManagerBad ", e.toString());
                            }
                        }
                    }
                });
    }
    
Margo answered 8/1, 2019 at 11:3 Comment(1)
This works but what about our dialog? We won't be able to show it if it went in catch blockPretense
E
1

I faced exactly the same issue. Calling '(!isFinishing())' prevented the crash, but it could not display the 'alert' message.

Then I tried making calling function 'static', where alert is displayed. After that, no crash happened and message is also getting displayed.

For ex:

public static void connect_failure() {      
        Log.i(FW_UPD_APP, "Connect failed");

        new AlertDialog.Builder(MyActivity)
        .setTitle("Title")
        .setMessage("Message")
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                  //do nothing
            }
         })
        .setIcon(R.drawable.the_image).show();      
    }
Eventuate answered 10/6, 2014 at 7:7 Comment(0)
D
1

After execute the thread, add these two line of code, and that will solve the issue.

Looper.loop();
Looper.myLooper().quit();
Dysgenic answered 4/9, 2018 at 2:49 Comment(0)
P
1

Another developer use case: If the WindowManager or getWindow() is being called on onCreate() or onStart() or onResume(), a BadTokenException is thrown. You will need to wait until the view is prepared and attached.

Moving the code to onAttachedToWindow() solves it. It may not be a permanent solution, but as much as I could test, it always worked.

In my case, there was a need to increase the screen brightness when the activity became visible. The line getWindow().getAttributes().screenBrightness in the onResume() resulted in an exception. Moving the code to onAttachedToWindow() worked.

Presser answered 23/12, 2019 at 13:16 Comment(0)
G
1

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

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.

External resources

Android – Displaying Dialogs From Background Threads

Error : BinderProxy@45d459c0 is not valid; is your activity running?

Graeco answered 24/4, 2020 at 9:41 Comment(0)
H
1

how's I handled is every time dismissing and doing null the dialog reference before showing dialog

public static void showProgressDialog(Context context){
    if (context==null)return;
    //do force null when trigger this method to avoid Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?
    if (dialog!=null && dialog.isShowing()){
        dialog.dismiss();
        dialog=null;
    }
    dialog=new Dialog(context);

    dialog.setCancelable(false);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.setContentView(ProgressBarLayoutBinding.inflate(LayoutInflater.from(context)).getRoot());
    if ((context instanceof AppCompatActivity  &&  !((AppCompatActivity) context).isFinishing()) && !dialog.isShowing()) {
        dialog.show();
    }
}
Hoo answered 6/9, 2021 at 12:14 Comment(0)
O
1

Problem

dialog.show(); // Getting error here...

Solution

private void Dialog(){
    if(!isFinishing()) { //by checking the activity is finished. We can solve this issue....
        dialog = new ProgressDialog(YourActivity.this);
        dialog.setMessage("Loading...");
        dialog.setCancelable(false);
        dialog.show(); 
    }
}
Openwork answered 5/1, 2023 at 13:30 Comment(0)
B
1

Check if the activity is finishing and its not null before showing the dialog.

if(activity != null && !activity.isFinishing()) {

//show dialog here

}

Blasphemous answered 27/3, 2023 at 11:47 Comment(0)
V
0

Just move your dialog code on Ui thread like this:

runOnUiThread{
// your dialog code or function
}
Vegetal answered 25/12, 2022 at 18:57 Comment(0)
V
0

For all who the "!isFinishing()" solution didn't work for them:

try to re-initialize the dialog also in onResume() .

Vachil answered 13/6, 2023 at 13:51 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Sublunary
S
0

Check what context you are passing to create a dialog box that is also a important, in my case i was calling from common class due to which it was not taking the proper context so i pass the context in function and it work.

For eg: CommonClass.getInstance(context).showDialog(context)

Shurlock answered 29/8, 2023 at 13:4 Comment(0)
S
-1

For me it was fixed by just removing the static property in the DialogHelper.class methods (resposble for creating & hiding the dialog), as I have properties related to Window in those methods

Stoeber answered 4/7, 2019 at 9:25 Comment(0)
S
-1

What you should do is to check if activity is finishing before showing alert. For this purpose isFinishing() method is defined within Activity class.

Here is what you should do:

if(!isFinishing())
 {
     alert.show();
 }
Sacred answered 15/10, 2020 at 7:11 Comment(0)
A
-1
if ((context instanceof AppCompatActivity && !((AppCompatActivity) context).isFinishing()) && !dialog.isShowing()) {
    dialog.show();
}

Try this, the dialog will be only called while the activity is alive else it won't.

Altamira answered 6/6, 2022 at 7:7 Comment(0)
V
-2

Under dependencyServices nothing of the above helped me, i ended up doing like below:

    class Static_Toast_Android
    {
        private static Context _context
        {
            get { return Android.App.Application.Context; }
        }
        public static void StaticDisplayToast(string message)
        {
            Toast.MakeText(_context, message, ToastLength.Long).Show();
        }
    }
    public class Toast_Android : IToast
    {

        public void DisplayToast(string message)
        {
            Static_Toast_Android.StaticDisplayToast(message);
        }
    }

I must use the "double-class" because an interface cannot be static. L-

Volpe answered 29/7, 2019 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.