Send push to Android by C# using FCM (Firebase Cloud Messaging)

Send push to Android by C# using FCM (Firebase Cloud Messaging)

To send a push notification to an Android device using FCM (Firebase Cloud Messaging) in C#, you can use the Firebase Admin SDK for .NET.

Here's an example:

// Install the FirebaseAdmin nuget package
// Add the Google.Apis.Auth nuget package for authentication

using Google.Apis.Auth.OAuth2;
using Google.Apis.FirebaseCloudMessaging.v1;
using Google.Apis.FirebaseCloudMessaging.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Threading.Tasks;

public async Task SendPushNotificationAsync(string token, string title, string message)
{
    // Load the credentials from a service account key file
    var credential = GoogleCredential.FromFile("path/to/serviceAccountKey.json");
    var channel = new Grpc.Core.Channel(FirebaseMessagingClient.DefaultEndpoint.Host,
                                        credential.ToChannelCredentials());

    // Create the Firebase Cloud Messaging client
    var client = new FirebaseMessagingClientBuilder()
        .Channel(channel)
        .Build();

    // Create the notification message
    var notification = new Notification()
    {
        Title = title,
        Body = message
    };

    // Create the Android-specific payload
    var data = JObject.FromObject(new
    {
        title = title,
        message = message
    });

    // Create the message request
    var messageRequest = new SendMessageRequest()
    {
        Target = new AndroidTarget()
        {
            Token = token
        },
        Notification = notification,
        Data = data
    };

    // Send the message and wait for the response
    var response = await client.Projects.Messages.Send(messageRequest).ExecuteAsync();

    Console.WriteLine($"Message ID: {response.MessageId}");
}

In this example, we first load the credentials for the Firebase project using a service account key file. We then create a FirebaseMessagingClient using the credentials and the endpoint URL for the Firebase Cloud Messaging service.

We create a Notification object to set the title and body of the push notification, and a JObject to create the Android-specific payload for the notification.

We then create a SendMessageRequest object to specify the target device token, the notification, and the payload data.

Finally, we call the Send() method of the FirebaseMessagingClient to send the message and wait for the response, which contains the message ID.

Note that you'll need to replace the values of token, title, and message with your own values, and provide the path to your service account key file.

Also note that you'll need to have the appropriate permissions and settings in your Firebase project to send push notifications to Android devices using FCM.

Examples

  1. "C# Firebase Cloud Messaging (FCM) send push notification to Android"

    • Description: Learn how to send a push notification to Android devices using C# and Firebase Cloud Messaging (FCM). This example demonstrates the basic setup and usage of FCM.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmPushSender
    {
        public void SendPushNotification(string registrationToken, string title, string body)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendPushNotification method in this code sends a push notification to the specified Android device using FCM. Ensure you replace "path/to/your/serviceAccountKey.json" with the actual path to your Firebase service account key.

  2. "C# FCM send push notification with data payload to Android"

    • Description: Explore how to send a push notification with a data payload to Android devices using C# and FCM. This example demonstrates including custom data in the push notification.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmDataPushSender
    {
        public void SendDataPushNotification(string registrationToken, string title, string body, string customDataKey, string customDataValue)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
                Data = new System.Collections.Generic.Dictionary<string, string>
                {
                    { customDataKey, customDataValue },
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendDataPushNotification method in this code sends a push notification with custom data to the specified Android device using FCM.

  3. "C# FCM send push notification with image to Android"

    • Description: Learn how to send a push notification with an image to Android devices using C# and FCM. This example demonstrates attaching an image to the push notification.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmImagePushSender
    {
        public void SendImagePushNotification(string registrationToken, string title, string body, string imageUrl)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
                Android = new AndroidConfig
                {
                    Notification = new AndroidNotification
                    {
                        ImageUrl = imageUrl,
                    },
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendImagePushNotification method in this code sends a push notification with an image to the specified Android device using FCM.

  4. "C# FCM send push notification with click action to Android"

    • Description: Explore how to send a push notification with a click action to Android devices using C# and FCM. This example demonstrates specifying a click action for the push notification.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmClickActionPushSender
    {
        public void SendClickActionPushNotification(string registrationToken, string title, string body, string clickAction)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
                Android = new AndroidConfig
                {
                    Notification = new AndroidNotification
                    {
                        ClickAction = clickAction,
                    },
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendClickActionPushNotification method in this code sends a push notification with a specified click action to the specified Android device using FCM.

  5. "C# FCM send push notification with sound to Android"

    • Description: Learn how to send a push notification with a custom sound to Android devices using C# and FCM. This example demonstrates including a sound in the push notification.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmSoundPushSender
    {
        public void SendSoundPushNotification(string registrationToken, string title, string body, string sound)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
                Android = new AndroidConfig
                {
                    Notification = new AndroidNotification
                    {
                        Sound = sound,
                    },
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendSoundPushNotification method in this code sends a push notification with a specified sound to the specified Android device using FCM.

  6. "C# FCM send push notification with priority to Android"

    • Description: Explore how to send a push notification with priority to Android devices using C# and FCM. This example demonstrates setting the priority of the push notification.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmPriorityPushSender
    {
        public void SendPriorityPushNotification(string registrationToken, string title, string body, Priority priority)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
                Android = new AndroidConfig
                {
                    Priority = priority,
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendPriorityPushNotification method in this code sends a push notification with a specified priority to the specified Android device using FCM.

  7. "C# FCM send push notification with collapse key to Android"

    • Description: Learn how to send a push notification with a collapse key to Android devices using C# and FCM. This example demonstrates using a collapse key for grouping notifications.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmCollapseKeyPushSender
    {
        public void SendCollapseKeyPushNotification(string registrationToken, string title, string body, string collapseKey)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
                Android = new AndroidConfig
                {
                    CollapseKey = collapseKey,
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendCollapseKeyPushNotification method in this code sends a push notification with a specified collapse key to the specified Android device using FCM.

  8. "C# FCM send push notification with time-to-live to Android"

    • Description: Explore how to send a push notification with a time-to-live (TTL) value to Android devices using C# and FCM. This example demonstrates setting the TTL for the push notification.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmTtlPushSender
    {
        public void SendTtlPushNotification(string registrationToken, string title, string body, TimeSpan timeToLive)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
                Android = new AndroidConfig
                {
                    TimeToLive = (int)timeToLive.TotalSeconds,
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendTtlPushNotification method in this code sends a push notification with a specified time-to-live (TTL) value to the specified Android device using FCM.

  9. "C# FCM send push notification with custom data to Android"

    • Description: Learn how to send a push notification with custom data to Android devices using C# and FCM. This example demonstrates including additional custom data in the push notification.
    using System;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmCustomDataPushSender
    {
        public void SendCustomDataPushNotification(string registrationToken, string title, string body, string customDataKey, string customDataValue)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var message = new Message()
            {
                Token = registrationToken,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
                Data = new System.Collections.Generic.Dictionary<string, string>
                {
                    { customDataKey, customDataValue },
                },
            };
    
            FirebaseMessaging.DefaultInstance.SendAsync(message).GetAwaiter().GetResult();
        }
    }
    

    The SendCustomDataPushNotification method in this code sends a push notification with additional custom data to the specified Android device using FCM.

  10. "C# FCM send push notification to multiple Android devices"

    • Description: Explore how to send a push notification to multiple Android devices using C# and FCM. This example demonstrates sending a push notification to a list of registration tokens.
    using System;
    using System.Collections.Generic;
    using FirebaseAdmin;
    using FirebaseAdmin.Messaging;
    using Google.Apis.Auth.OAuth2;
    
    public class FcmMultiDevicePushSender
    {
        public void SendMultiDevicePushNotification(List<string> registrationTokens, string title, string body)
        {
            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile("path/to/your/serviceAccountKey.json"),
            });
    
            var messages = registrationTokens.Select(token => new Message()
            {
                Token = token,
                Notification = new Notification
                {
                    Title = title,
                    Body = body,
                },
            }).ToList();
    
            FirebaseMessaging.DefaultInstance.SendAllAsync(messages).GetAwaiter().GetResult();
        }
    }
    

    The SendMultiDevicePushNotification method in this code sends a push notification to multiple Android devices using a list of registration tokens with FCM. Replace "path/to/your/serviceAccountKey.json" with the actual path to your Firebase service account key.


More Tags

shiny-server biometrics qdialog file-location android-sharedpreferences react-hooks android-radiobutton jtable digital-signature command-prompt

More C# Questions

More Transportation Calculators

More Entertainment Anecdotes Calculators

More Biochemistry Calculators

More Chemical thermodynamics Calculators