Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity.showDialog when activity may not be in foreground

Tags:

android

I have an activity that gets some data from the internet in background while showing a progress dialog. When I get the data (or an error) I dismiss that dialog and show another one.

If for some reason the website takes too long to deliver the response (15+ seconds for example), the phone will turn off the screen. Now, while the screen is off, if I get a response and try to show a dialog, there will be an error (WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@483fa968 is not valid; is your activity running?)

The reason of this problem is simple: when the screen turned off, another activity came to the foreground (keyguard or something).

Question: Now, whats the best method for invoking showDialog on an activity that we know that might not be running? (the activity was created but it's not the one the user is interacting with.. in other words, it's in stopped state).

I believe a similar behavior would happen if I clicked home and changed to the Home activity. (Although I can't do this in my particular case because my activity would cancel the request and everything would shutdown correctly).

I don't think that this makes any difference, but I reproduced this in Android 2.1

like image 773
Pedro Loureiro Avatar asked Dec 22 '10 19:12

Pedro Loureiro


1 Answers

Catch that exception and use some kind of persistent storage to save a flag that shows that you are waiting to show a dialog. Then in onResume() check that flag and if its true show the appropriate dialog. Something like this perhaps:

try {
    getYourDataFromWeb();
    showDialog()
} catch (BadTokenException e) {
    myPrefsEditor.putBoolean("FailedToShowDialog", true);
    myPrefsEditor.commit();
    e.printStackTrace();
}

Then in your onResume() method something like this:

if(myPrefs.getBoolean("FailedToShowDialog", false) == true){
    showDialog();
    myPrefsEditor.putBoolean("FailedToShowDialog", false);
    myPrefsEditor.commit();
}
like image 127
FoamyGuy Avatar answered Dec 17 '22 07:12

FoamyGuy