I have the following code. When a push notification is clicked on by the user while the app is in the background or closed, MainActivity.OnNewIntent is called but the intent is missing the extras that were put in when processing the push notification. If the app is in the foreground when the notification is clicked, the intent parameter has the extras and is properly handled.
[Service]
[IntentFilter(new[] {"com.google.firebase.MESSAGING_EVENT"})]
[IntentFilter(new[] {"com.google.firebase.INSTANCE_ID_EVENT"})]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
public override void OnMessageReceived(RemoteMessage message)
{
var intent = new Intent(this, typeof(MainActivity));
intent.PutExtra("source", "notification");
intent.PutExtra("title", message.GetNotification()?.Title ?? "");
intent.PutExtra("body", message.GetNotification()?.Body ?? "");
foreach (var extra in message.Data)
{
intent.PutExtra(extra.Key, extra.Value);
}
string category = "Miscellaneous";
if (message.Data.ContainsKey("category")
&& !string.IsNullOrWhiteSpace(message.Data["category"]))
{
category = message.Data["category"];
}
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, category);
notificationBuilder.SetContentTitle(message.GetNotification()?.Title)
.SetSmallIcon(Resource.Drawable.notificationicon)
.SetContentText(message.GetNotification()?.Body)
.SetAutoCancel(true)
.SetShowWhen(false)
.SetPriority(1)
.SetContentIntent(pendingIntent)
.SetCategory(category)
.SetChannelId(category);
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
}
And my MainActivity's OnNewIntent method looks like:
protected override async void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
if (intent.Extras != null
&& intent.Extras.ContainsKey("source")
&& "notification".Equals((string)intent.Extras.Get("source")))
{
this.GetLog().Info("Houston, we have liftoff!");
}
}
When the push notification is clicked by the user when the app is open, we hit the log message. When clicked by the user when the app is closed or in the background, it is not hit because intent.Extras is null. I can't find any articles or questions that help. Thoughts?
UPDATE:
How to handle notification when app in background in Firebase
This question got me partway there. By removing the notification object in the json when the message is sent from the server, I can now process the notification when the app is in the background. But still not when it is closed altogether.