2012-05-16 78 views
0

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

这是SendMessage函数在服务器端功能的C#

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

回答

0

在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

可以找到