Search code examples
c#mauiazure-notificationhub

Editing notifications in Firebase


I would like to receive a large number of messages from firebase notificaiton and edit its content when the message is downloaded. It's mainly about the bodysuit. E.g. Content: "Hello, #Name" Then replace the #Name value.

public override void OnMessageReceived(RemoteMessage message)
{
    message.GetNotification().Body = "";
    base.OnMessageReceived(message);

    if (message.Data.TryGetValue("action", out var messageAction))
        NotificationActionService.TriggerAction(messageAction);
}

Is this possible? Maybe there is a better solution for mass notifications and you can share your experiences. Please provide code samples. Thank you and best regards.


Solution

  • When sending a data message, include a key-value pair with a placeholder in the message body, for example:

    {
      "to": "<device_token>",
      "data": {
        "title": "Greetings",
        "body": "Hello, #Name",
        "name": "John" // You can provide dynamic values for placeholders
      }
    }

    Android Client (using FirebaseMessagingService):

    public override void OnMessageReceived(RemoteMessage message)
    {
        // Ensure the message contains data payload
        if (message.Data.ContainsKey("body"))
        {
            // Get the notification body with placeholders
            string body = message.Data["body"];
    
            // Replace placeholders in the body (e.g., replace #Name with the actual name from the data)
            if (message.Data.ContainsKey("name"))
            {
                string name = message.Data["name"];
                body = body.Replace("#Name", name);
            }
    
            // Build and display the notification with the customized message body
            ShowCustomNotification(message.Data["title"], body);
        }
    
        // Trigger any additional actions if needed
        if (message.Data.TryGetValue("action", out var messageAction))
        {
            NotificationActionService.TriggerAction(messageAction);
        }
    }
    
    // Method to display the custom notification
    private void ShowCustomNotification(string title, string body)
    {
        var notificationBuilder = new NotificationCompat.Builder(this, "default_channel_id")
            .SetSmallIcon(Resource.Drawable.ic_stat_ic_notification) // Set your icon
            .SetContentTitle(title)
            .SetContentText(body)
            .SetPriority(NotificationCompat.PriorityHigh)
            .SetAutoCancel(true);
    
        var notificationManager = NotificationManagerCompat.From(this);
        notificationManager.Notify(0, notificationBuilder.Build());
    }