Search code examples
xamarin.formsxamarin.androidfirebase-notifications

Resume App from a Firebase Notification is not working (Xamarin Forms)


I am working on integrating firebase push notification to my application.

Please find my firebase FirebaseMessagingService class.

If the app is open and running everything is working fine. But if the app is not open / if I switch to some other app (my app is not closed). I am getting notification but when I tap on Notification it relaunches the app without resuming.

I am using launch mode LaunchMode = LaunchMode.SingleTop in my main activity.

And if the app is open I am getting the response in OnNewIntent override method of main activity.

Can anyone please help me to figure of the real cause. Please help.

    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class DriverAppMessagingService : FirebaseMessagingService
    {
        #region Overriden Methods

        public override void OnMessageReceived(RemoteMessage message)
        {
            base.OnMessageReceived(message);
            var parameters = new Dictionary<string, object>();
            var notification = message.GetNotification();
            if (null != notification)
            {
                if (!string.IsNullOrEmpty(notification.Body))
                {
                    parameters.Add("Body", notification.Body);
                }

                if (!string.IsNullOrEmpty(notification.BodyLocalizationKey))
                {
                    parameters.Add("BodyLocalizationKey", notification.BodyLocalizationKey);
                }

                // convert the incoming message to a local notification
                SendLocalNotification(parameters);

                // send the incoming message directly to the MainActivty
                SendNotificationToMainActivity(parameters);
            }
        }

        public override void OnNewToken(string p0)
        {
            base.OnNewToken(p0);
            //Persist the token to app settings for registration purpose.
            AppDefinition.Helpers.Settings.Current.PnsHandle = p0;
        }

        #endregion

        #region Private Methods
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        private void SendNotificationToMainActivity(Dictionary<string, object> args)
        {
            if (CrossCurrentActivity.Current.Activity is MainActivity activity)
            {
                var message = args["Body"].ToString();
                activity.TriggerPushNotification(message);
            }
        }

        /// <summary>
        /// Method to trigger the local notification.
        /// </summary>
        /// <param name="args"></param>
        private void SendLocalNotification(Dictionary<string, object> args)
        {
            //TODO Only using one token from message response.
            var message = args["Body"].ToString();

            var intent = new Intent(CrossCurrentActivity.Current.Activity, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            intent.PutExtra("message", message);

            var pendingIntent = PendingIntent.GetActivity(CrossCurrentActivity.Current.Activity, 0, intent, PendingIntentFlags.UpdateCurrent | PendingIntentFlags.OneShot);

            var notificationBuilder = new NotificationCompat.Builder(CrossCurrentActivity.Current.Activity, Constants.NotificationChannelName)
                .SetContentTitle(Constants.ContentTitle)
                .SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
                .SetContentText(message)
                .SetAutoCancel(true)
                .SetShowWhen(false)
                .SetLights(0xff0000, 100, 100)
                .SetContentIntent(pendingIntent);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                notificationBuilder.SetChannelId(Constants.NotificationChannelName);
            }
            var notificationManager = NotificationManager.FromContext(CrossCurrentActivity.Current.Activity);
            notificationManager.Notify(0, notificationBuilder.Build());
        }
        #endregion
    }

Solution

  • Data messages - Handled by the client app. These messages trigger the onMessageReceived() callback even if your app is in foreground/background/killed. When using this type of message you are the one providing the UI and handling when push notification is received on an Android device.

    {
        "data": {
            "message" : "my_custom_value",
            "other_key" : true,
            "body":"test"
         },
         "priority": "high",
         "condition": "'general' in topics"
    }
    

    Try this, this will solve your issue.