Intro to Android

Lab: Getting on the bus

In the last lab, we posted an event to a bus. Now let's do something with it.

Registering the bus

To start listening for Otto events we need to register. In CalculatorActivity, we register the bus in onResume():

@Override
public void onResume()
{
    super.onResume();
    Log.d( TAG, "onResume()" );
    getBus().register( this );
}

protected Bus getBus()
{
    return CalculatorApplication.getInstance().getBus();
}

And deregister in onPause():

@Override
protected void onPause()
{
    super.onPause();
    Log.d( TAG, "onPause()" );
    getBus().unregister( this );
}

Reacting to an event

If your component is interested in a particular bus event, subscribe for that event type. Let's add this subscription to CalculatorActivity and move the Toast from ButtonFragment here instead. When you run this, you should still see the same behavior.

/**
 * Handles the selection of a number.
 *
 * @param event - number entered
 */
@Subscribe
public void onNumberSelected( NumberButtonEvent event )
{
    Toast.makeText( this,
                    "Clicked: " + event.getNumber(),
                    Toast.LENGTH_SHORT )
         .show();
}