首页 > 解决方案 > 使用 FCM 将通知从 Web 数据推送到移动应用程序

问题描述

因此,我已经设置了项目,甚至尝试通过添加来自云消息传递的示例通知并在我的 Android 模拟器中接收该通知来对其进行测试。

在此处输入图像描述

但是,当网络发生变化时,我需要将其推送到移动端。所以我在网上尝试了这段代码:

public void PushNotificationToFCM()
        {
            try
            {
                var applicationID = "AIzaSyDaWwl..........";
                var senderId = "487....";
                string deviceId = "1:487565223284:android:a3f0953e5fbdd790";
                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 = "sending to..",
                        title = "title-----"
                    }
                };
                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();
                                string str = sResponseFromServer;
                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                string str = ex.Message;
            }
        }

回应是:

{"multicast_id":7985385082196953522,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

请帮我。谢谢你。

标签: c#firebaseasp.net-mvc-4xamarin.androidfirebase-cloud-messaging

解决方案


我建议您查看 Nico Bonoro 在 Medium 上撰写的这篇精彩指南,该指南解释了使用 .Net 后端配置Firebase 所需的所有步骤

创建一个PushNotificationLogic.cs使用此方法调用的静态类:

SendPushNotifications在这些参数所在的位置添加一个名为的静态方法:

  • deviceTokens:字符串数组,每个字符串代表 Firebase 在每次应用安装时提供的 FCM 令牌。这将是通知要发送的应用安装列表。
  • 标题:这是通知的粗体部分。
  • body:它代表 Firebase SDK 的“消息文本”字段,这是您要发送给用户的消息。
  • 数据:有一个动态对象,它可以是任何你想要的,因为这个对象将被用作你想要发送到应用程序的附加信息,它就像隐藏信息一样。例如,当用户按下某个产品的通知或 ID 时,您想要执行的操作。

对于该方法,我将假设所有参数都是正确的,没有错误的值(您可以添加所需的所有验证)。我们要做的第一件事是创建一个对象,其中包含我们需要发送到 API 的所有数据

添加两个类,如下所示:

public class Message
{
  public string[] registration_ids { get; set; }
  public Notification notification { get; set; }
  public object data { get; set; }
}
  public class Notification
{
   public string title { get; set; }
   public string text { get; set; }
}

然后,只需创建一个“Message”类型的新对象并像我在这里所做的那样对其进行序列化:

var messageInformation = new Message()
{
   notification = new Notification()
  {
    title = title,
    text = body
  },
  data = data,
  registration_ids = deviceTokens
 };
 //Object to JSON STRUCTURE => using Newtonsoft.Json;
 string jsonMessage = JsonConvert.SerializeObject(messageInformation);

注意:您需要在项目中添加NewtonSoft.Json

现在我们只需要一个对 Firebase API 的请求,我们就完成了。该请求必须作为 Firebase API-Url 的“发布”方法,我们必须添加一个“授权”标题并使用“key={Your_Server_Key}”之类的值。然后我们添加内容(jsonMessage),您就可以使用 API。

// Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation(“Authorization”, “key=” + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, “application/json”);
HttpResponseMessage result;
using (var client = new HttpClient())
{
   result = await client.SendAsync(request);
}

万一有疑问,祝您好运随时回复。


推荐阅读