开发者

Access Android activity stack from asynchronous thread?

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 ot开发者_Go百科her 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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜