开发者

Android application event handling

Is th开发者_JS百科ere a standard set of Listener/Observer/Observable classes in Android for managing application events in Android?

I'm not talking about UI or other Android API events, but rather custom app events like GameOverEvent, LevelClearedEvent, etc.

Is there a preferred interface to implement/extend so that I can implement things like:

public void addGameOverListener(GameOverListener listener)


It's easy,, you just need to create your own EventListener

public interface onGameFinishedListener {

    public void onGameFinished(GameView gameView);

}

and some class which has onGameFinished() method

public abstract class GameView extends SurfaceView implements SurfaceHolder.Callback{

    List<onGameFinishedListener> listeners;
    public GameThread gameThread;
    protected int width;
    protected int height;
    public GameView(Context context) {
        super(context);
        width = 320;
        height = 480;
        listeners = new ArrayList<onGameFinishedListener>();
    }

    public abstract void init();
    public void registerGameFinishedListener(onGameFinishedListener listener) {
        listeners.add(listener);
    }
    protected void GameFinished(GameView gameView) {
        for (onGameFinishedListener listener : listeners) {
            synchronized(gameThread.getSurfaceHolder()) {
                listener.onGameFinished(gameView);
            }
        }
    }
}

and then you implement the onGameFinishedListener in your activity or view which you want to do operation when the game finish,

public class RocketActivity extends GameActivity implements onGameFinishedListener {

private final int MENU = 0;
private final int END = 1;
private final int CONFIRMATION = 2;
private RelativeLayout layout;
private RocketView rocketView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    layout = new RelativeLayout(this);
    rocketView = new RocketView(this);

    rocketView.registerGameFinishedListener(this);
    rocketView.init();
    layout.addView(rocketView);
    setContentView(layout);
}

@Override
public void onGameFinished(GameView gameView) {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            showDialog(END);
        }
    });
}

}

there. no need to rely on Android for EventListener. :)


Have you tried EventBus by GreenRobot?

It is basically a pretty standard implementation of an eventBus for handling application wide events. It provides inter-thread communication which is quite neat.

Pretty similar to what you get for GWT

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜