Push notifications in Multi-Module App

Root module

First, we need to have a root module, all modules in our application will declare this module as a dependency and will be able to access its classes and files.

Push Sender

To start with the implementation we are going to create the following 3 classes.

  • AppLifecycle: This class will help us to know if the application is in the foreground and based on that we will show the notification as a dialog or in the status bar.
  • PushNotification: This class represents the information that will arrive in the push notification in json format, then we will use it in the parsing with the Gson library.
implementation "com.google.code.gson:gson:$gson_version"
  • PushSender: This interface defines the methods that must be implemented to propagate the notifications in all the application modules.
  • PushSenderImpl: It is the implementation of the PushSender interface, in this case we will use the EventBus library to propagate notifications in all the application modules. (If you know another library that you like better, you can use it :D).
implementation "org.greenrobot:eventbus:$eventbus_version"

Push Core

Now we are going to create the class that will contain all the logic to display the notifications in the status bar or propagate them using the PushSender class that we created earlier.

The MyFirebaseMessagingService

Now we only have to create the class (service) to receive the notifications from Firebase, obtain the information from the push notification and pass it as an object to the PushCore onReceive() method.

Receiving push notifications

At this time our application can already receive push notifications and if the application is in the background, they are already shown in the status bar.

override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
open fun onPushNotification(notification: PushNotification) {
Log.d(javaClass.name, "Push notification: $notification")
}

Testing time!

To test we will go to our MainActivity, make it inherit from BaseActivity and send a push notification.

FAQ

It only works with Firebase notifications?

Github

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store