How To Send Mobile Push Notification To Multiple Device Using Firebase Device Group

In the world of mobile application development, Push Notification plays a key role. Being a mobile developer, we all know that Firebase is the most common platform to get this done.
 

How Push Notification works

 
It’s a simple logic of sending messages to the devices based on the unique device token. The token will be unique for each device, but the token keeps on changing in some scenarios like, uninstalling and installing the app or restarting the device after clearing the app data.
 
So, what if the requirement is the app can be used by the users on multiple devices with the same login? We need to track and save the device token generated in each device for the user.
 
Fine, we got it saved in our DB. Now, to send the Push Notification for a user, do we need to send messages individually to all the devices in which he logged in? That’s a time-consuming process. So, what’s the solution?
 

Firebase Device Group

 
It is just like creating Groups in Chat applications to send a single message but deliver to all. The concept is we will just create a group where the individual device token is added as member. A separate unique token will be created for each device group which can be used as a receiver while sending Push Notifications.
 
Now to send Notifications to multiple devices of a user, you just need to send a notification to the user’s Device Token group which, in turn, sends the push notification to all the devices in the group.
 

Limitations of Firebase Device Group

 
There will always be some limitations to any concept. Here are the few limitations of Firebase Device Group.
  • A group can hold only 20 device tokens, to add more than 20 devices in a group you need to create another group.
  • If the app is uninstalled from a device, the token generated will become invalid and it will also be deleted from all the firebase device groups where it is added.
  • If all the tokens from a device group are removed, the group becomes invalid and when you try to add another device in the group you get an error message saying “notification_key not found”.

How to create a Firebase Device Group?

 
We have multiple options to do this, like using native Firebase SDK, Rest APIs. Here, we are going to see how to create a Firebase Device Group using FireBase Rest API.
 
Request Url: https://fcm.googleapis.com/fcm/notification 
 
Headers
 
Key 1: project_id
Value 1: Your_Project_Id
Key 2: Authorization
Value 3: key=Your_Firebase_key
 
Request Body
  1. {  
  2.    "operation":"create",  
  3.    "notification_key_name":"Devive_Group_name",  
  4.    "registration_ids":["Device_token_1","Device_token_2"]  
  5. }  
Response
  1. {  
  2.    "notification_key":"Unique_Device_key",  
  3. }  
Below is the sample C# code to create Firebase Device group using Rest API.
  1. public static async Task<string> createDeviceGroupFCMToken(string fcmToken, string notificationKey)  
  2.         {  
  3.             string content = string.Empty;  
  4.             HttpClient httpClient = null;  
  5.             HttpResponseMessage response = null;  
  6.   
  7.             try  
  8.             {  
  9.                 string serverApiKey = "FireBaseServerApiKey"// Get this from your Firebase Developer Console Login  
  10.                 string senderId = "FirebaseSenderId"// Get this from your Firebase Developer Console Login  
  11.                 string apiEndpoint = "https://fcm.googleapis.com/fcm/notification";  
  12.   
  13.                 using (httpClient = new HttpClient())  
  14.                 {  
  15.                     httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", (string.Format("key={0}", serverApiKey)));  
  16.                     httpClient.DefaultRequestHeaders.TryAddWithoutValidation("project_id", senderId);  
  17.   
  18.                     var dynamicPostData = new  
  19.                     {  
  20.                         operation = "create",  
  21.                         notification_key_name = notificationKey,  
  22.                         registration_ids = new List<string>() { fcmToken }  
  23.                     };  
  24.   
  25.                     response = httpClient.PostAsJsonAsync(new Uri(apiEndpoint), dynamicPostData).Result;  
  26.                     content = await response.Content.ReadAsStringAsync();  
  27.                     response.EnsureSuccessStatusCode();  
  28.   
  29.                     FCMGroupResponse resp = JsonConvert.DeserializeObject<FCMGroupResponse>(content);  
  30.                     return resp.notification_key;  
  31.                 }  
  32.             }  
  33.             catch (Exception ex)  
  34.             {  
  35.                 throw;  
  36.             }  
  37.         }  

How to add a device to a Firebase Device Group?

 
While creating a device group, we can add the devices in the group as given above. Here, we are going to see how to add a new device to the existing Firebase Device Group.
 
Request Url: https://fcm.googleapis.com/fcm/notification
 
Headers
 
Key 1: project_id
Value 1: Your_Project_Id
Key 2: Authorization
Value 3: key=Your_Firebase_key
 
Request Body
  1. {  
  2.    "operation":"add",  
  3.    "notification_key":" Unique_Device_Key_Returned_While_Creating_Group",  
  4.    "registration_ids":["Device_token_1","Device_token_2"]  
  5. }  
Below is the sample C# code to add device in an existing Firebase Device Group using Rest API.
  1. public static async Task<string> addDeviceInGroup(string fcmToken, string fcmToken1, string notificationToken)  
  2.         {  
  3.             string content = string.Empty;  
  4.             HttpClient httpClient = null;  
  5.             HttpResponseMessage response = null;  
  6.   
  7.             try  
  8.             {  
  9.                 string serverApiKey = "FireBaseServerApiKey"// Get this from your Firebase Developer Console Login  
  10.                 string senderId = "FirebaseSenderId"// Get this from your Firebase Developer Console Login  
  11.                 string apiEndpoint = "https://fcm.googleapis.com/fcm/notification";  
  12.   
  13.                 using (httpClient = new HttpClient())  
  14.                 {  
  15.                     httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", (string.Format("key={0}", serverApiKey)));  
  16.                     httpClient.DefaultRequestHeaders.Add("project_id", senderId);  
  17.   
  18.                     var dynamicPostData = new  
  19.                     {  
  20.                         operation = "add",  
  21.                         notification_key = notificationToken,  
  22.                         registration_ids = new List<string>() { fcmToken, fcmToken1 }  
  23.                     };  
  24.   
  25.                     response = httpClient.PostAsJsonAsync(new Uri(apiEndpoint), dynamicPostData).Result;  
  26.                     content = await response.Content.ReadAsStringAsync();  
  27.                     response.EnsureSuccessStatusCode();  
  28.   
  29.                     FCMGroupResponse resp = JsonConvert.DeserializeObject<FCMGroupResponse>(content);  
  30.                     return resp.notification_key;  
  31.                 }  
  32.             }  
  33.             catch (Exception ex)  
  34.             {  
  35.                  throw;  
  36.             }  
  37.         }  
I hope this article helps you to get an understanding of Firebase Device Group. If you have any questions/issues about this article, please let me know in the comments.