2

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
    }
Sooraj
  • 133
  • 1
  • 7

2 Answers2

3

As you set the MainActivity LaunchMode = LaunchMode.SingleTop and set ActivityFlags.ClearTop,when you tap the notification to open your application,it will clear all activities above MainActivity and place MainActivity at the top of the stack. Instead of recreating MainActivity, it enters the OnNewIntent method.

You could make a breakpoint in OnCreate method,when you open the application after tap the notification,it will not step into it.

Leo Zhu
  • 15,726
  • 1
  • 7
  • 23
  • So could you please let me know, which flag or config will work here? – Sooraj May 21 '20 at 07:09
  • 1
    But in Xamarin Forms. There is only one Activity available right? – Nitha Paul May 21 '20 at 07:23
  • I tried, In my case it is again entering into the OnCreate. If the app is not open. If the app is open and present in the screen, then as you said it is not entering oncreate – Sooraj May 21 '20 at 07:25
  • @Sooraj Could you share a screen shot? Everything works fine on my side,when I set `LaunchMode = LaunchMode.SingleTop` to MainActivity, it just goes into its `OnNewIntent` method.Or you try to change the `LaunchMode` to `LaunchMode.SingleTask`,then `intent.AddFlags(ActivityFlags.NewTask);`(even though they're equivalent) – Leo Zhu May 21 '20 at 07:36
  • @NithaPaul Yes,in general,we just use one MainActivity in forms. – Leo Zhu May 21 '20 at 07:38
  • What exactly you meant by screenshot? screen snot of code or page? – Sooraj May 21 '20 at 08:03
  • @Sooraj you could record a shot video – Leo Zhu May 21 '20 at 08:10
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/214317/discussion-between-sooraj-and-leo-zhu-msft). – Sooraj May 21 '20 at 08:40
  • @Sooraj i am outside now,i will check it tomorrow. – Leo Zhu May 21 '20 at 08:42
1

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.

Rakesh R Nair
  • 1,736
  • 2
  • 12
  • 30