Android EventBus Library Tutorial with example – continue




This Android EventBus library tutorial is next part of the this tutorial. So, please go through it before proceeding.

In previous part, we have already talked about what is EventBus library, how to do basic setup, how to use it to send simple event. We have also seen how to communicate between Fragment and Activity using simple event. In this part, We are going to talk about StickyEvent and more about this library.

Output

tutorialwing android eventbus library tutorial output

Video Output

Source Code

1. Getting Started

In this tutorial, we will learn about StickyEvent. We will see how to use stickEvent to send and receive message among different components of android application.

Note: We are going to use code of previous post into this post. So, we are assuming that you have already gone through previous post.

1.1 Sticky Event

StickyEvent is another type of event in EventBus library which holds the last value broadcasted. Suppose you have to broadcast messages “A”, “B”, “C” in this order using stickyEvent. After first time broadcasting, stickyEvent will have value “A” that will be stored in memory. Finally, stickyEvent will have value “C”. Each time stickyEvent is broadcasted, it replaces the old value with current value and store it in memory.

Let’s say, an stickyEvent is posted some time ago and an activity is started. As soon as this activity subscribes to this event(i.e. stickyEvent), it will receive already posted stickyEvent.

You can post stickyEvent as below

eventBus.postSticky(event);

Also, You can subscribe to this event as below

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void getMessage(Events.ActivityActivityMessage activityActivityMessage) {
}

1.2 How to use StickyEvent?

In this tutorial, we will see communication between Activity and Activity using stickyEvent. We are going to use MainActivity and SecondActivity for this purpose. In MainActivity, there is button which post an stickyEvent and starts SecondActivity. When we click on this button, it posts an stickyEvent (Events.ActivityActivityMessage). Then, SecondActivity is started. Note that Event is posted before the SecondActivity is started. Even if event is posted before SecondActivity starts, it will get the latest value of stickyEvent. This is the beauty of this stickyEvent. You don’t need to be subscribed when event is being posted, you will get the latest value even after the event has already been posted.

Now, it’s time to write code to perform above discussed task. Add activity i.e. SecondActivity in tutorialwing.com.eventbuslibrarytutorial package.

1.2.1 Write code in MainActivity to post stickyEvent

In activity_main.xml,
a. add code to show button which will post stickyEvent and show secondActivity.

Add following code in activity_main.xml.

<RelativeLayout
    android:id="@+id/secondActivityLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/fragmentContainer"
    android:layout_marginTop="@dimen/margin_extra_large"
    android:background="@android:color/white"
    android:padding="@dimen/padding_medium">

    <TextView
        android:id="@+id/stickyTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/margin_large"
        android:text="@string/title_stickyEvent"
        android:textStyle="bold"/>

    <Button
        android:id="@+id/showSecondActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/stickyTitle"
        android:layout_centerHorizontal="true"
        android:onClick="showSecondActivity"
        android:padding="@dimen/padding_large"
        android:text="@string/show_second_activity"/>
</RelativeLayout>

In MainActivity.java, write code to perform following actions on button click –
a. post stickyEvent.
b. start SecondActivity on button click.

Add following code in MainActivity.java

public void showSecondActivity(View view) {
	// Post an Sticky event before starting an activity to show the message,
	// sent by the MainActivity, in SecondActivity.
	Events.ActivityActivityMessage activityActivityMessageEvent =
			new Events.ActivityActivityMessage("Hello Tutorialwing");

	GlobalBus.getBus().postSticky(activityActivityMessageEvent);

	// Start SecondActivity.
	startActivity(new Intent(this, SecondActivity.class));
}

Finally, MainActivity.java and activity_main.xml class would be like below.
Final MainActivity.java code

package tutorialwing.com.eventbuslibrarytutorial;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.Subscribe;

public class MainActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		addFragment();
	}

	@Override
	protected void onStart() {
		super.onStart();
		// Register this fragment to listen to event.
		GlobalBus.getBus().register(this);
	}

	private void addFragment() {
          // Code to add fragment..already shown in previous tutorial.
	}

	public void sendMessageToFragment(View view) {
          // code to send message to fragment... Already shown in previous tutorial
     	}

	public void showSecondActivity(View view) {

		// Post an Sticky event before starting an activity to show the message,
		// sent by the MainActivity, in SecondActivity.
		Events.ActivityActivityMessage activityActivityMessageEvent =
				new Events.ActivityActivityMessage("Hello Tutorialwing");

		GlobalBus.getBus().postSticky(activityActivityMessageEvent);

		// Start SecondActivity.
		startActivity(new Intent(this, SecondActivity.class));
	}

	@Subscribe
	public void getMessage(Events.FragmentActivityMessage fragmentActivityMessage) {
          // Action to preform when event is received.. Already shown in previous tutorial
	}

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

Final activity_main.xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/margin_large"
    android:background="#cfcfcf">

    <RelativeLayout
        android:id="@+id/activityLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:padding="@dimen/padding_medium">

    <!-- Code to show simple event example shown in previous tutorial -->
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/activityLayout"
        android:layout_marginTop="@dimen/margin_extra_large"
        android:orientation="vertical">
    </LinearLayout>

    <!-- Code for stickyEvent Example START -->
    <RelativeLayout
        android:id="@+id/secondActivityLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/fragmentContainer"
        android:layout_marginTop="@dimen/margin_extra_large"
        android:background="@android:color/white"
        android:padding="@dimen/padding_medium">
        <TextView
            android:id="@+id/stickyTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/margin_large"
            android:text="@string/title_stickyEvent"
            android:textStyle="bold"/>
        <Button
            android:id="@+id/showSecondActivity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/stickyTitle"
            android:layout_centerHorizontal="true"
            android:onClick="showSecondActivity"
            android:padding="@dimen/padding_large"
            android:text="@string/show_second_activity"/>
    </RelativeLayout>
    <!-- Code for stickyEvent Example END -->
</RelativeLayout>



1.2.2 Write code to receive stickyEvent in Activity

In SecondActivity, write code to subscribe to stickyEvent and perform some action on it.
activity_second.xml

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

    <TextView
        android:id="@+id/messageReceived"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
</RelativeLayout>

SecondActivity.java

package tutorialwing.com.eventbuslibrarytutorial;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

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

public class SecondActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
	}

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

	@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
	public void getMessage(Events.ActivityActivityMessage activityActivityMessage) {
		TextView messageView = (TextView) findViewById(R.id.messageReceived);
		messageView.setText(getString(R.string.message_received) + " " + activityActivityMessage.getMessage());

		Toast.makeText(getApplicationContext(),
				getString(R.string.message_second_activity) + " " + activityActivityMessage.getMessage(),
				Toast.LENGTH_SHORT).show();
	}

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

Note that SecondActivity is registered to the EventBus in onStart method and unregistered from EventBus in onStop method. Also, it is subscribed to Events.ActivityActivityMessage. In MainActivity, we are posting this event before SecondActivity is started.

1.3 Get and Remove stickyEvent manually

If you want to get stickyEvent or remove stickyEvent, you can do it as below.
Get stickyEvent: Use EventBus.getDefault().getStickyEvent(Event.class) to get stickyEvent. You can perform action as below.

Events.ActivityActivityMessage stickyEvent = GlobalBus.getBus().getStickyEvent(Events.ActivityActivityMessage.class);
//Check if stickyEvent is actually posted or not.
if(stickyEvent != null) {
//Perform some actions.
}

Remove stickyEvent : Use EventBus.getDefault().removeStickyEvent(Event.class) to remove stickyEvent. You can perform action as below.

Events.ActivityActivityMessage stickyEvent =  GlobalBus.getBus().removeStickyEvent(Events.ActivityActivityMessage.class);
//Check if stickyEvent is actually posted or not.
if(stickyEvent != null) {
//Perform some actions.
}

1.4 Set Priorities and Event cancellation

If you want to set an order in which subscriber will receive the posted event, you need to provide priority to the subscriber during registration. For example,

@Subscribe(priority = 1);
public void onEvent1(Event event) {
//Write code to perform some action.
}

@Subscribe(priority = 0);
public void onEvent0(Event event) {
//Write code to perform some action.
}

Since priority of event1 is higher than event0, event1 will receive event before event0. Note that condition is event subscribers should be in same thread, otherwise priority doesn’t effect order of delivery.
Also, If you want to cancel the event, you can do it as below.

EventBus.getDefault().cancelEventDelivery(event);



Output

If you run the app, you will get output as shown above.

Conclusion

Android EventBus library is one of the popular android libraries which is based on publisher/subscriber pattern to communicate between different components in the application. You can use sticky event, provided by this library, to hold the last value broadcasted.

Support Us

If you have any suggestion about this post, please comment below. We are looking for someone who helps use to make our tutorial better. Also, If you want tutorials on any topic, you can mail us at tutorialwing@gmail.com. We will try to cover the topic as soon as possible. Connect with us on Facebook, Google+, Twitter and Youtube for more updates.