You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

55 lines
1.9 KiB

  1. using Android.App;
  2. using Android.Content;
  3. using AndroidX.Core.App;
  4. using Firebase.Messaging;
  5. using HybridApp;
  6. [Service(Exported = true)]
  7. [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
  8. public class FirebaseService : FirebaseMessagingService
  9. {
  10. public FirebaseService() { }
  11. public override void OnNewToken(string token)
  12. {
  13. base.OnNewToken(token);
  14. if (Preferences.ContainsKey("DeviceToken"))
  15. {
  16. Preferences.Remove("DeviceToken");
  17. }
  18. Preferences.Set("DeviceToken", token);
  19. }
  20. public override void OnMessageReceived(RemoteMessage message)
  21. {
  22. base.OnMessageReceived(message);
  23. var notification = message.GetNotification();
  24. SendNotification(notification.Body, notification.Title, message.Data);
  25. }
  26. private void SendNotification(string messageBody, string title, IDictionary<string, string> data)
  27. {
  28. var intent = new Intent(this, typeof(MainActivity));
  29. intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
  30. foreach (var key in data.Keys)
  31. {
  32. string value = data[key];
  33. intent.PutExtra(key, value);
  34. }
  35. var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NotificationID, intent, PendingIntentFlags.OneShot | PendingIntentFlags.Immutable);
  36. var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.Channel_ID)
  37. .SetContentTitle(title)
  38. .SetSmallIcon(HybridApp.Resource.Mipmap.appicon)
  39. .SetContentText(messageBody)
  40. .SetChannelId(MainActivity.Channel_ID)
  41. .SetContentIntent(pendingIntent)
  42. .SetAutoCancel(true)
  43. .SetPriority((int)NotificationPriority.Max);
  44. var notificationManager = NotificationManagerCompat.From(this);
  45. notificationManager.Notify(MainActivity.NotificationID, notificationBuilder.Build());
  46. }
  47. }