【问题标题】:Android C2DM send extras from server sideAndroid C2DM 从服务器端发送附加信息
【发布时间】:2012-05-16 18:45:14
【问题描述】:

如何使用 c2dm 从服务器端发送附加信息,如 userId 或 eventId,并在 onMessage() 函数中从我的 android 应用程序获取?

这是服务器端函数 C# 上的 SendMessage

private static void SendMessage(string authTokenString, string registrationId, string message)
    {
        //Certeficate was not being accepted for the sercure call
        //ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GoogleMessageUrl);
        request.Method = PostWebRequest;
        request.KeepAlive = false;

        NameValueCollection postFieldNameValue = new NameValueCollection();
        postFieldNameValue.Add(RegistrationIdParam, registrationId);
        postFieldNameValue.Add(CollapseKeyParam, "0");
        postFieldNameValue.Add(DelayWhileIdleParam, "0");
        postFieldNameValue.Add(DataPayloadParam, message);

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

        request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
        request.ContentLength = byteArray.Length;

        request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + authTokenString);

        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse response = request.GetResponse();
        HttpStatusCode responseCode = ((HttpWebResponse)response).StatusCode;
        if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
        {
            Console.WriteLine("Unauthorized - need new token");
        }
        else if (!responseCode.Equals(HttpStatusCode.OK))
        {
            Console.WriteLine("Response from web service not OK :");
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        }

        StreamReader reader = new StreamReader(response.GetResponseStream());
        string responseLine = reader.ReadLine();
        reader.Close();
    }

【问题讨论】:

    标签: android cloud device messaging android-c2dm


    【解决方案1】:

    在 c2dm 中,您可以在服务器的 data.<key> POST 字段中发送您自己的数据,例如你可以这样做:

    postFieldNameValue.Add("data.userid", theUserId);
    postFieldNameValue.Add("data.eventid", theEventId);
    

    确保您发送的字符串(theUserIdtheEventId)经过 URL 编码。

    Android 客户端可以通过onMessage(Context context, Intent intent) 方法获取数据:

    Bundle extras = intent.getExtras();
    String theUserId = extras.getString("userid");
    String theEventId = extras.getString("eventid");
    

    更深入的解释可以在这个tutorial中找到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多