How to show notifications in the background on Android.

Andrew Snyder
2 min readApr 12, 2023

--

Intro

If you’re like me, you may have faced the frustration of trying to configure notifications on Android. The Google documentation on this topic is not very helpful, and you might end up in the same situation as I did. I want to share my experience so that it can help someone else who is struggling with this issue.

Context

I am currently working on an AI Chatbot project that uses a serverless API (Azure Function) to process messages asynchronously. Once a response is generated, it sends a push notification back to the user. It’s a simple flow, but it’s critical that notifications work both when the app is open and when it’s closed.

Solution

After some trial and error, I discovered that there are two types of FCM (Firebase Cloud Messaging) messages: Notification and Data. The documentation doesn’t clearly communicate this, so it’s easy to miss. Here’s what you should use for each use-case:

App is open or in the background but still alive: Use the Data message type, which triggers your app’s “onMessageReceived” code. You can create a notification or handle it silently depending on your needs.

Example message:

{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}

App is not open in any way: Use the Notification message type, which shows the notification in the system’s notification bar. Tapping the notification will open your app’s main entry point. This will also go to “onMessageReceived” if the app is open.

Example message:

{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}

You can also mix both message types as needed for your use case.

Example message:

{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}

Conclusion

That’s all there is to it. I hope this article helps you save some time and frustration. Remember that there are two types of FCM messages, and use the appropriate type depending on whether your app is open or closed. Good luck with your projects!

--

--