Azure / azure-notificationhubs-xamarin

Azure Notification Hubs Sample for Xamarin Forms
MIT License
35 stars 23 forks source link

OnPushNotificationReceived method not hit when app in background #58

Open wesoos opened 3 years ago

wesoos commented 3 years ago

Hello, when my android app is in background, the OnPushNotificationReceived method is never hit. I am receiving the notification, and it's displayed in task tray using the default notification channel. However we need to be able to intercept the notification data for further processing.

I'm am using the latest version of everything.
Windows 10 Visual Studio

public class AzureListener : Java.Lang.Object, INotificationListener
    {
        public void OnPushNotificationReceived(Context context, INotificationMessage message)
        {
            var intent = new Intent(context, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID);

            notificationBuilder.SetContentTitle("aaa:::" + message.Title)
                        .SetSmallIcon(Resource.Drawable.ic_launcher)
                        .SetContentText(message.Body)
                        .SetAutoCancel(true)
                        .SetShowWhen(false)
                        .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManager.FromContext(context);

            notificationManager.Notify(0, notificationBuilder.Build());
        }
wesoos commented 3 years ago

Update, I read in another closed issue that if the app is in the background, and the notification is clicked in the task tray, the intent should have the data payload as extras in the intent. However this is not working. My extras is always null, in OnNewIntent and OnCreate.

{
    "notification":{
        "title":"Notification Hub Test Notification",
        "body":"This is a sample notification delivered by Azure Notification Hubs."
    },
    "data":{
        "property1":"value1",
        "property2":42
    }
}
MelissaW990 commented 3 years ago

Hello, can you try these two methods in your Azure Listener Class:

`void INotificationListener.OnPushNotificationReceived(Context context, INotificationMessage message) { string messageBody = string.Empty; string title = string.Empty; long serialNumber = 0;

        if (!string.IsNullOrEmpty(message.Body))
        {
            messageBody = message.Body;
        }
        else
        {
            try
            {
                if (message.Data.ContainsKey("message"))
                    messageBody = message.Data["message"];

                if (message.Data.ContainsKey("title"))
                    title = message.Data["title"];

                if (message.Data.ContainsKey("serialNumber"))
                    serialNumber = Convert.ToInt64(message.Data["serialNumber"]);
            }
            catch (Exception ex)
            {
                //Crashes.TrackError(ex);
            }
        }

        SendLocalNotification(context, messageBody, title, serialNumber);
    }`

`private void SendLocalNotification(Context context, string messageBody, string title, long serialNumber) { Intent intent = new Intent(context, typeof(MainActivity)); intent.AddFlags(ActivityFlags.ClearTop); intent.PutExtra("body", messageBody); intent.PutExtra("title", title); intent.PutExtra("serialNumber", serialNumber.ToString());

        PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NotificationHubConstants.NotificationChannelName)
            .SetContentTitle(title)
            .SetSmallIcon(Resource.Drawable.logo)
            .SetContentText(messageBody)
            .SetAutoCancel(true)
            .SetShowWhen(false)
            .SetContentIntent(pendingIntent);

        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            notificationBuilder.SetChannelId(NotificationHubConstants.NotificationChannelName);

        NotificationManager notificationManager = NotificationManager.FromContext(context);
        notificationManager.Notify(0, notificationBuilder.Build());
    }`

And then in MainActivity set the 'Launch Mode' to 'LaunchMode.SingleTop' and add this method in the class:

protected async override void OnNewIntent(Intent intent) { if (intent.Extras != null) { long serialNumber = Convert.ToInt64(intent.GetStringExtra("serialNumber")); //Do Whatever With Serial Number } base.OnNewIntent(intent); }

Also, I use a data only push notification: {"data":{"title":"My App", "message": "Hello Android User", "serialNumber" : "50505050"}}

Hope this helps.

MelissaW990 commented 3 years ago

Can you also share how you are creating your push notification channel, even though the documentation doesn't say you have to, I have found myself creating it manually or else the notification doesn't appear in the tray at all.

wesoos commented 3 years ago

Thanks Melissa,

I have sorted out the Android side of things. You have to do data only object in the notification to be able to intercept it in the background as well.

As for iOS, I'm receiving when app is in foreground, but not in background. Are you able to intercept in background? Also can you share how you display the notifications in iOS?

Thanks

MelissaW990 commented 3 years ago

No worries, are you able to receive push notifications on Android when the app has been swiped closed? This is something I cannot get to work at all.

On iOS make sure you have the background modes enabled: Remote notifications and background processing.

Also make sure you are sending notifications like this : { "aps" : { "alert" : { "title" : "Hello User", "body" : "This is a push notification", }, "content-available" : 1, "category" : "customPush", "sound" : "default" } }

wesoos commented 3 years ago

Hi Melissa,

Thank you. I got it working now. It's something in that payload that causes background notifications to work. One thing though, when in background mode, it displays the notification separate and in parallel also goes into DidReceivePushNotification override. Is that expected or have you figured something out there?

I have not looked into notifications not working when swiped closed. Will let you know when I do...

MelissaW990 commented 3 years ago

Glad you got sorted. I think that is the expected behaviour.

no worries, thank you!