I have developed an app that receives firebase push notification. Within the app there is a chat part that works within a specific ChatActivity
. The service looks like below:
class PushNotificationsService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
showPushNotification(remoteMessage)
}
}
I want not to display the push notifications in case my ChatActivity
is visible.
What is more common or better said right way to handle this case ?
I tried the following options, but not sure 100% that will work fine on production:
Check all the time ChatActivity
lifecycle via SharedPreferences
Check all the time ChatActivity
lifecycle via a static variable defined in the app Application.class
I think option 2) could work pretty well. You would simply have a boolean isChatActivityVisible
variable in your Application class and toggle that on or off depending on the activity's lifecycle.
You can also take a look at this link for further ideas: Android: how do I check if activity is running?
Later edit:
I think you could also try a different approach using a broadcast and having a broadcast receiver handle the push. Another one would be to use Greenrobot's EventBus and handle the push through it. In that case, you would register and unregister the EventBus in the onStart()/onStop() (or onPause()/onResume()) methods and send the push as a pojo. It will work as you need automatically.
First, you need to add its dependency in your build.gradle(app) file:
implementation 'org.greenrobot:eventbus:3.1.1'
You would have something like this (in ChatActivity):
override fun onResume(){
super.onResume()
EventBus.getDefault().register(this)
}
override fun onPause(){
EventBus.getDefault().unregister(this)
super.onPause()
}
And then, wherever you're receiving the push, you're going to use:
EventBus.getDefault().post(YourChatPushNotificationEvent(message))
In your case, this will be:
class PushNotificationsService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
EventBus.getDefault().post(YourChatPushNotificationEvent(remoteMessage))
}
}
where YourChatPushNotificationEvent
contains whatever payload you want to get into your ChatActivity (it's a simple pojo where you can put anything, in this case it has a String message that is passed in the constructor). If done right, I see no reason why this wouldn't work. It might add some complexity in your app as it's being developed further, but you can deal with that if you name your events properly, I guess.
To treat the event that you just emitted, you will have this in your ChatActivity:
@Subscribe(threadMode = ThreadMode.MAIN)
fun onYourChatPushNotificationEvent(event: YourChatPushNotificationEvent) {
//do whatever you need to do in here with the payload that is in the event object
}
Good luck!