【发布时间】:2017-02-26 09:59:57
【问题描述】:
为了从控制台应用程序向安卓设备发送通知,我使用以下代码:
class Program
{
static void Main(string[] args)
{
string applicationId = "applicationId";
string senderId = "senderId";
string deviceId = "deviceId";
string message = "TestMessage";
var x = new AndroidFCMPushNotificationStatus();
var response = x.SendNotification(applicationId, senderId, deviceId, message);
Console.WriteLine(response);
Console.ReadLine();
}
}
和
public class AndroidFCMPushNotificationStatus
{
public string SendNotification(string applicationID, string senderId, string deviceId, string message)
{
try
{
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = deviceId,
notification = new
{
body = message,
title = message,
},
priority = "high"
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
string sResponseFromServer = tReader.ReadToEnd();
return (sResponseFromServer);
}
}
}
}
catch (Exception ex)
{
return (ex.Message);
}
}
}
我创建了一个 firebase 控制台项目,从项目设置中,从选项卡 Cloud Messaging 我得到了服务器密钥和发件人 ID(在代码中它们是 applicationId 和 senderId)。我还从我下载到手机的应用程序中获取了我的设备 ID,它在标签 Android 设备 ID 下给了我一个字符串。
但是我收到消息错误:InvalidRegistration。
我对此很陌生,我想我错过了一些东西。
- 上面的代码应该可以工作吗?每当我运行程序时,我都会在手机上收到通知?
- 我应该做些什么来允许此通知发送到我的手机吗?我没有在我的设备上配置任何东西。
- 这个想法是将此代码打包到服务中,每当服务器上发生某些事情时,我想使用此代码来通知 我的设备。这是正确的方法吗?
提前谢谢你。
【问题讨论】:
标签: c# android firebase firebase-cloud-messaging