Mobile Center Push

Mobile Center Push enables you to send push notifications to users of your app from the Mobile Center portal. Mobile Center portal and the Push SDK is integrated with Firebase Cloud Messaging.

Note that only devices having the Google Play store application or emulators with Google APIs images can receive the notifications. Also, Firebase displays a notification in the system notification center only if the application is in background at the moment the Push is received.

Prerequisite - Add Firebase to your app

1. Create a Firebase project

The first step in integrating your application with Mobile Center Push is to integrate it with Firebase Cloud Messaging. Start by creating a Firebase project in Google's Firebase console. Sign in with your Google account and proceed to the console. To create a Firebase project, select the add project button. Next, enter a project name and select Create Project.

Now that you've created a Firebase project, you must configure your application to receive Firebase notifications. On the side menu, select Notifications to navigate to the notifications page. To configure your application to receive notifications, select the Android logo (the button to the right of the one that says "iOS").

firebase-notifications-page

Follow steps one and two in the setup window. Since you are creating a Xamarin application, you may ignore step three. Finally, make sure to note where you save the google-services.json file, as you will need it later.

2. Obtain your Android API Key

Go to Project Settings and under Cloud Messaging, copy your Server Key. This will be the Android API Key that you will need to include in the Mobile Center Push portal.

3. Customize Proguard configuration

To ensure that the Proguard optimizer doesn't remove certain classes, you must customize its configuration.

3.1. Create a Proguard configuration file

Note

If you already have a Proguard configuration file in your project, you may skip to step 1.3.2.

Add an empty file to your Xamarin.Android project named proguard.cfg. Set the build action to "ProguardConfiguration."

proguard-configuration-build-action

3.2. Add customization to Proguard configuration file

In your Xamarin.Android project, please add the following lines to your proguard.cfg file:

-dontwarn com.google.android.gms.**
-keep class com.google.firebase.provider.FirebaseInitProvider
-keep class com.google.firebase.iid.FirebaseInstanceIdReceiver
-keep class com.microsoft.azure.mobile.push.TokenService
-keep class com.microsoft.azure.mobile.push.PushMessagingService

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 / Xamarin Studio

  1. From the menu bar, navigate to Project -> Add NuGet Packages...

  2. Search for Mobile Center Push and select the package titled Mobile Center Push (the package ID will be Microsoft.Azure.Mobile.Push), then click Add Package.

Package Manager Console

  1. Type the following command in Package Manager Console:

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

You may have the following known issues while building:

  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. Add the google-services.json File

Locate the google-services.json file from step 1 and add it to your project. Set the build action to "GoogleServicesJson."

google-services-json-build-action

Important

If you do not see this option under build actions, make sure you've added the Mobile Center Push NuGet package already. If you have and it still doesn't appear, try restarting your IDE.

3. Modify AndroidManifest.xml

Edit AndroidManifest.xml and insert the following <receiver> elements into the <application> section:

  <receiver 
      android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" 
      android:exported="false" />
  <receiver 
      android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" 
      android:exported="true" 
      android:permission="com.google.android.c2dm.permission.SEND">
      <intent-filter>
          <action android:name="com.google.android.c2dm.intent.RECEIVE" />
          <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
          <category android:name="${applicationId}" />
      </intent-filter>
  </receiver>

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

Note

If your Xamarin.Android project is part of a Xamarin.Forms application, it is not necessary to add the call to MobileCenter.Start() in the Xamarin.Android portion of the project. The method call can instead be made from the PCL or shared project portion of your Xamarin.Forms application.

Intercept push notifications

Additional setup

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

Subscribe to the push event

You can subscribe to the event Push.PushNotificationReceived to be notified whenever a push notification is received in the foreground or a background push notification has been clicked by the user. The following example demonstrates how to use the event and get the push data.

// 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);
};

Existing Firebase Analytics users

Mobile Center Push has a dependency on Firebase. Firebase Analytics is included in the core Firebase module and therefore, it's a dependency for Firebase messaging. Mobile Center Push SDK automatically disables Firebase Analytics to prevent unwanted data collection by Firebase.

If you are a Firebase customer and want to keep reporting analytics data to Firebase, you need to call Push.EnableFirebaseAnalytics() before MobileCenter.Start() like so:

Push.EnableFirebaseAnalytics();
MobileCenter.Start("{Your App Secret}", typeof(Analytics), typeof(Crashes), typeof(Push));

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