Home » Android » React Native – Android – FCM – Display group notification like What's app also allowing multiple grouped notifications

React Native – Android – FCM – Display group notification like What's app also allowing multiple grouped notifications

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to display a group notification instead of multiple notifications like whatsapp does.
For eg:
One notification with message – “2 discussions 1 comment” instead of
total three notifications.

I used react-native-fcm library (https://github.com/evollu/react-native-fcm)
I used group & tag keys but couldn’t achieve the result as below code

FCM.presentLocalNotification({
  title: 'Title',
  body: 'Body',
  priority: "high",
  click_action: true,
  show_in_foreground: true,
  local: true,
  group: 'group1',
  tag: 'tag1'
});

Is it possible to achieve this functionality in react native FCM? Please let me know.

How to&Answers:

The project react-native-fcm is moved under react-native-firebase and there is a solution under this issue on the project.

The main idea:

The trick is to create an additional notification that will contain the notifications for that group.

// ID for grouping notifications, always the same
const SUMMARY_ID = `${ALERTS_GROUP}.summary`

const sendIt = (notification: Firebase.notifications.Notification) => {
  return firebase.messaging().hasPermission().then((yes) => {
    if (yes) {
      try {
        return firebase.notifications().displayNotification(notification)
          .catch((err) => {
            Log.e(`[sendNotification] ERROR: ${err}`)
            return Promise.resolve()
          })
      } catch (err) {
        Log.e('[sendNotification] Error displaying notification: ' + err)
      }
    }
    return Promise.resolve()
  })
}

const sendSummary = (data: MessageData) => {
  const summary = new firebase.notifications.Notification()
    .setNotificationId(SUMMARY_ID)
    .setTitle(_T('notification.channels.alert.description'))
    .setData(data)
    .android.setAutoCancel(true)
    .android.setCategory(firebase.notifications.Android.Category.Message)
    .android.setChannelId(getChannelId(MsgType.Alert))
    .android.setColor(variables.scheme.primaryColor)
    .android.setSmallIcon(STATUS_ICON)
    .android.setGroup(ALERTS_GROUP)
    .android.setGroupSummary(true)
    .android.setGroupAlertBehaviour(firebase.notifications.Android.GroupAlert.Children)
  sendIt(summary)
}

/**
 * Called by `bgMessaging` or the `onMessage`  handler.
 */
export function sendNotification (message: Firebase.messaging.RemoteMessage) {
  const payload: MessagePayload = message.data as any || {}
  const notification = new firebase.notifications.Notification()
  // ... more code

  if (Platform.OS === 'android' && Platform.Version >= 24) {
    notification.android.setGroup(ALERTS_GROUP)
    sendSummary(notification.data)
  }
  Log.v('[sendSummary] sending notification.')
  return sendIt(notification)
}