如何通过GCM推送通知发送给更多的则1000用户 [英] How to send push notification to more then 1000 user through GCM

查看:339
本文介绍了如何通过GCM推送通知发送给更多的则1000用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用asp.net C#通过GCM发送推送通知给用户。这是我的code发送通知。

I'm using asp.net c# to send push notifications to users through GCM. This is my code to send notification.

string RegArr = string.Empty;
RegArr = string.Join("\",\"", RegistrationID);      // (RegistrationID) is Array of endpoints

string message = "some test message";
string tickerText = "example test GCM";
string contentTitle = "content title GCM";
 postData =
"{ \"registration_ids\": [ \"" + RegArr + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";

string response = SendGCMNotification("Api key", postData);

SendGCMNotification功能: -

SendGCMNotification Function:-

private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
    {

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        //  CREATE REQUEST
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
        Request.Method = "POST";
        Request.KeepAlive = false;
        Request.ContentType = postDataContentType;
        Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
        Request.ContentLength = byteArray.Length;

        Stream dataStream = Request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        //
        //  SEND MESSAGE
        try
        {
            WebResponse Response = Request.GetResponse();
            HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
            if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
            {
                var text = "Unauthorized - need new token";
            }
            else if (!ResponseCode.Equals(HttpStatusCode.OK))
            {
                var text = "Response from web service isn't OK";
            }
            StreamReader Reader = new StreamReader(Response.GetResponseStream());
            string responseLine = Reader.ReadToEnd();
            Reader.Close();

            return responseLine;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return "error";
    }

这是正常工作,正常的通知发送到1000 users.But现在我有更多然后1000个用户,我必须将通知发送给他们,但GCM文档中它被指定,我们可以在同一时间通过1000注册的id 。什么我可以做通知发送到所有用户?任何帮助将appriciated

It is working properly and notification delivered properly to 1000 users.But now i have more then 1000 users and i have to send notifications to them all,but in gcm documentation it is specified that we can pass 1000 registrations ids at one time.what can i do to send notification to all user?Any help will be appriciated

在这里输入的形象描述

推荐答案

好吧,你可能得到的异常,因为你不设置内容类型。我发现文章如何发送数据以及它改写了您的需求。你还需要安装Json.Net包

Well probably you get exception because you are not setting content type. I found article how to send data and rewrote it to your needs. You also would need to install Json.Net package

public class NotificationManager
    {
        private readonly string AppId;
        private readonly string SenderId;

        public NotificationManager(string appId, string senderId)
        {
            AppId = appId;
            SenderId = senderId;
            //
            // TODO: Add constructor logic here
            //
        }

        public void SendNotification(List<string> deviceRegIds, string tickerText, string contentTitle, string message)
        {
            var skip = 0;
            const int batchSize = 1000;
            while (skip < deviceRegIds.Count)
            {
                try
                {
                    var regIds = deviceRegIds.Skip(skip).Take(batchSize);

                    skip += batchSize;

                    WebRequest wRequest;
                    wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                    wRequest.Method = "POST";
                    wRequest.ContentType = " application/json;charset=UTF-8";
                    wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
                    wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

                    var postData = JsonConvert.SerializeObject(new
                    {
                        collapse_key = "score_update",
                        time_to_live = 108,
                        delay_while_idle = true,
                        data = new
                        {
                            tickerText,
                            contentTitle,
                            message
                        },
                        registration_ids = regIds
                    });

                    var bytes = Encoding.UTF8.GetBytes(postData);
                    wRequest.ContentLength = bytes.Length;

                    var stream = wRequest.GetRequestStream();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();

                    var wResponse = wRequest.GetResponse();

                    stream = wResponse.GetResponseStream();

                    var reader = new StreamReader(stream);

                    var response = reader.ReadToEnd();

                    var httpResponse = (HttpWebResponse) wResponse;
                    var status = httpResponse.StatusCode.ToString();

                    reader.Close();
                    stream.Close();
                    wResponse.Close();

                    //TODO check status
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

然后就可以调用方法

Then you can call method

 var notificationManager = new NotificationManager("AppId", "SenderId");
 notificationManager.SendNotification(Enumerable.Repeat("test", 1010).ToList(), "tickerText", "contentTitle", "message");

这篇关于如何通过GCM推送通知发送给更多的则1000用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆