带有AlertDialog的Looper.prepare()

时间:2012-02-02 09:28:55

标签: android android-alertdialog looper

我想在游戏中插入时间计数器。如果时间为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类是一个Thread:

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,但应用程序崩溃,并显示以下消息:只有创建视图层次结构的原始线程才能触摸视图。但这是创造的线索......问题出在哪里?

2 个答案:

答案 0 :(得分:2)

使用Handler或Use

执行此操作
this.runOnUiThread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub

        }
    });

错误本身讲述了整个故事。 如果你不在Activity / View的Parent类中,那么使用一些回调Mechnasim。 这有助于您解决问题。 欢呼声。

答案 1 :(得分:1)

根据您获得的错误判断,您将View对象从其他地方传递到Thread类构造函数,然后尝试使用它的方法来创建AlertDialog。不幸的是,这不起作用。 您需要使用Handler将消息(在您的情况下,时间= 0)从您的线程发送回View类,您已在其中定义了showTime()方法。 定义Handler,然后覆盖handleMesage()方法以调用showTime()methid。

以下链接可以帮助您入门。 http://developer.android.com/reference/android/os/Handler.html