[英]ending android activity from surfaceview using thread.join
我正在為Android開發第一個應用程序-snake。 現在,我正在嘗試為該應用實施“游戲結束”。 因此,基本上,當蛇撞到牆上時,應用程序應該詢問您的名字,並將其分數記錄在HiScore上。 好吧,我在砸牆碎片。 我正在嘗試線程,到目前為止,我還沒有找到停止錯誤的方法。
我在Google上搜索了很多,每個人都在說thread.join();。 正在等待線程結束,那么結束每半秒繪制一次簡單正方形的線程需要多長時間? 當我在播放時按下手機上的后退按鈕時,pause(); 功能完美運行。 日志“游戲已結束”出現在LogCat上。
因此,問題在於當蛇撞到牆上時,我無法停止此活動,永遠不會發生“游戲已結束”日志。 這是為什么?
我的代碼:
public class SnakeCage extends SurfaceView implements Runnable{
// blah blah .. functions that draw and stuff ..
public void pause() {
isRunning = false;
while(true){
try {
aThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
aThread = null;
Log.d("pause()","game has ended"); // <<<<<<<<<THIS ONE>>>>>>>>>
}
public void resume() {
isRunning = true;
aThread = new Thread(this);
aThread.start();
}
public void init(){
// blah blah...
}
private void gameOver() {
int pHeadX = snakeHead.posX;
int pHeadY = snakeHead.posY;
Log.d("gameOver()", "checking");
if(pHeadY<0 || pHeadX<0 || pHeadX>23 || pHeadY>19){
Log.d("gameOver()", "game now will end");
gameOver = true;
}
}
public void run() {
while (isRunning){
if(!aHolder.getSurface().isValid())
continue;
canvas = aHolder.lockCanvas();
// drawing
gameOver();
if(gameOver) break;
// more drawing
aHolder.unlockCanvasAndPost(canvas);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(gameOver){
pause();
}
}
和活動類:
public class PlayingActivity extends Activity implements OnClickListener{
SnakeCage v;
Button snakeGoUp;
Button snakeGoDown;
Button snakeGoLeft;
Button snakeGoRight;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame_layout);
v = (SnakeCage)findViewById(R.id.sView);
// listeners and stuff
}
@Override
protected void onPause() {
super.onPause();
v.pause();
}
@Override
protected void onResume() {
super.onResume();
v.resume();
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.snakeUp:
v.move(1);
break;
case R.id.snakeDown:
v.move(2);
break;
case R.id.snakeLeft:
v.move(3);
break;
case R.id.snakeRight:
v.move(4);
break;
}
}
}
我已經做了:
Context context = getContext();
((PlayingActivity)context).finish();
從:
雖然它不令我滿意...就目前而言
我建議使用LocalBroadcastManager將消息發送到Activity
,以通知它殺死自己。 您可以在Activity
有一個內部類來接收廣播,並在Activity
調用一個私有方法以結束廣播。
public class MyActivity extends Activity {
public void onCreate(Bundle state) {
LocalBroadcastManager.getInstance(this).registerReceiver(new MessageHandler(),
new IntentFilter("kill"));
}
private void killActivity() {
finish();
}
public class MessageHandler extends BroadcastReceiver {
onReceive(Context context, Intent intent) {
killActivity();
}
}
然后,在SurfaceView
您所需要做的就是:
Intent intent = new Intent("kill");
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
它的代碼多一點,但恕我直言。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.