0

我想在 android 线程中执行检查以检查另一个类中方法的返回值。到目前为止,这是我的代码:

public class HelloWorldAndroid extends AndroidApplication {

    private MyGame myGame;

@Override
public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

            **********Other lines Omitted***********

    myGame = new MyGame(false, 30, new AndroidLeaderboard());


            //check to see if the game is over
    Thread background = new Thread(new Runnable() {

        @Override
        public void run() {
            if (myGame.gameOver()) {


                //if the game is over go to another screen
                startActivity(new Intent(HelloWorldAndroid.this, MainActivity.class));

            }
        }

    });
            background.start();
      }

我试图用一个处理程序来实现它,但它只是不执行检查,所以当值为 true 时它仍然运行。有谁知道我如何myGame.gameOver() = true在这个线程的整个运行过程中连续执行检查(这样我就可以继续进行不同的活动)。

几天来一直在绞尽脑汁,但仍然一无所获:S 欢迎任何想法。

4

2 回答 2

4

为什么不创建某种侦听器(接口)?

小而基本的例子,

myGame = new MyGame(false, 30, new AndroidLeaderboard());
myGame.setGameOverListener(this);

注意:您不需要setGameOverListener方法,也可以将构造函数更改为具有侦听器参数。

侦听器将如下所示:

interface GameOverListener {
    abstract public void notifyGameOver();
}

并在您的 MyGame 对象中创建一个方法:

setGameOverListener(GameOverListener gol){
    this.gol = gol;
}

您的 Activity 将实现该侦听器,并在该notifyGameOver()方法中打开该 Activity。

像这样:

public void notifyGameOver(){
    startActivity(new Intent(HelloWorldAndroid.this, MainActivity.class));
}

要通知您的游戏结束,只需让您的 MyGame 对象调用该notifyGameOver()方法:

gol.notifyGameOver();
于 2012-10-17T19:17:40.207 回答
3

这对我来说似乎是非常糟糕的设计。相反,我建议创建一个OnGameOverListener具有一种方法的接口,onGameOver(). 该类MyGame具有客户端可以设置的此接口的实例。然后,当MyGame班级决定游戏结束时,它可以调用onGameOver()

观察者模式

于 2012-10-17T19:17:25.263 回答