Abtisam Ansari
Abtisam Ansari

Reputation: 65

Send push notification to particular user in android or ios

I am successfully send push notification via firebase to all devices from server(.net C#) to android devices using given below code:

var result = "-1";
            var webAddr = "https://fcm.googleapis.com/fcm/send";
            var serverKey = "xxxxxxx";
            var senderId  = "xxxxxxx";
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "key="+ serverKey);
            httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId)); 
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string strNJson = @"{
                    ""to"": ""/topics/ServiceNow"",
                    ""data"": {
                        ""ShortDesc"": ""Some short desc"",
                        ""IncidentNo"": ""any number"",
                        ""Description"": ""detail desc""
  },
  ""notification"": {
                ""title"": "": Incident No. number"",
    ""text"": ""This is Notification"",
""sound"":""default""
  }
        }";
                streamWriter.Write(strNJson);
                streamWriter.Flush();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            return result;

Now, i want to send push notification to specific or single android device. Please help me in this regard.

Thanks.

Upvotes: 0

Views: 2340

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317828

To send a message to an individual device, you'll need to collect a device token (Android, iOS) from it. That token can then be used in they JSON payload to the FCM API. There are many examples shown here in the documentation. There is also more comprehensive documentation about the HTTP v1 API here. The token should be added to the "token" key when building the payload:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"
    }
  }
}

It looks like you're using an older API (that uses the "to" field), so I suggest moving to the new one.

Upvotes: 1

d219
d219

Reputation: 2835

It's the 'to' field that you have in the JSON string above that you'll want to populate.

You'll need to have the FCM token for each device you want to send the message to. I've only worked on the server side of this but there's further info at:

https://firebase.google.com/docs/cloud-messaging/android/first-message

Upvotes: 0

Related Questions