ゲーム内にタイムカウンターを入れたいのですが。時間が0の場合、時間切れであることをユーザーに通知し、前のアクティビティに戻るAlertDialogがあります。メソッドは次のとおりです(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が表示されますが、アプリがクラッシュし、次のメッセージが表示されます。ビュー階層を作成した元のスレッドのみがビューにアクセスできます。しかし、これは作成したスレッドです...問題はどこにありますか?