Reputation: 1491
I have a question concerning the best practices for designing and developing a 2d game on the Android OS. Following the Lunar Lander example, I have my game running on a separate thread so it doesn't block the UI thread. However, once certain "waves" are over in the game I want to show a screen to tally the score for that wave, show bonuses, etc. I was thinking about doing this as a separate activity by calling startActivityForResult() at the end of the wave. What is the best way to do this since I am not in the main thread? And would this even be considered a good practice?
Thanks!
Upvotes: 0
Views: 405
Reputation: 14633
This may have a useful answer for your situation. In short, startActivityForResult is synchronous, so if you don't mind pausing your Service, then that works. Otherwise, have the score Activity call back to the Service.
Upvotes: 0
Reputation: 36035
Create a Handler
in the main UI thread. Make it handle a message that a wave ends. In the game thread, call Handler.sendMessage(WAVE_END).sendToTarget()
on the Handler
to tell the UI thread that the wave ended. The Handler
will execute the code that you want.
Example:
public int MSG_WAVE_END = 1;
private final Handler endWave = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg.what == MSG_WAVE_END) { // the number is arbitrary. Traditionally a constant
// Do what you want to do when a wave ends like startActivityForResult()
}
}
}
Then in your game thread call this when your wave ends:
endWave.obtainMessage(MSG_WAVE_END).sendToTarget();
The Handler
essentially acts as a callback. You can send "messages" between threads safely to execute code on whatever thread it was created on. You can also pass two integer arguments and an object if need be. It will be contained in the Message
object.
Upvotes: 1