使用fire base的Android通知

时间:2017-10-11 09:23:39

标签: android push-notification google-cloud-messaging

您好我正在开发webapi中的推送通知。最近我升级到了火基并使用下面的代码。

string deviceId = "dmsGj47_Ulk:APA91bEMkevJzP2_mV2ALCSc_kSTZw57gMBEP2TWtHkrPl1VGTPJYvb0Be_F0zrzsttk78wopecHT_Af3ShAU39sMku0Ht09Pz22YevWkk6hkHjjl87DEvz_7mUJ3vGc05j4n0wjfKR7";
            string message = "Demo Notification";
            string tickerText = "Patient Registration";
            string contentTitle = "Hi";
            string postData =
            "{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
              "\"data\": {\"tickerText\":\"" + tickerText + "\", " +
                         "\"contentTitle\":\"" + contentTitle + "\", " +
                         "\"message\": \"" + message + "\"}}";

            string apiKey = "";

            string response = SendGCMNotification(apiKey, postData);
            return Request.CreateResponse(HttpStatusCode.OK, "notification sent");
  private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
        {
            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
            Request.Method = "POST";
            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();
            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 e)
            {
            }
            return "error";
        }

当我运行上面的代码时,我收到错误“{\"multicast_id\":6423299842549772135,\"success\":0,\"failure\":1,\"canonical_ids\":0,\"results\":[{\"error\":\"MismatchSenderId\"}]}".https://console.firebase.google.com/project/androidnotification-17721223233/settings/general/设置选项中,有一个常规选项卡。在常规选项卡中,有Web API密钥。在云消息传递选项卡下,我可以看到服务器密钥,旧服务器密钥和发件人ID。在上面的api密码代码中,我使用了服务器密钥,旧服务器密钥和webapi密钥,但都失败了。我可以知道哪个是正确的吗?任何帮助,将不胜感激。谢谢。

    HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
    Request.Method = "POST";
    Request.ContentType = postDataContentType;
    Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
    Request.Headers.Add(string.Format("Sender: id={1}", "507022575461"));

2 个答案:

答案 0 :(得分:1)

您必须在http-header

中设置发件人ID

在云消息传递选项卡下,服务器密钥是发件人ID。

在http-header中:

'内容类型:application / json'

'授权:密钥= AAAA0 ...'< =你的密钥在这里。

将POST请求发送到此地址: https://fcm.googleapis.com/fcm/send

答案 1 :(得分:0)

错误按摩是MismatchSenderId。如果您在Android上运行此代码,则应将google-services.json放在应用程序的app文件夹中,它应该是在firebase console中为您的应用程序创建的文件夹。如果您在Android项目中有此文件,请打开它并检查senderID的值是否与您正在使用的server key的senderId相同。