繁体   English   中英

从Web API C#到Android的FCM通知

[英]FCM notification from web api c# to android

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

因此,我需要与通知消息一起发送数据。 我已经使用Firebase Console对其进行了测试,并且工作正常,已经收到通知,并且我的启动器活动已接收到来自数据的额外信息

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

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

这是我的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");
    }

看起来您输入了错误的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字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM