Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use EventBus in Android

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 324
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: