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 must install the packages in each of the projects: the portable, Android, iOS and UWP ones.

Note

If your Android project does not target the Mono framework version 8.1 or higher, you will not be able to install the package. You can safely bump this version in Options > General > Target framework as this has no impact on minimum API level or target API level fields. If you are using App Center Build, you must make sure Mono version is 5.8 or higher (in Build Config > Build app > More options).

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

Launch mode

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

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

Splash screen activity

This section applies if you have a Splash Screen activity (or a similar concept) that starts the main activity and main activity is the one creating the forms application.

When you click on the push notification if the application is not launched, the push information are intent extras in the launcher activity which is the splash screen. This intent needs to be copied to the main activity if the SDK is initialized in the main activity in order to process that information.

The simplest way of doing that is to locate the code where you start your main activity from the launcher activity:

    // Most apps have this
    StartActivity(new Intent(this, typeof(MainActivity)));

And modify it like this:

    var intent = new Intent(this, typeof(MainActivity));
    if (Intent.Extras != null)
        intent.PutExtras(Intent.Extras); // copy push info from splash to main
    StartActivity(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
// Avoid duplicate event registration:
if (!AppCenter.Configured)
{
    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);
    };
}

// AppCenter.start after
AppCenter.Start(..., ... ,typeof(Push), ...);

Custom Data in your notifications

You can send optional custom data as part of the push payload. The data will be sent in the key-value format. This custom data can be intercepted in the app through Push SDK callback.

There are few reserved keywords in each platform that can be set via custom data:

Android

  • color: The notification's icon color, expressed in #rrggbb format. Will be applied only on devices with Android 5.0 and later.
  • icon: The notification's icon. You should specify name of the icon resource. Supports drawable and mipmap types. If this value isn't specified application icon will be used.
  • sound: Add this key when you want the to play a sound when the device receives the notification. Supports default or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/. This is effective only for devices running or targeting an Android version lower than 8. Sound is set by default on Android 8 and user can change notification settings for the group of notifications coming from AppCenter.

Configure notification's default values

You can specify custom defaults for the icon and color that gets applied when it isn't set in the push payload.

The lines below should be added to AndroidManifest.xml inside the application tag:

<!-- Set default notification icon and color. -->
<meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_notification" />
<meta-data
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/notification" />

If no custom default icon is set and no icon is set in the push payload, AppCenter displays the application icon.

iOS

  • badge: Add this key when you want to modify the badge of your app icon. If this key is not included, the badge is not changed. To remove the badge, set the value of this key to 0.
  • sound: Add this key when you want the to play a sound. The value of this key is the name of a sound file in your app's main bundle or in the Library/Sounds folder of your app’s data container. If the sound file cannot be found, or if you specify default for the value, the system plays the default alert sound.
  • content-available: Add this key with a value of 1 to configure a silent notification. When this key is present, the system wakes up your app in the background and delivers the notification to its app delegate. For information about configuring and handling silent notifications, see Configuring a Silent Notification.
  • mutable-content: Add this key with a value of 1 to enable media attachments. The application needs to support a service extension to download and handle the attachment content. For more information you can refer to Apple documentations.

Windows

  • audio: Add this key when you want the to play a sound. this will modify the audio attribute for toast notifications.
  • image: Add this key when you want to modify the image attribute for tile and toast notifications.

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 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();