EventBus is third party library which is best for communication with Activities,Fragment,Thread etc. It simplifies the communication between components. It is fast and less code use.
First of all add dependencies to gradle file.
compile 'org.greenrobot:eventbus:3.0.0'
Create a simple Java Bean class
public class MyEvent {
public final String message;
public MyEvent(String message) {
this.message = message;
}
}
Implement Subscriber event handling methods. This methods will call when Event is posted. These methods are describe with @Subscribe annotation.
@Subscribe
public void onMessageEvent(MyEvent event){
Toast.makeText(this, event.message, Toast.LENGTH_SHORT).show();
}
Event is posted by post() of EventBus.
EventBus.getDefault().post(new MyEvent("MyEvent Called"));
Subscribers are need to register and unregister. Subscribers will not be called before register or after unregister.
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
Happy Coding :)
0 Comment(s)