App Center Push

App Center Push enables you to send push notifications to users of your app from the App Center portal.

Prerequisite - Perform platform-specific setup

Push notifications work differently on UWP, iOS, and Android, therefore, before the shared APIs can be leveraged in Xamarin.Forms, you need to perform some setup on each platform. Follow the instructions for integrating push with each of the platform-specific setup guides for Push, and then return here.

Setup Guides

Important

Even if you only access the AppCenter or Push class from your shared or PCL project, the App Center NuGet packages must be added to each platform-specific project.

Add App Center Push to your app

Please follow the Get started section if you haven't set up and started the SDK in your application yet.

1. Add the App Center Push module

Visual Studio for Mac or Xamarin Studio

  • Under your project, select Packages, open context menu and click Add packages.
  • Search for App Center, and select App Center Push.
  • Click Add Packages.

Visual Studio for Windows

  • Navigate to the Project > Manage NuGet Packages...
  • Search for App Center, then install Microsoft.AppCenter.Push.

Package Manager Console

  • Type the following command in Package Manager Console:

    PM> Install-Package Microsoft.AppCenter.Push

Note

If you use the App Center SDK in a portable project (such as Xamarin.Forms), you need to install the packages in each of the projects: the portable, Android, iOS and UWP ones.

2. Start App Center Push

In order to use App Center, you need to opt in to the module(s) that you want to use, meaning by default no modules are started and you will have to explicitly call each of them when starting the SDK.

Add the following using statement to the top of the file you are referencing Push from:

using Microsoft.AppCenter.Push

Next, add typeof(Push) to your AppCenter.Start() method to start App Center Push service.

AppCenter.Start("{Your App Secret}", typeof(Push));

Make sure you have replaced {Your App Secret} in the code sample above with your app secret.

Intercept push notifications

App Center Push makes it possible to intercept push notifications but there is some additional setup required to enable this feature in plaform specific projects.

iOS additional steps

Note

You only need this step if you disabled method swizzling while setting up Xamarin.iOS.

To enable the push event feature, implement DidReceiveRemoteNotification in your AppDelegate class as follows:

public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, System.Action<UIBackgroundFetchResult> completionHandler)
{
    var result = Push.DidReceiveRemoteNotification(userInfo);
    if (result)
    {
        completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
    }
    else
    {
        completionHandler?.Invoke(UIBackgroundFetchResult.NoData);
    }
}

Android additional steps

If (and only if) your launcher activity uses a launchMode of singleTop, singleInstance or singleTask, you need add this in the activity OnNewIntent method:

        protected override void OnNewIntent(Android.Content.Intent intent)
        {
            base.OnNewIntent(intent);
            Push.CheckLaunchedFromNotification(this, intent);
        }

UWP additional steps

To enable the push event feature, modify your UWP application's OnLaunched method to include Push.CheckLaunchedFromNotification(e); at the end as follows:

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    // ... not showing entire long method ...
    if (e.PrelaunchActivated == false)
    {
        if (rootFrame.Content == null)
        {
            // This is what triggers Xamarin.Forms portable App.OnStart method where you typically call AppCenter.Start
            rootFrame.Navigate(typeof(MainPage), e.Arguments);
        }
        Window.Current.Activate();
    }

    // Best place to call this method
    Push.CheckLaunchedFromNotification(e);

    // End of method
}

Subscribe to the push event

You can subscribe to the Push.PushNotificationReceived event to be notified whenever a push notification is received in the foreground or a background push notification has been clicked by the user.

The behavior of the event depends on:

  • The platform (iOS vs Android vs UWP).
  • Whether the push is received while application is in foreground or background.

For all platforms, when the push is received in background, the event is not fired right away, the user will first see an Android system notification, an iOS alert or a UWP toast.

The event is fired only by clicking the notification in that case.

When the push is received in foreground, the event is fired right away but no notification is shown to user.

Note

When the push is clicked from background on Android and UWP, the event does not have title and message in the event arguments, only iOS expose those fields for all events.

Note

On iOS only, if silent notifications are enabled and you push a notification with content-available: 1, then the event may be triggered twice for the same notification: when the notification is received in background and when it is tapped.

The following example demonstrates how to use the push event.

// This should come before AppCenter.Start() is called
Push.PushNotificationReceived += (sender, e) => {

    // Add the notification message and title to the message
    var summary =  $"Push notification received:" +
                        $"\n\tNotification title: {e.Title}" +
                        $"\n\tMessage: {e.Message}";

    // If there is custom data associated with the notification,
    // print the entries
    if (e.CustomData != null)
    {
        summary += "\n\tCustom data:\n";
        foreach (var key in e.CustomData.Keys)
        {
            summary += $"\t\t{key} : {e.CustomData[key]}\n";
        }
    }

    // Send the notification summary to debug output
    System.Diagnostics.Debug.WriteLine(summary);
};

Enable or disable Push at runtime

You can enable and disable App Center Push at runtime. If you disable it, the SDK will stop updating the WNS registration identifier that is used to push notifications, but the existing one will continue to work. In other words, disabling the App Center Push in the SDK will NOT stop your application from receiving push notifications.

Push.SetEnabledAsync(false);

To enable App Center Push again, use the same API but pass true as a parameter.

Push.SetEnabledAsync(true);

You don't need to await this call to make other API calls (such as IsEnabledAsync) consistent.

Check if App Center Push is enabled

You can also check if App Center Push is enabled or not:

bool isEnabled = await Push.IsEnabledAsync();