簡體   English   中英

使用gcm的android推送通知

[英]android push notification using gcm

我正在使用Google的GCM API開發wcf推送通知服務。 我創建了一個服務,該服務將發送到使用我的應用程序的所有設備,但是,我想特定於某個設備。 我想我必須使用注冊GCM服務時獲得的令牌。 但是我不知道在哪里以及如何實現它。 大多數在線帖子都使用PHP,當我看到代碼時,我有點困惑。 任何具有C#實施建議的人或一般人都可以? 這是我所有設備的代碼:

 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;
    }

提前致謝!

首先,我認為您不應該重新發明輪子,而應該包括Push消息庫來完成所有多余的工作。

我使用PushSharp

那一切都是蛋糕。

聲明以下處理程序類使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM