2

We are using App Center Push Notification and according to the following article https://learn.microsoft.com/en-us/appcenter/sdk/push/xamarin-forms, push notifications can be handled in App.xaml.cs with the use of Push.PushNotificationReceived.

This is actually working ATM, and the method is actually triggered for both background and foreground notifications.

We need to be able to distinguish them. We navigate the user to a specific part of the app whenever they tap on the notification (background) and we can't do the same if the app is already opened (foreground).

I've seen some ways of accomplishing that but they were all specific to the platform (iOS in this case). Is there a way to do the same in the PCL?

DAlvarenga
  • 36
  • 5

1 Answers1

3

I think Xamarin Forms doesn't give an api for us to get the App's state.

You can achieve this by use DependencyService in Xamarin.Forms:

First define a Interface in your PCL project:

public interface IGetAppState
{
    bool appIsInBackground();
}

In iOS:

[assembly: Dependency(typeof(GETAppState_iOS))]

namespace App129.iOS
{
    public class GETAppState_iOS : IGetAppState
    {
        public bool appIsInBackground()
        {
            UIApplicationState state = UIApplication.SharedApplication.ApplicationState;
            bool result = (state == UIApplicationState.Background);

            return result;
        }
    }
}

In Android:

[assembly: Dependency(typeof(GETAppState_Android))]

namespace App129.Droid
{
    public class GETAppState_Android : IGetAppState
    {
        public bool appIsInBackground()
        {
            bool isInBackground;

            RunningAppProcessInfo myProcess = new RunningAppProcessInfo();
            GetMyMemoryState(myProcess);
            isInBackground = myProcess.Importance != Importance.Foreground;

            return isInBackground;
        }
    }
}

And at anywhere you want to know if your app is in background or foreground, you can use:

bool isInBackground = DependencyService.Get<IGetAppState>().appIsInBackground();
nevermore
  • 15,432
  • 1
  • 12
  • 30
  • 1
    Thanks for the answer Jack, but unfortunately this is not helping. Once the notification is received, we tap on it and the app opens, the appIsInBackground() is always coming back as false. – DAlvarenga Dec 28 '18 at 19:20
  • @DAlvarenga how did you solve this? You're right, it will always be a foreground handling. – TPG Jul 08 '19 at 08:25