App Center Push

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

Note

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 App 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 App 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.appcenter.push.TokenService
-keep class com.microsoft.appcenter.push.PushMessagingService

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.

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 8.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 8.0, then you need all the lines in packages.config to match this: targetFramework="monoandroid80".
  3. If you have a package conflict when installing or updating the Push nuget package, you need to update the Xamarin.GooglePlayServices.Basement package (using the U.I. and checking pre-release check box), to version 60.1142.0-beta1 or more recent before trying again to install or update App Center Push.
  4. If you have build issues, please note that a Visual Studio clean might not be enough. Try closing Visual Studio, and remove every bin and obj folders that were not cleaned.
  5. 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 App 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 App 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 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.

Note

If your Xamarin.Android project is part of a Xamarin.Forms application, it is not necessary to add the call to AppCenter.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 (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);
        }

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.

Note

Firebase does not generate notifications when the push is received in foreground.

Note

If the push is received in background, the event is NOT triggered at receive time. The event is triggered when you click on the notification.

Note

The Firebase SDK does NOT expose title and message to the background notification click callback. Title and message are only available in foreground pushes.

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

Existing Firebase Analytics users

App 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. App 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 AppCenter.Start() like so:

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

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