Skip to content

Instantly share code, notes, and snippets.

@Haosvit
Created July 13, 2016 04:58
Show Gist options
  • Select an option

  • Save Haosvit/922fdd9286ac177baab879b19745e805 to your computer and use it in GitHub Desktop.

Select an option

Save Haosvit/922fdd9286ac177baab879b19745e805 to your computer and use it in GitHub Desktop.
public void PushNotification(string title, string message, string topic)
{
if ((title == null) || (message == null) || (topic == null))
{
return;
}
var jGcmData = new JObject();
jGcmData.Add("to", topic);
var jDataNotification = new JObject();
jDataNotification.Add("title", title);
jDataNotification.Add("body", message);
jGcmData.Add("content_available", true);
jGcmData.Add("priority", "high");
jGcmData.Add("notification", jDataNotification);
SendToGCM(jGcmData);
}
private static void SendToGCM(JObject jGcmData)
{
var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation(
"Authorization", "key=" + API_KEY);
Task.WaitAll(client.PostAsync(url,
new StringContent(jGcmData.ToString(), Encoding.UTF8, "application/json"))
.ContinueWith(response =>
{
Console.WriteLine(response);
Console.WriteLine("Message sent: check the client device notification tray.");
}));
}
}
catch (Exception e)
{
Console.WriteLine("Unable to send GCM message:");
Console.Error.WriteLine(e.StackTrace);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment