Service to Activity Data Transfer using EventBus

Dr. Vipin Kumar
4 min readOct 5, 2021

What is EventBus?

EventBus is an open-source library for Android using Java and Kotlin for based on loose coupling pattern. EventBus enables or provides central communication to decoupled classes with just a few lines of code — simplifying the code, removing dependencies, and speeding up app development.

Figure 1: EventBus Event Lifecycle

Advantages of using EventBus:

  1. It’s simplifies the communication between activity to service, service to activity, fragment to activity, activity to fragment and etc.
  2. It uses to decouples event senders and receivers
  3. It works perfect with UI artifacts (e.g. Activities, Fragments) and background threads
  4. It avoids complex and error-prone dependencies and life cycle issues
  5. It is very fast; specifically optimized for high performance
  6. It is tiny only (~60k jar)
  7. Already, 1,000,000,000+ app using EventBus
  8. It also has advanced features like delivery threads, subscriber priorities, etc.

EventBus Features:

  1. Convenient Annotation based API: Simply put the @Subscribe annotation to your subscriber methods.
  2. Android main thread delivery: EventBus interacting with the UI, and can deliver events in the main thread regardless how an event was posted.
  3. Background thread delivery: If you have long running tasks, EventBus can also use background threads to avoid UI blocking.
  4. Event & Subscriber inheritance: In EventBus, the object oriented paradigm applies to event and subscriber classes.
  5. Jump start: You can get started immediately — without the need to configure anything
  6. Configurable: To tweak EventBus to your requirements, you can adjust its behaviour using the builder pattern.

Adding EventBus to your project:

For understanding EventBus working, I am taking example of Firebase Cloud Messaging. Here I am sending message from Firebase Console under Firebase Cloud Messaging. This message will be received by Google FCM Service: FirebaseMessagingService (Explain in Step 4). With the help of EventBus this message will be send to MainActivity. In MainActivity, this message will be display in TextView using EventFunction execute by EventBus.Let’s us understand it by prober example:

Step 1:

Add line below in module level Gradle File, so that it can be added in android app:

implementation ‘org.greenrobot:eventbus:3.2.0’

Step 2:

Now, we have to do setting for register, un-register and event handler function declaration for EventBus in your Activity or Service class. Here I am doing in MainActivity File

Method Declaration:

This method will execute when data will be send by service to activity, this method will execute in MAIN thread of activity, but you can also subscribe for other mode like background thread mode:

@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)fun onEvent(event:MessageEvent) {    binding.message=event}Register EventBus:Registering EventBus in onStart() functions.override fun onStart() {    super.onStart()    EventBus.getDefault().register(this)}Un-Register EventBus:Un-registering EventBus in onStop() functions.override fun onStop() {    super.onStop()    EventBus.getDefault().unregister(this)}Let’s is the complete code of MainActivity:

class MainActivity : AppCompatActivity() {
lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= DataBindingUtil.setContentView(this,R.layout.activity_main)
EventBus.getDefault().register(
this)
binding.lifecycleOwner=this
binding
.message= MessageEvent(“this is msg”)
}

@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
fun onEvent(event:MessageEvent) {
binding.message=event

}

override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(
this)
}
}

Step 3:In step 3rd, I am creating data class for exchanging data between activity and service. Service will post message in Data Class and Activity will receive this Data Class object to display in TextView.Data Class:data class MessageEvent(val msg:String)Step 4:Sending Data to Activity and Passing Data:In this part, I created subclass FCMToken inherited with FirebaseMessagingService class to fire notification when message received from Firebase Cloud Messaging server. In this class, I have called post method to send message to MainActivity with the help of EventBus library post method.Calling of EventBus post method:EventBus.getDefault().post(MessageEvent(it.body.toString()))

I have to register FCMToken service in Manifest file also. Here is the registration of this class in Manifest file.

Registering FCM Service in Manifest file:

<service
android:name=”.FCMToken”
android:exported=”true”
>>
<
intent-filter>
<
action android:name=”com.google.firebase.MESSAGING_EVENT”/>
</
intent-filter>
</
service>

Coding of FCMToken Class:

Finally, here is the coding of Firebase Service class FCMToken. In this service class, I called post method of EventBus to send message to MainActivity.

class FCMToken : FirebaseMessagingService() {
override fun onNewToken(s: String) {
super.onNewToken(s)
Log.e(
“FCM”, s)
}

override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
if (remoteMessage.data.isNotEmpty()) {
Log.d(
“FCM”, “Message data payload: ${remoteMessage.data}”)

}

// Check if message contains a notification payload.
remoteMessage.notification?.let
{
Log.d(“FCM”, “Message Notification Body: ${it.body}”)
EventBus.getDefault().post(MessageEvent(
it.body.toString()))
}

}
}

Step 5:

In this final step, I am sending message from Firebase Cloud Messaging at Firebase Console to specific android application based on Token ID generated from FCM or package name:

Figure 2: Firebase Cloud Messaging Image for Sending Message

Now click on test button to send message to specific android device. At last insert Token ID and click on Test button to send message to specific android device at have same Token ID inserted by you.

Figure 3: Image of Sending Message to Specific Device of Token ID Inserted

For information watch my video on my YouTube channel: Dr. Vipin Classes. Link given below:

And have source code of this app at GitHub link given below:

https://github.com/DrVipinKumar/Android-Kotlin

--

--

Dr. Vipin Kumar

Assoc. Prof. , DCA & Assoc. Head (SD), SDFS, at KIET, PhD (CS) My YouTube Channel: Dr. Vipin Classes (https://www.youtube.com/channel/UC-77P2ONqHrW7h5r6MAqgSQ)