Simple EventBus.getDefault().post() bring exception not main thread. How to send event from Activity to service with greenrobot event bus?
chronometer = (Chronometer)findViewById(R.id.chrono);
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer arg0) {
long countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;
String asText = (countUp / 60) + ":" + (countUp % 60);
Log.e("asText", "asText" + asText);
ChronometerEvents event=new ChronometerEvents();
event.setTime(asText);
bus.post(event);
}
});
public class ChronometerEvents {
private String time;
public ChronometerEvents() {
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
public void onEvent(ChronometerEvents freq) {
Log.e("Chronometer", "Chronometer" + freq.getTime());
}
service class
public class NewLocationUpdateService extends Service {
private EventBus bus = EventBus.getDefault();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
bus.unregister(this);
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
public void onEvent(ChronometerEvents freq) {
Log.e("Chronometer", "Chronometer" + freq.getTime());
}
}
is it posible to send using greenrobot event bus?
I would strongly recommend reconsidering your architecture here. The EventBus is not designed to cross process boundaries and the Android Services don't lend themselves easily to the idea.
The EventBus is a great tool but it is very easy to misuse.
If you want to send information from an Activity to a Service it's best to use Intent's, but if you really need some closer interaction then you should look into binding. The Eventbus should not replace these interactions.