我想在游戏中插入一个计时器。如果时间为 0,则会有一个 AlertDialog 告诉用户时间已到,并返回到上一个 Activity。这是方法(它在扩展 SurfaceView 的类中):
public void showTime(){
time--;
Log.i("GameView time", "" + time);
if (time <= 0){
Log.i("gameview time","time out");
gameTimer.setRunning(false);
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this.getContext());
AlertDialog alert = alt_bld.create();
alert.setTitle("Time is out. You lose.");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
main.onBackPressed();
}});
alert.show();
}
}
GameTimer 类是一个线程:
public class GameTimer extends Thread{
private GameView gameView;
private boolean run;
public GameTimer(GameView gameView){
this.gameView = gameView;
}
public void setRunning(boolean value){
this.run = value;
}
public void run(){
Looper.prepare();
while (run){
try {
gameView.showTime();
sleep(1000);
} catch (Exception e){
e.printStackTrace();
}
}
Looper.loop();
}
}
出现 AlertDialog,但应用程序崩溃,并显示以下消息:只有创建视图层次结构的原始线程才能触摸视图。但这是创建的线程......问题出在哪里?