简体   繁体   中英

FCM notification from web api c# to android

I'm developing API via c# that will send notification to specific user ( android user) , then when user open the notification I want to redirect him to specific activity.

So I needed to send data along with notification message. I've tested it using Firebase Console and it's working fine , The notification is received and my launcher activity receive the extra from data has been sent

I've also tested it from my backend and the notification is received except that my launcher intent doesn't receive any extra.

I've been struggling for hours now , Any idea would help !

this is my code from 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";
        }

    }
}

And this is my launcher activity :

@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");
    }

It looks like you have the wrong JSON: ," + "\\"data:\\"" + "{\\"mymsg\\":" + "\\"h\\" }} will be:

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

just correct your JSON. But I recommend using c# classes and serialization. Look at this simple example:

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

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

But its just example. You should create classes instead of anonym objects and using JsonProperty or another way to serialize the object. Something like that:

/// <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; }
}

with message builder which serialize your message body to correct json string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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