My app's initial activity sends an Intent to an IntentService in its onStart() method. It places a ResultReceiver (anonymous inner class) in the Intent it uses to invoke the service. The service then uses the ResultReceiver to pass data base to the caller.
This seems to work fine, except when I launch the app and, while the service call is still running, quickly hit the "back" button to return to the home screen. As soon as the service action completes it sends a result to the ResultReceiver, whose onReceiveResult() method creates a progress dialog (using MyActivity.this as the context) and proceeds to do something else.
Trying to create the progress dialog is what generates the exception since the activity has already finished:
06-23 23:29:14.114: E/AndroidRuntime(29570): FATAL EXCEPTION: main
06-23 23:29:14.114: E/AndroidRuntime(29570): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@4051bf80 is not valid; is your activity running?
06-23 23:29:14.114: E/AndroidRuntime(29570): at android.view.ViewRoot.setView(ViewRoot.java:557)
06-23 23:29:14.114: E/AndroidRuntime(29570): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
06-23 23:29:14.114: E/AndroidRuntime(29570): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
06-23 23:29:14.114: E/AndroidRuntime(29570): at android.view.Window$LocalWindowManager.addView(Window.java:433)
06-23 23:29:14.114: E/AndroidRuntime(29570): at android.app.Dialog.show(Dialog.java:265)
06-23 23:29:14.114: E/AndroidRuntime(29570): at android.app.ProgressDialog.show(ProgressDialog.java:107)
06-23 23:29:14.114: E/AndroidRuntime(29570): at android.app.ProgressDialog.show(ProgressDialog.java:90)
06-23 23:29:14.114: E/AndroidRuntime(29570): at android.app.ProgressDialog.show(ProgressDialog.java:85)
06-23 23:29:14.114: E/AndroidRuntime(29570): at com.myapp.SplashScreen.someMethod(SplashScreen.java:137)
So then: what's the proper way to do this kind of thing in order to avoid the above?
It seems incredibly burdensome to have to check whether the activity is still running inside every callback before displaying a dialog. That alone makes me suspect I'm going at this the wrong way.
EDITED TO ADD:
This actually only seems to happen when I launch my app, quickly close it (via back button to home screen) then quickly launch it again. If I just launch it and hit the back button and then sit there for a few seconds I never get the exception.