0

我正在为 Android 编写一个小游戏。游戏是使用线程在 SurfaceView 上绘制的。在 Thread 的 run() 方法中,我测试游戏是否结束,如果是,我尝试显示游戏结束对话框,但是这给了我前面提到的错误消息。我知道当非 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;
        }

    }
}
4

4 回答 4

2

像这样尝试...除了主线程之外,您无法对 ui 进行任何更改..在if(gameOver())之后将此部分放入您的线程中

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

               BouncingBallActivity.this.showDialog(DIALOG_GAMEOVER_ID);
           }
       });
于 2012-03-27T12:07:45.907 回答
1

您正在从工作(后台)线程调用 Dialog。您需要从主线程调用它。尝试使用 Activity.runOnUIThread() 调用它并在其中创建一个处理程序,它将调用您的 showDialog 方法。

于 2012-03-27T12:04:12.407 回答
0

我使用 [ https://stackoverflow.com/a/16886486/3077964]来解决这个问题。

在 runOnUiThread() 中显示对话框后,您需要暂停 BouncingBallView 的线程。那是:

//if(gameOver()){       
BouncingBallActivity.this.runOnUiThread(new Runnable() {
 @Override
public void run() {    BouncingBallActivity.this.showDialog(DIALOG_GAMEOVER_ID);    }    });    pause();    }
于 2014-11-30T07:11:29.470 回答
0

对我来说,我在我的 surfaceView 中使用了这个处理程序来创建对话框。

Handler someHandler = new Handler(){
//this method will handle the calls from other threads. 
public void handleMessage(Message msg) {

                 final Dialog dialog = new Dialog(Game.this);

                   dialog.setContentView(R.layout.question_dialog);
                   dialog.setTitle("GAME OVER");




                   Button restart=(Button)dialog.findViewById(R.id.btn Restart);

                   // Set On ClickListener
                   restart.setOnClickListener(new View.OnClickListener() {

                       public void onClick(View v) {


                               Toast.makeText(Game.this, "Restart Game", Toast.LENGTH_LONG).show();
                               dialog.dismiss();

                           }


                       }
                   });

                   dialog.show();

             }

所以,我在游戏线程中编写了 looper.prepared() 来调用这个 Handler。如果player power = 0,就会出现这个对话框。

Looper.prepare();

 //create the message for the handler 
 Message status = someHandler.obtainMessage();
 Bundle data = new Bundle();
 String msgContent = null;
 data.putString("SOMETHING", msgContent);
 status.setData(data);
 someHandler.sendMessage(status);

 Looper.loop();

  }      
于 2015-07-27T08:46:03.340 回答