[英]android push notification using gcm
I am developing wcf push notification service using google's GCM API. 我正在使用Google的GCM API开发wcf推送通知服务。 i created a service which sends to all the device which use my application but, i wanted to be specific to some device. 我创建了一个服务,该服务将发送到使用我的应用程序的所有设备,但是,我想特定于某个设备。 i am thinking i have to use the token i get when i register for the GCM service. 我想我必须使用注册GCM服务时获得的令牌。 but i dont know where and how to implment it. 但是我不知道在哪里以及如何实现它。 most of the online posts are in PHP and i am kind of confused when i see the codes. 大多数在线帖子都使用PHP,当我看到代码时,我有点困惑。 Any one with C# implmentation advice or in general may be? 任何具有C#实施建议的人或一般人都可以? here is my code for all the devices: 这是我所有设备的代码:
public bool notify(string sender, string message)
{
var jGcmData = new JObject();
var jData = new JObject();
bool Value;
jData.Add("message", message);
jData.Add("name", sender);
jGcmData.Add("to", "/topics/global");
jGcmData.Add("data", jData);
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.Default, "application/json"))
.ContinueWith(response =>
{
Console.WriteLine(response);
Console.WriteLine("Message sent: check the client device notification tray.");
}));
}
Value = true;
}
catch (Exception e)
{
Console.WriteLine("Unable to send GCM message:");
Console.Error.WriteLine(e.StackTrace);
Value = false;
}
return Value;
}
thanks in advance! 提前致谢!
1st of all I think you should not reinvent the wheel and include a Push messaging library to do all the redundant work. 首先,我认为您不应该重新发明轮子,而应该包括Push消息库来完成所有多余的工作。
Then everything is cake. 那一切都是蛋糕。
Declare the following handler class Using the SendGCMNotification method just throw an object to serialize and a specific user's push messaging id . 声明以下处理程序类使用SendGCMNotification方法只是抛出要序列化的对象和特定用户的推送消息传递id。
public class PushNotificationHandler : IDisposable
{
private static readonly string googleApiKey;
private static PushBroker pushBrokerInstance;
static PushNotificationHandler()
{
googleApiKey = ConfigurationManager.AppSettings["GoogleAPIKey"].ToString();
pushBrokerInstance = new PushBroker();
pushBrokerInstance.RegisterGcmService(new GcmPushChannelSettings(googleApiKey));
}
public static void SendGCMNotification(Notification messageObj, String CloudMessagingId)
{
String Content = Newtonsoft.Json.JsonConvert.SerializeObject(messageObj);
pushBrokerInstance.QueueNotification(new GcmNotification().ForDeviceRegistrationId(CloudMessagingId).WithJson(Content));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.