How: Start an Activity inside a Thread and use finish() to get back
I am programming a game on android. I'm using a Thread while calling a Surface View class to update and draw my game. Inside the update I wanted to start an activity based on if the game has just started and this would launch my MENUS.
My Thread for the most part..
while (myThreadRun) {
Canvas c = null;
try {
gameTime = System.currentTimeMillis();
c = myThreadSurfaceHolder.lockCanvas(null);
synchronized (myThreadSurfaceHolder) {
// Update Game.
myThreadSurfaceView.onUpdate();
// Draw Game.
myThreadSurfaceView.onDraw(c);
You can see there where I am updating the game... here is onUpdate();
protected void onUpdate() {
// Test if menu needs to be displayed.
while (thread.getMenu()) {
// Test if menu activity has been started.
if (thread.getMenuRunning() == false) {
Intent menuIntent = new Intent(this.getContext(), MyMenu.class);
((Activity) cxt).startActivityForResult(menuIntent, 1);
thread.setMenuRunning(true);
}
}
I am using a while loop because if I didn't use it the thread just keeps going.
Basically I just don't know how to implement my menus using a thread as a game loop. Everywhere I look it seems like that's best practice.
In my menu activity I just display the menu layout and a few开发者_如何转开发 buttons and when the person wants to start the game it uses finish() to go back to my thread where they play the game.
I am very new to this so any insight will be helpful,
Thanks
Your SurfaceView thread should concern itself solely with drawing the game's current state to the SurfaceView. Anything not to do with that rendering - especially things like deciding whether to run a menu activity - belongs on the UI thread.
So don't do all that stuff in your onUpdate()... do it in your game's Activity class, in response to the Menu button being pressed or something. You should be pausing your rendering thread from GameActivity.onPause() and resuming it in GameActivity.onResume() so the game isn't churning away while the menu is showing.
(And onResume() is also a good time for the game to react to the changes the user just made via the menu activity).
精彩评论