Search code examples
androidfirebasexamarinonesignalandroid-syncadapter

Xamarin receive a push message that trigger action, without notification


I'm creating a Xamarin (android) app that I want to receive a push message and trigger a update in the application, not show a notification.

I first tested the OneSignal like this:

            OneSignal.Current.StartInit("xxx")
            .HandleNotificationReceived(HandleNotificationReceived)
            .EndInit();

The HandleNotificationReceived() is received and I can use the text received for triggering my own functions. But I'm not able to stop the notification to show. Is that possible?

Onesignal might be to "special" in this case, not to handle such case, but I am not bound to it.

Will it be solvable using Xamarin.Firebase.Messaging (followed this guide: https://blog.xamarin.com/implementing-push-notifications-android-apps/ )?

I could not get rid of the notification there either.

After thinking for alternativesan alarm trigged in a interval could solve it, but https://developer.android.com/training/scheduling/alarms did not recommend it at all. Use syncadapter was their solution, but I have not found any good examples showing it in action for Xamarin.

Thanks in advance for your help! :)


Solution

  • You can trigger notification received action without displaying notification using OneSignal.

    In your OneSignal notification handler class :

    Set Infocus displaying value to OSInFocusDisplayOption.None

    .InFocusDisplaying(OSInFocusDisplayOption.None)
    

    Check my code for reference :

    public void InitializeOneSignalService()
            {
                OneSignal.Current.SetLogLevel(LOG_LEVEL.NONE, LOG_LEVEL.NONE);
                SetRequiresConsent(false);
    
                OneSignal.Current.StartInit("Your OneSignal Key").Settings(new Dictionary<string, bool>() {})
                .InFocusDisplaying(OSInFocusDisplayOption.None) //This line will stop displaying notification
    
                  .HandleNotificationOpened((result) =>
                  {
    
                  })
                  .HandleNotificationReceived((notification) =>
                  {
    
                  })
                  .EndInit();
    
            } 
    

    Now send notification from OneSignal you will receive notification callback on .HandleNotificationReceived without displaying notification.