Search code examples
c#push-notificationazure-notificationhub

How is a messages sent to a specific user after it has been registred by the BackEnd using Azure Notification Hubs


The Backend code to send messages using Azure Notificaion Hub to a specific userId:

var hubClient = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);

var notification = new Dictionary<string, string> {
    { "message", "New Message" }
};

var userIdTag = "userId:12345";

await hubClient.SendTemplateNotificationAsync(notification, userTag);

Register the userId using an api that is called by the app:

var hubClient = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);

var installation = new Installation
{
    InstallationId = Guid.NewGuid().ToString(), //or use userId?
    PushChannel = deviceToken, //sent by app
    Tags = new List<string> { "userId:12345" }
};

await hubClient.CreateOrUpdateInstallationAsync(installation);

How is a message then sent to a specific userId, what work needs to be done on the Android app side in order for the message to be sent to a specific userId?


Solution

  • How is a message then sent to a specific userId, what work needs to be done on the Android app side in order for the message to be sent to a specific userId?

    Workflow:

    • Create an Android app and initialize < app request for FCM token from Firebase Cloud Messaging < By using onNewToken method in MyFirebaseMessagingService it will trigger FCM by this token will obtain < That token is sent to the backend server for registration with Azure Notification Hub < backend server receives the FCM token from the Android app < backend server uses the Azure Notification Hub SDK to register the FCM token with Azure Notification Hub < FCM token is associated with the appropriate user ID using tags < based on our Configuration we will get the success or failure of the registration process

    Firebase Messaging Service :

    import android.util.Log;
    import com.google.firebase.messaging.FirebaseMessagingService;
    import com.google.firebase.messaging.RemoteMessage;
    
    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    
        private static final String TAG = "MyFirebaseMsgService";
    
        @Override
        public void onNewToken(String token) {
            Log.d(TAG, "Refreshed token: " + token);
            // Send the token to your backend server
            sendRegistrationToServer(token);
        }
    
        private void sendRegistrationToServer(String token) {
            // Send the token to your backend server
            // This is where you would make an HTTP request to your backend API to register the token with Azure Notification Hub
            // Your backend server should handle the registration and association with the user ID
        }
    
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            // Handle incoming FCM messages here
            // You can customize the behavior based on the message payload
        }
    }
    

    AndroidManifest.xml :

    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    
    • Enable your android API for public messaging. enter image description here

    • Copy this server key to connect with the azure notification hub. enter image description here

    • Save the key as shown below. enter image description here

    Backend Code :

    class Program
    {
        private static string connectionString = "YourNotificationHubConnectionString";
        private static string hubName = "YourNotificationHubName";
    
        static async Task Main(string[] args)
        {
            string userId = "12345"; // Sample user ID
            string deviceToken = "YourDeviceToken"; // Sample device token obtained from the Android app
    
            await RegisterDeviceTokenAsync(userId, deviceToken);
    
            Console.ReadLine(); // Keep the console window open
        }
    
        static async Task RegisterDeviceTokenAsync(string userId, string deviceToken)
        {
            var hubClient = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);
    
            try
            {
                // Create or update installation for the user
                var installation = new Installation
                {
                    InstallationId = Guid.NewGuid().ToString(), // You can use InstallationId or any other identifier, such as userId
                    PushChannel = deviceToken,
                    Tags = new List<string> { $"userId:{userId}" }
                };
    
                await hubClient.CreateOrUpdateInstallationAsync(installation);
    
                Console.WriteLine("Installation created or updated successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error creating or updating installation: " + ex.Message);
            }
        }
    }
    
    • Or else you can place the device token in the above application, which we get from the android app.

    We can also send a test notification from portal to our required UserID as shown in below.

    enter image description here