2 ssummeraw ssummeraw 于 2013.04.15 10:00 提问

Can't create handler inside thread has not called Looper.prepare() 错误

我在android环境下创建一个小游戏。这个游戏使用一个线程绘制在一个SurfaceView 上面。在线程的run()方法中,我测试看游戏是否结束,如果游戏结束就显示游戏结束对话框,但是却给出“Can't create handler inside thread has not called Looper.prepare()”的错误消息。我觉得是当一个非UI线程试图去介入UI线程的时候,发生了错误。有什么好的方法可以显示这样的一个游戏结束对话框?
贴出我的代码:

public class BouncingBallActivity extends Activity{

    private static final int DIALOG_GAMEOVER_ID = 0;
    private BouncingBallView bouncingBallView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bouncingBallView = new BouncingBallView(this);
        bouncingBallView.resume();
        setContentView(bouncingBallView);
    }

    protected Dialog onCreateDialog(int id)
    {
        switch (id) {
        case DIALOG_GAMEOVER_ID:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Game Over.")
                    .setCancelable(false)
                    .setPositiveButton("Try Again",
                            new DialogInterface.OnClickListener()
                                {

                                public void onClick(DialogInterface arg0,
                                        int arg1)
                                {
                                    bouncingBallView.resume();

                                }
                            })
                    .setNegativeButton("Exit",
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog,
                                        int which)
                                {
                                    BouncingBallActivity.this.finish();

                                }
                            });

            AlertDialog gameOverDialog = builder.create();
            return gameOverDialog;
        default:
            return null;
        }


    }


    class BouncingBallView extends SurfaceView implements Runnable
    {
        SurfaceHolder   surfaceViewHolder;
        Canvas          canvas;
        Context         context;
        Thread          drawingThread;

        boolean         drawingThreadIsRunning;
        boolean         isInitialised;

        Ball            ball;
        ArtificialIntelligence ai;

        BouncingBallView(Context context)
        {
            //
        }

        public void pause()
        {
            isInitialised = false;
            drawingThreadIsRunning = false;
            boolean joiningWasSuccessful = false;

            while(!joiningWasSuccessful)
            try {
                drawingThread.join();
                joiningWasSuccessful = true;
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        public void resume()
        {
            isInitialised = false;
            drawingThread = new Thread(this);

            drawingThread.setName("Drawing Thread");
            drawingThreadIsRunning = true;
            drawingThread.start();

        }

        public void run()
        {
            while(drawingThreadIsRunning)
            {
                if(!surfaceViewHolder.getSurface().isValid())
                    continue;

                if(gameOver())
                    BouncingBallActivity.this.showDialog(DIALOG_GAMEOVER_ID);

                try{
                    canvas = surfaceViewHolder.lockCanvas();
                    if(!isInitialised)init(canvas);
                    update();
                    surfaceViewHolder.unlockCanvasAndPost(canvas);
                }catch(Exception e)
                {
                    Log.e(BouncingBallActivity.this.toString(),String.format("%s: Just as the emperor had foreseen!\n(This error is expected. Canvas destroyed while animations continue.)", e.toString()));
                }
            }
        }

        private void init(Canvas canvas)
        {
            ball = new Ball(canvas, Color.GREEN);
            ai   = new ArtificialIntelligence(canvas, (int) (ball.getX()+100),canvas.getWidth());

            isInitialised = true;
        }

    }
}

1个回答

nana4ever
nana4ever   2013.04.15 15:20

除了主线程,在别的线程中不能做任何改变。在 if(gameOver()) 方法后把下面的代码放在你的线程中

//if(gameOver())
 runOnUiThread(new Runnable() {
           @Override
           public void run() {

               BouncingBallActivity.this.showDialog(DIALOG_GAMEOVER_ID);
           }
       });
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!