Skip to content

Instantly share code, notes, and snippets.

@matthew-carroll
Created May 18, 2014 12:05
Show Gist options
  • Save matthew-carroll/82f45b009dfd09298eb4 to your computer and use it in GitHub Desktop.
Save matthew-carroll/82f45b009dfd09298eb4 to your computer and use it in GitHub Desktop.
Introduction to Otto
/**
* BusProvider is a Singleton which provides
* app-wide access to a single Bus instance.
*/
public class BusProvider
{
private static BusProvider instance;
public BusProvider getInstance()
{
if(instance == null)
instance = new BusProvider();
return instance;
}
private Bus bus;
private BusProvider()
{
bus = new Bus(ThreadEnforcer.ANY)
}
public Bus getBus()
{
return bus;
}
}
/**
* An event object that encapsulates the location
* data we care about broadcasting.
*/
public class LocationEvent
{
private LatLng location;
public LocationEvent(LatLng location)
{
this.location = location;
}
public LatLng getLocation()
{
return location;
}
}
/**
* Pretend that this LocationService is an Android
* Service running in the background tracking changes
* in the user's location.
*/
public class LocationService extends Service
{
private Bus bus;
public void onCreate()
{
super.onCreate();
bus = BusProvider.getInstance().getBus();
}
// ... implement all the service methods needed
// ... implement location tracking behavior
// broadcasts new user locations to anyone who cares
private void broadcastNewLocation(LatLng location)
{
LocationEvent event = new LocationEvent(location);
bus.post( event );
}
}
pulic class MyActivity extends Activity
{
private Bus bus;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
bus = BusProvider.getInstance().getBus();
}
@Override
public void onStart()
{
super.onStart();
// start listening for events
bus.register(this);
}
@Override
public void onStop()
{
super.onStop();
// stop listening for events
bus.unregister(this);
}
@Subscribe
public void onLocationChange(LocationEvent event)
{
LatLng newLocation = event.getLocation();
// do whatever you want with the user's new location
// it doesn't get any easier than this to monitor a
// user's location in an Activity/Fragment
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment