This post will show how one can make an API call and send a notification to an Android device.
The code below requires 2 keys for authentication, the SERVER_KEY_TOKEN and SENDER_ID can be retrieved via Firebase’s developer console. One can find those in Project Overview (click Cog icon) / Users and Permissions / Cloud Messaging tab.
The deviceId that is passed as parameter is an id of the Android phone and can be obtained via the application.
public string SendNotificationJSON(string deviceId, string title, string body, string click_action) { string SERVER_KEY_TOKEN = "SERVER_KEY_TOKEN"; var SENDER_ID = "SENDER_ID"; WebRequest tRequest; tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = " application/json"; tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_KEY_TOKEN)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID)); var a = new { notification = new { title, body, icon = "https://domain/path/to/logo.png", click_action, sound = "mySound" }, to = deviceId }; byte[] byteArray = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(a)); tRequest.ContentLength = byteArray.Length; Stream dataStream = tRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse tResponse = tRequest.GetResponse(); dataStream = tResponse.GetResponseStream(); StreamReader tReader = new StreamReader(dataStream); string sResponseFromServer = tReader.ReadToEnd(); tReader.Close(); dataStream.Close(); tResponse.Close(); return sResponseFromServer; }
Additional Resources
- This link provides a good overview on the Firebase APIs. Pretty useful to quickly find what functionality is available https://medium.com/@selvaganesh93/firebase-cloud-messaging-important-rest-apis-be79260022b5
- This SO question has many similar yet good answers on the same topic https://stackoverflow.com/questions/37412963/send-push-to-android-by-c-sharp-using-fcm-firebase-cloud-messaging
1. it’s void why you have return?
2.how can get deviceId ?
3.if we want send to all device what we should to do?
Hi Ehsan,
Thank you for noticing, I updated the function’s signature.
The device id is retrieved by the Android application, when the user enables the push notifications.