I try to use Otto. I think it works so far but I receive the events twice.
This is what I have (I followed the example on GitHub):
The producer:
public class NetworkChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, final Intent intent)
{
Log.i("ralphs", "onReceive");
// .... more stuff
final Bus bus = TRaumfeldApp.getInstance().getBus();
bus.register(this);
bus.post(new NetworkChangeEvent());
bus.unregister(this);
}
@Produce
public NetworkChangeEvent produceAnswer()
{
Log.i("ralphs", "produceAnswer");
return new NetworkChangeEvent();
}
}
The Subscriber:
public class MainActivity extends ActionBarActivity
{
private Bus mBus;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// otto event bus
mBus = TRaumfeldApp.getInstance().getBus();
}
@Override
protected void onResume()
{
super.onResume();
mBus.register(this);
}
@Override
protected void onPause()
{
super.onPause();
mBus.unregister(this);
}
@Subscribe
public void answerAvailable(NetworkChangeEvent event)
{
Log.i("ralphs", "answerAvailable");
}
}
The log locks like this:
I/ralphs﹕ onReceive
I/ralphs﹕ produceAnswer
I/ralphs﹕ answerAvailable
I/ralphs﹕ answerAvailable
Why I receive the events twice?
When your subscriber registers, it gets the first event from the
@Produce
-annotated method if an object with such methods is registered. The second event is from the explicitpost()
operation.You don't need to register in order to post but you do need it for the
@Produce
annotation.