views:

75

answers:

1

There are a ton of activity stack related questions on StackOverflow, but I didn't really see any that answered the question I have. I'm working on an online game that (for now) has 3 different activities:

  1. Login/Register
  2. Menu (seen when logged in, includes "new game", "my stats", and a few other things...I'm just worried about the "new game" option for now.)
  3. Game

The socket connection occurs in the login/register activity, which creates a custom service that runs in the background. Since data can arrive at any point, the socket class I'm using has asynchronous response handlers. This means I won't have access to the current context any time a message is received.

I need a way to figure out what the current context is when various message types are received so that I can handle the message accordingly. For example, If a user's reached the game screen (#3 above) and gets one kind of message, it should simply tell the game screen to update with the new game state. However, the user could be at the same game screen and receive a different type of message that says "close screens #3 and #2 and log the user out, returning them to screen #1".

Basically, I'm trying to figure out the best way to get the current activity/context, determine if it's the right context for the current message, and how to handle it.

A: 

You could use an ordered broadcast. Have the service send out the broadcast. Have each activity register for the broadcast, with whatever priority scheme you feel is appropriate. Have the activity that gets the broadcast call abortBroadcast() so the broadcast is stopped. That way, your service can "blindly" send out the event.

You might not even need it to be ordered in this case. I think that a BroadcastReceiver registered by an activity will only receive broadcasts if the activity is in the foreground (not paused).

I have a bit more written about the pattern in a blog post, though for a slightly different situation (either handle an event in an activity or raise a Notification).

CommonsWare
This sounds like it might be exactly what I need. I'll take a detailed look when I get home, and if it does the trick, I'll definitely award you the answer. Thanks!
Matt Huggins