How to handle notification when app in background in Firebase

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How to handle notification when app in background in Firebase

How to Handle Notifications When App is in Background in Firebase 👋📱💬

So, you've developed an awesome app with Firebase and you're using Firebase Cloud Messaging (FCM) for sending notifications to your users. Everything works great when your app is in the foreground, but when it's in the background, the default notification shows up and your code in the onMessageReceived method doesn't get executed. 😱

Don't worry, we've got you covered! In this guide, we'll explain why this happens and provide easy solutions to ensure that your code runs even when the app is in the background. Let's get started! 🚀

The Issue 🤔

By default, when your app is in the background and a notification arrives, the system displays a notification automatically, without invoking your onMessageReceived method. This is the reason your code doesn't execute and your custom logic is not triggered.

The Solution 🎉

To make sure your code runs when the app is in the background, you'll need to handle the notification yourself and create a custom notification. Here's how you can do it:

  1. Create a new class that extends FirebaseMessagingService and override the onMessageReceived method. Let's call this class MyFirebaseMessagingService.

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    // ...
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Your code goes here
    }
}
  1. In your manifest file, register your MyFirebaseMessagingService class as the service to be used for handling the FCM messages.

<service android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
  1. Now, in your onMessageReceived method, you can handle the FCM message and create a custom notification using the NotificationCompat.Builder class.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // Get the message data
    Map<String, String> data = remoteMessage.getData();
    String title = remoteMessage.getNotification().getTitle();
    String message = remoteMessage.getNotification().getBody();
    String imageUrl = data.get("image");
    String action = data.get("action");

    // Log the received message data for debugging
    Log.i(TAG, "onMessageReceived: title : " + title);
    Log.i(TAG, "onMessageReceived: message : " + message);
    Log.i(TAG, "onMessageReceived: imageUrl : " + imageUrl);
    Log.i(TAG, "onMessageReceived: action : " + action);
    
    // Your custom logic goes here
    if (imageUrl == null) {
        sendNotification(title, message, action);
    } else {
        new BigPictureNotification(this, title, message, imageUrl, action);
    }
}
  1. Finally, implement the sendNotification method to create and display your custom notification.

private void sendNotification(String title, String message, String action) {
    // Create the notification channel (required for Android Oreo and above)
    createNotificationChannel();

    // Build the notification using NotificationCompat.Builder
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle(title)
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true);

    // Set the action for the notification, if applicable
    if (action != null) {
        Intent intent = new Intent(this, MyActivity.class);
        intent.setAction(action);
        // Set any additional intent extras, if needed
        // ...
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
    }

    // Show the notification
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notificationId, builder.build());
}

That's it! With these steps, you will be able to handle notifications when your app is in the background and have full control over the notification's appearance and behavior.

Take It to the Next Level 🚀

Now that you know how to handle notifications when the app is in the background, why not explore more advanced features of Firebase Cloud Messaging? You can customize the notification further by adding actions, using different styles (e.g., Big Picture style), or even implementing message grouping. The possibilities are endless!

Feel free to check out the official Firebase documentation for more information and examples: Firebase Cloud Messaging Documentation


We hope this guide helped you overcome the challenge of handling notifications when your app is in the background. Remember, custom notifications provide a great opportunity to enhance the user experience of your app and keep your users engaged.

If you found this guide helpful, don't forget to share it with your fellow developers. And if you have any questions or suggestions, feel free to leave a comment below. We'd love to hear from you! Happy coding! 😃👩‍💻👨‍💻

  • The [Your Tech Blog Name] Team

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my