OneSignal / OneSignal-Xamarin-SDK

OneSignal is a free push notification service for mobile apps. This plugin makes it easy to integrate your Xamarin app with OneSignal. https://onesignal.com
Other
105 stars 50 forks source link

Android: How to receive Notifications when App was closed (swiped away) #85

Closed ArgusMagnus closed 6 years ago

ArgusMagnus commented 6 years ago

Can you please provide help/an example on how I can still receive notifications even after the app was closed (swiped away) by the user? I do get the notification in the android notification shade, but I need to get my hands on the additional data in the app logic.

I tried to follow the instructions on https://documentation.onesignal.com/docs/android-customizations#section-background-data-and-notification-overriding which works fine as long as the app is running (either in focus or in the background) but it does not help with receiving the data when the app was closed.

This is the NotificationExtenderService I have so far:

/// <summary>
/// Necessary to receive background notifications:
/// https://documentation.onesignal.com/docs/android-customizations#section-background-data-and-notification-overriding
/// </summary>
[Service(Permission = "android.permission.BIND_JOB_SERVICE", Exported = false)]
[IntentFilter(actions: new[] { "com.onesignal.NotificationExtender" })]
public sealed class OneSignalNotificationExtenderService : Com.OneSignal.Android.NotificationExtenderService
{
    protected override bool OnNotificationProcessing(OSNotificationReceivedResult p0)
    {
        var notification = Com.OneSignal.NotificationOpenedHandler.OSNotificationToNative(new OSNotification() { Payload = p0.Payload });
        App.ReceiveNotification(notification).Wait();
        //return false;
        DisplayNotification(new OverrideSettings() { Extender = new Extender() });
        return true;
    }

    protected override void OnHandleIntent(Intent intent)
    {
    }

    sealed class Extender : Java.Lang.Object, NotificationCompat.IExtender
    {
        const int AA = unchecked((int)0xFF000000);
        static Random rand = new Random();
        public NotificationCompat.Builder Extend(NotificationCompat.Builder builder)
        {
            return builder
                .SetContentTitle("Extender")
                .SetColor(AA | rand.Next(0xFFFFFF));
        }
    }
}

From the Color and the title which is only changed if the app is running I conclude that the extender service is not running as expected.

(On a side note: The source notes that the NotificationExtenderService should be a JobIntentService instead of a IntentService but that it wouldn't compile. It seems to compile for me if a change it (maybe this is due to a new Xamarin version?). Could this be related?)

ArgusMagnus commented 6 years ago

I was wrong, this is related to some threading issue which causes an exception in App.ReceiveNotification(notification)