George Armhold
George Armhold

Reputation: 31064

Android application event handling

Is there 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)

Upvotes: 4

Views: 4159

Answers (2)

Chepech
Chepech

Reputation: 5541

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

Upvotes: 1

Fugogugo
Fugogugo

Reputation: 4480

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. :)

Upvotes: 3

Related Questions