Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 29  Broadcast Intents


For the More Curious: Local Events


Broadcast intents allow you to propagate information across the system in a global fashion. What if
you want to broadcast the occurrence of an event within your app’s process only? Using an event bus is
a great alternative.


An event bus operates on the idea of having a shared bus, or stream of data, that components within
your application can subscribe to. When an event is posted to the bus, subscribed components will be
activated and have their callback code executed.


EventBus by greenrobot is a third-party event bus library we use in our Android applications. Other
alternatives to consider include Square’s Otto, which is another event bus implementation, or using
RxJava Subjects and Observables to simulate an event bus.


Android does provide a local way to send broadcast intents, called LocalBroadcastManager. But we
find that the third-party libraries mentioned here provide a more flexible and easier-to-use API for
broadcasting local events.


Using EventBus


To use EventBus in your application, you must add a library dependency to your project. Once the
dependency is set up, you define a class representing an event (you can add fields to the event if you
need to pass data along):


public class NewFriendAddedEvent { }


You can post to the bus from just about anywhere in your app:


EventBus eventBus = EventBus.getDefault();
eventBus.post(new NewFriendAddedEvent());


Other parts of your app can subscribe to receive events by first registering to listen on the bus. Often
you will register and unregister activities or fragments in corresponding lifecycle methods, such as
onStart(...) and onStop(...):


// In some fragment or activity...
private EventBus mEventBus;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEventBus = EventBus.getDefault();
}


@Override
public void onStart() {
super.onStart();
mEventBus.register(this);
}


@Override
public void onStop() {
super.onStop();
mEventBus.unregister(this);
}

Free download pdf