Mobile Center Push

Mobile Center Push enables you to send push notifications to users of your app from the Mobile 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 MobileCenter or Push class from your shared or PCL project, the Mobile Center NuGet packages must be added to each platform-specific project.

Add Mobile 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 Mobile Center Push module

Visual Studio for Mac or Xamarin Studio

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

Visual Studio for Windows

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

Package Manager Console

  • Type the following command in Package Manager Console:

    PM> Install-Package Microsoft.Azure.Mobile.Push

Note

If you use the Mobile 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.

You may have the following known issues while building on Android:

  1. After adding if you see java exited with code 2, it is caused by the Firebase dependency. Xamarin team is tracking an issue where Xamarin.Android projects hit the multidex limit.
    • For debug builds, we recommend enabling Multi-dex in build options to work around that issue.
    • For release builds, you can also use multi-dex but it's better to try using Proguard first (and if you can, Link All). Read more about linker settings and how they work.
  2. If your target framework is lower than 7.0, you need to update it.
    • Target framework has no impact on minimum supported version which remains unchanged (you can still support Android 4.0.3 / API level 15, this setting has nothing to do with it). You can change target version in build settings. The difference between minimum and target API levels is explained in the Xamarin.Android API levels guide.
    • After the change, you need to update your packages.config and update all targetFramework attributes to match the version. For example if in build settings the version is 7.1, then you need all the lines in packages.config to match this: targetFramework="monoandroid71".
  3. If you see the following error message in the logs:

    java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process {your_package_name}. Make sure to call FirebaseApp.initializeApp(Context) first.

Make sure the google-services.json has the GoogleServicesJson build action. If you are sure, then clean and build again, this is a known issue when reusing builds (this issue is not caused by Mobile Center SDK, you can read more about this issue in the Xamarin forums).

2. Start Mobile Center Push

In order to use Mobile 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.Azure.Mobile.Push

Next, add typeof(Push) to your MobileCenter.Start() method to start Mobile Center Push service.

MobileCenter.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

Mobile 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 MobileCenter.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 MobileCenter.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 Mobile 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 Mobile Center Push in the SDK will NOT stop your application from receiving push notifications.

Push.SetEnabledAsync(false);

To enable Mobile 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 Mobile Center Push is enabled

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

bool isEnabled = await Push.IsEnabledAsync();