Firebase onMessageReceived not called when app in background

CodingWithTashi
3 min readMar 20, 2021

Pushing notification to your application is not as difficult as we thought.With firebase it is few minute of work and you are good to go.

Firebase push notification with foreground and background kotlin
Photo by Jamie Street on Unsplash

Hello guys, My name is Tashi and In this shitty post we will see how to push notification in your application with onMessageReceived called in both foreground and background.

There are different way to send notification such as

a)Notification messages

b)Data messages

c)Messages with both notification and data payloads

We will use data messages as it is the only way to called onMessageReceived method in foreground,background or killed.

Lets get start

  1. I won’t waste your time creating new application and connecting with firebase rather we will go straight to push notification.
  2. First things is to add firebase dependency in your application

go to->tool->firebase->cloud messaging and click on add fcm

3. Now that it is connected Subcribe to topic so that we can send notification to any group or all the device base on topic. I will send notification to all device and to do that. all application should subcribe to yopic called “all’’

I have created application class and create topic called “all ” and subscribe to it. PrayerApp.kt

4.Now that we set the topic,We will send data such as title,body and description from postman later to this topic .

When we send this message to this topic, our application will listen to this topic and onMessageReceived will get called . For that Create new class for firebase messaging service as MessagingService.kt

Now that we have handle message and display notification from this sevice class. lets update in AndroidManifest.xml too.

5. Update AndroidManifest.kt

That all, now run the application and wait for the notification.

Now to trigger notification get API from your firebase console and open postman and update as below. Make sure you have data since this is data message.

Enter firebase pushnotification url: https://fcm.googleapis.com/fcm/send

Also update Header as below. to get Authorization key firebase console and add “key=” as prefix.

Now click on send button and you shoud get the output by now whether application is in foreground, background or killed.

If you noticed now onMessageReceived method will also called no matter what your application state is.

That all,Thanks guys, I hope you like this shitty blog. please make sure to give clap 👏 and leave some engagement. let me know in comment section if you face any issue.

Checkout more blog from CodingWithTashi. Follow me on twitter or Instagram or YouTube.

--

--