【问题标题】:FCM notification from web api c# to android从 web api c# 到 android 的 FCM 通知
【发布时间】:2019-12-20 11:00:52
【问题描述】:

我正在通过 c# 开发 API,它将向特定用户(android 用户)发送通知,然后当用户打开通知时我想将他重定向到特定活动。

所以我需要连同通知消息一起发送数据。我已经使用 Firebase 控制台对其进行了测试,它工作正常,收到通知并且我的启动器活动从已发送的数据中接收到额外的数据

我还从我的后端对其进行了测试,并收到了通知,只是我的启动器意图没有收到任何额外信息。

我已经挣扎了好几个小时了,任何想法都会有所帮助!

这是我的 c# 代码

        public String getNotification ()
    {
        string serverKey = "xxxx";
        var result = "-1";

        try
        {
            var webAddr = "https://fcm.googleapis.com/fcm/send";
            var regID = "xxxx"; 

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add("Authorization:key=" + serverKey);
            httpWebRequest.Method = "POST";


            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {




                string json = "{\"to\": \"" + regID +
                    "\",\"notification\": {\"title\": \"Testing\",\"body\": \"Hi Testing\"}" +
                       "," + "\"data:\"" + "{\"mymsg\":" + "\"h\" }}";



                streamWriter.Write(json);
                streamWriter.Flush();
            }


            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }

            return result;
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            return "Can't Send";
        }

    }
}

这是我的启动器活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.d("test" , "in main");

    if (getIntent().getStringExtra("mymsg") != null) {
        Log.d("test" , "has extra");
        Intent intent = new Intent(this, Main2Activity.class);
        startActivity(intent);
        finish();
    } else {
        Log.d("test" , "no extra");
    }

【问题讨论】:

  • @JakeB 我不能像这样将它存储在字符串值中
  • 您能否在您的 Android 应用中第一次收到来自 firebase 的消息的位置发布代码。

标签: c# android api web-services push-notification


【解决方案1】:

您的 JSON 格式似乎有误: ," + "\"data:\"" + "{\"mymsg\":" + "\"h\" }} 将是:

"data:" {
  "mymsg":"h"
}

只需更正您的 JSON。但我建议使用 c# 类和序列化。看这个简单的例子:

var payload = new {
    to = "XXXX",
    notification = new
    {
        body = "Test",
        title = "Test"
    },
    data = new {
      mymsg = "h"
    }
  }

// Using Newtonsoft.Json
string postbody = JsonConvert.SerializeObject(payload).ToString();

但这只是一个例子。您应该创建类而不是匿名对象,并使用 JsonProperty 或其他方式来序列化对象。类似的东西:

/// <summary>
/// Data for sending push-messages.
/// </summary>
public class PushData
{
  /// <summary>
  /// [IOS] Displaying message
  /// </summary>
  [JsonProperty("alert")]
  public Alert Alert { get; set; }

  /// <summary>
  /// [IOS] badge value (can accept string representaion of number or "Increment")
  /// </summary>
  [JsonProperty("badge")]
  public Int32? Badge { get; set; }

  /// <summary>
  /// [IOS] The name of sound to play
  /// </summary>
  [JsonProperty("sound")]
  public String Sound { get; set; }

  /// <summary>
  /// [IOS>=7] Content to download in background
  /// </summary>
  /// <remarks>
  /// Set 1 for silent mode
  /// </remarks>
  [JsonProperty("content-available")]
  public Int32? ContentAvailable { get; set; }

  /// <summary>
  /// [IOS>=8] Category of interactive push with additional actions
  /// </summary>
  [JsonProperty("category")]
  public String Category { get; set; }

  /// <summary>
  /// [Android] Used for collapsing some messages with same collapse_key
  /// </summary>
  [JsonProperty(PropertyName = "collapse_key")]
  public String CollapseKey { get; set; }

  /// <summary>
  /// [Android] This parameter specifies how long (in seconds) the message should be kept in GCM storage if the device is offline. 
  /// The maximum time to live supported is 4 weeks, and the default value is 4 weeks.
  /// </summary>
  /// <value>
  /// Time_to_live value of 0 means messages that can't be delivered immediately will be discarded
  /// </value>
  [JsonProperty("time_to_live")]
  public Int32 TimeToLive { get; set; }

  /// <summary>
  ///  [Android] Uri of activity to open when push activated by user
  /// </summary>
  [JsonProperty("url")]
  public String Url { get; set; }

  /// <summary>
  /// Payload for push
  /// </summary>
  [JsonProperty("data")]
  public Payload Payload { get; set; }
}

使用消息生成器序列化您的消息正文以更正 json 字符串。

【讨论】:

  • 天啊!你真的拯救了我的一天!我试过了,它的工作!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 2017-07-01
  • 1970-01-01
  • 2017-01-12
  • 2017-02-03
  • 1970-01-01
  • 2019-08-07
相关资源
最近更新 更多