How to Handle the Firebase Notification When App Is in Foreground

How to handle the Firebase notification when app is in foreground

When app is in foreground, notifications are not generated themselves. You need to write some additional code. When message is received onMessageReceived() method is called where you can generate the notification. Here is the code:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}

Push notification when app is in foreground (using Firebase triggers)

If depends on whether your message contains a data property, a notification property, or both.

If the message only contains a notification property, it'll delivered to your application code if the app is in the foreground, but handled by the system when the app is in the background.

If your message contains a data property, it'll always be delivered to your application code. If it also contains a notification property, that part will be handled by the system when the app is in the background.

For more on this, see the Firebase documentation on message types.

FCM handles IOS notification when app is foreground which is I do not want to

I found the solution:
It was too obvious :D

await instance.setForegroundNotificationPresentationOptions(alert: false, badge: true, sound: true);

alert parameter should be false if you do not want FCM to handle foreground alers.

Firebase notifications in the foreground

Like you said you are receiving the message since you are seeing the log messages in the console so you have handled the FCM part properly and the issue is likely with your creation of the notification.

If you look at your notification creation code you are missing a couple of the required elements to create a notification on Android. From the docs:

A Notification object must contain the following:

  • A small icon, set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()

So I think if you add those items to your notification creation you should see the notification in the notification area.

How to handle notification when app in background in Firebase

1. Why is this happening?

There are two types of messages in FCM (Firebase Cloud Messaging):

  1. Display Messages: These messages trigger the onMessageReceived() callback only when your app is in foreground
  2. Data Messages: Theses messages trigger the onMessageReceived() callback even if your app is in foreground/background/killed

NOTE: Firebase team have not developed a UI to send data-messages to
your devices, yet. You should use your server for sending this type!


2. How to?

To achieve this, you have to perform a POST request to the following URL:

POST https://fcm.googleapis.com/fcm/send

Headers

  • Key: Content-Type, Value: application/json
  • Key: Authorization, Value: key=<your-server-key>

Body using topics

{
"to": "/topics/my_topic",
"data": {
"my_custom_key": "my_custom_value",
"my_custom_key2": true
}
}

Or if you want to send it to specific devices

{
"data": {
"my_custom_key": "my_custom_value",
"my_custom_key2": true
},
"registration_ids": ["{device-token}","{device2-token}","{device3-token}"]
}


NOTE: Be sure you're not adding JSON key notification

NOTE: To get your server key, you can find it in the firebase console: Your project -> settings -> Project settings -> Cloud messaging -> Server Key

3. How to handle the push notification message?

This is how you handle the received message:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String myCustomKey = data.get("my_custom_key");

// Manage data
}

Android bring app to foreground on Firebase notification

If app is active or in background, after phone is locked it will still be considered active. So since an activity is active, it can't be thrown on top with intent since its already used to activate the activity.

We need to add window flags on an active activity to bring it to front like this:

 if (isOpened) {

focusIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

activity.startActivity(focusIntent);

// Adding Window Flags to bring app forward on lock screen

activity.runOnUiThread(new Runnable() {

@Override
public void run() {

activity.getWindow()
.addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
);

}
});

}


Related Topics



Leave a reply



Submit