我正在使用 Google 示例项目来推送通知,我已经成功地构建和部署了客户端和服务器应用程序,并且我能够在服务器端注册设备,当我尝试发送通知时,它显示消息已被推送但我没有在设备或模拟器上收到通知。
客户端应用程序使用 IDE eclipse 编译和部署,示例服务器应用程序由 ANT 构建器构建并部署在 Tomcat 7 中。
我正在使用 Android 4.2 Google API 模拟器和带有 gmail 配置的设备。
最佳答案
在本文中,我将尝试解释如何使用 ASP.NET 和 C# 为 Android 集成推送通知服务。众所周知,移动应用是蓬勃发展的市场趋势。一些自定义移动应用程序使用推送通知服务向应用程序用户提供更新。在这里,我将解释我们如何使用 Google 的 GCM 推送通知服务。
类文件“AndroidGCMPushNotification.cs”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Collections.Specialized;
public class AndroidGCMPushNotification
{
public AndroidGCMPushNotification()
{
//
// TODO: Add constructor logic here
//
}
public string SendNotification(string deviceId, string message)
{
string GoogleAppID = "google application id";
var SENDER_ID = "9999999999";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
}
您可以通过传递设备 ID 和消息来调用 SendNotification 函数。
AndroidGCMPushNotification apnGCM = new AndroidGCMPushNotification();
string strResponse =
apnGCM.SendNotification("123123xxxxxxxxxxxxxxxxxxxxxxxx",
"Test Push Notification message ");
关于android - Android 中的 GCM 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14258205/