How to use Event bus on Android

0
20

Android EventBus is a tiny Android library that allows on publisher/subscriber pattern to communicate between different components in the application. In this example, we will learn how to use Event bus on Android.

Download Project – EventBusDemo

Download Apk – Apk

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Creating New Project – EventBusEdemo

Open your Android Studio & create a new Project, have taken Blank Activity for this project and clicked finish.

Pre-Requisites

To add Event bus you have to add dependencies to build.gradle file

compile 'org.greenrobot:eventbus:3.0.0'

Add the above code and sync the project.

Creating Layout

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <EditText
            android:id="@+id/firsttxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:inputType="textPersonName" />

    <Button
        android:id="@+id/firstbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="37dp"
        android:text="Show"
        android:layout_below="@+id/firsttxt"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/first"
        android:textSize="20dp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/firstbtn"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="42dp"
        android:text="" />
</RelativeLayout>

This xml file contains one button one textview and one edittext.

Message.java

public class Message {
    private String message;
    public Message(String message){
        this.message = message;
    }
    public String getMessage(){
        return message;
    }
}

We need to create a class which is broadcasted when needed.This java class used for communication between components. This above code uses for sent message and receives messages.

Related:

Handle on touch event on Google-Map in Android

Android Motion Sensor using SensorManager and SensorEventListener

Handle Multiple Geofencing in Common Areas in google map in android application

Creating MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {
    EditText txt;
    Button btn;
    TextView tv;

    EventBus eventBus = EventBus.getDefault();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (EditText)findViewById(R.id.firsttxt);
        tv = (TextView)findViewById(R.id.first);
        btn = (Button)findViewById(R.id.firstbtn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                eventBus.post(new Message(txt.getText().toString()));
            }
        });
    }
     @Subscribe(threadMode = ThreadMode.MAIN)
     public void PostEvent(Message message){
        tv.setText(message.getMessage());
     }

    @Override
    protected void onStart() {
        super.onStart();
        eventBus.register(this);
    }

    @Override
    protected void onStop() {
        eventBus.unregister(this);
        super.onStop();
    }
}

using EventBus.getDefault() we add event Eventbus on our project.

 eventBus.post(new Message(txt.getText().toString()))

Here we are used post method with the help of Message.java class.

eventBus.register(this);
 eventBus.unregister(this);

We need to register Android EventBus for this activity when the activity starts and when the activity stop or pause we need to unregister event bus for this activity.

@Subscribe(threadMode = ThreadMode.MAIN)
     public void PostEvent(Message message){
        tv.setText(message.getMessage());
     }

We need to define a subscriber that will receive the message so we add above code. This is a Subscriber message so we are used @Subscribe

Conclusion
In this Project, you saw how to use Android EventBus Library.I hope you will understand the method. In the case of any queries, you may ask questions. Keep following more amazing Android Blogs. If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

LEAVE A REPLY

Please enter your comment!
Please enter your name here