This seems like it should be simple, but I'm not finding an answer anywhere. I have an Android application that performs network tasks in the background. If an error comes back, I want to display an error dialog. When the task returns, I don't know which Activity is in the foreground. Based on this post, it looks like we can't use the application context to display a dialog (and indeed I do get the crash if I try).
So how can I get the context of the current activity? Again, the receiver for the network task is running in the Application context, not in a particular Activity. Any other ideas?
Edit: I should clarify. I don't want to display an error dialog if I'm not the foreground application. I'm only interested in the case where our app is in the foreground for now.
If an error comes back, I want to display an error dialog.
Please only do this if you know that the user is actively using your application. The user will be very very annoyed if you interrupt them in the middle of something else (playing a game, watching a movie, reading a book).
So how can I get the context of the current activity?
You don't. At most, you let the current activity know that it needs to do something.
Any other ideas?
One possibility is to use an ordered broadcast, so if you have a foreground activity, it gets control, otherwise you raise a Notification
to let the user know about the problem without popping a dialog. The activity that receives the ordered broadcast can display an AlertDialog
or otherwise let the user know about the problem. I wrote about the details of how to do this in a blog post (and a book chapter, for that matter), and here is a sample application demonstrating the technique.
Or, have the service call startActivity()
to start up a dialog-themed activity.