为了从控制台应用程序向Android设备发送通知,我使用以下代码:
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选项卡中我获得了Server Key和Sender Id(在代码中它们是applicationId和senderId)。我还从我下载到手机的应用程序中获取了设备ID,它在Android设备ID标签下给了我一个字符串。
但是我收到消息错误:InvalidRegistration。
我对此很陌生,我想我错过了一些东西。
提前谢谢。
答案 0 :(得分:1)
error:InvalidRegistration
表示deviceId(也称为注册令牌)错误。
检查传递给服务器的注册令牌的格式。 确保它与客户端应用程序收到的注册令牌相匹配 从注册Firebase通知。不要截断或添加 其他角色。
https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
检查您是否正在阅读正确的令牌:
FirebaseInstanceId.getInstance().getToken()