0

Android用の小さなゲームを書いています。ゲームは Thread を使用して SurfaceView に描画されます。スレッドの 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

ワーカー(バックグラウンド)スレッドからダイアログを呼び出しています。メインスレッドからこれを呼び出す必要があります。Activity.runOnUIThread() を使用して呼び出してみて、その中にハンドラーを作成します。これにより、showDialog メソッドが呼び出されます。

于 2012-03-27T12:04:12.407 に答える
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();

             }

そこで、この Handler を呼び出すために looper.prepared() をゲーム スレッドに記述します。プレイヤーのパワー = 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 に答える
0

[ https://stackoverflow.com/a/16886486/3077964]を使用して問題を解決しました。

runOnUiThread() 内でダイアログを表示した後、BounceBallView のスレッドを一時停止する必要があります。あれは:

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