1

这是我第一次制作安卓游戏。游戏通过 SurfaceView 运行。

这是 SurfaceView

public class GameView extends SurfaceView implements SurfaceHolder.Callback
{
    private GameThread game_thread;

    public GameView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        SurfaceHolder sh = getHolder();
        sh.addCallback(this);
        setFocusable(true);

        game_thread = new GameThread(sh, context, new Handler());
    }

    public void surfaceCreated(SurfaceHolder holder)
    {
        game_thread.start();
    }

    public void surfaceDestroyed(SurfaceHolder holder)
    {
        game_thread.stop();
    }
}

运行游戏的线程是这样的。

public class GameThread extends Thread
{
    public GameThread(SurfaceHolder sh_arg, Context c, Handler h)
    {
        sh = sh_arg;
        context = c;
    }

    @Overide
    public void run()
    {
        super.run();
        while(!dead)
        {
            // Update here
        }
        // Game Over. Start another activity from here to show player score.
    }
}

到目前为止,我设法让它开始另一个活动的唯一方法是在循环之后添加它。

context.startActivity(new Intent(context, GameOver.class));

活动确实开始并显示,但冻结并导致 ANR。

我猜从线程开始活动并不是一个好主意,并且有更好的替代方法。

4

2 回答 2

0

When you instantiate and start the thread, you do it from the main thread, which also the UI thread. With that, you have a UI thread and a background thread. Now, when you want to launch another UI thread (by starting another activity) from the second thread, because you already have another Activity with the UI thread, you get problem. You can't have two Activities running at the same time.

于 2013-02-20T14:55:05.423 回答
0

尝试使用

    ((Activity)context).runOnUiThread(new Runnable(){

    public void run()
    {
    context.startActivity(new Intent(context, GameOver.class));
    } 
    });
于 2013-09-02T17:20:17.143 回答