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:
Create a new class that extends
FirebaseMessagingService
and override theonMessageReceived
method. Let's call this classMyFirebaseMessagingService
.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
// ...
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Your code goes here
}
}
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>
Now, in your
onMessageReceived
method, you can handle the FCM message and create a custom notification using theNotificationCompat.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);
}
}
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.
