App Center Push

Note

For all the Android developers using App Center, there is a change coming where Firebase SDK is required to use Push Notifications. For Android P, its scheduled at the release date for the latest OS version. For all other versions of Android, it will be required after April 2019. Please follow the How to add Firebase SDK guide.

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.

Only devices with the Google Play Store application or emulators using Google APIs images can receive notifications.

Note

A notification appears in the system notification center only if the application is in the background at the moment the Push is received.

Prerequisites

1. Set up Firebase Cloud Messaging

  1. Create a project on the Firebase Console.
  2. Click the Android logo on the page to create an application matching your package name.
  3. Go to Project Settings and download the google-services.json file.
  4. Copy this file to your Android project app module.

2. Obtain your Android API Key

  1. In the Firebase Console, go to Project Settings.
  2. Navigate to the Cloud Messaging tab.
  3. Copy the Server Key. This will be the Android API Key that you will need to set in the App Center Push portal.

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

  • Open Visual Studio for Mac.
  • Click File > Open and choose your solution.
  • In the solution navigator, right click the Packages section, and choose Add NuGet packages....
  • Search for App Center, and install App Center Push.
  • Click Add Packages.

Visual Studio for Windows

  • Open Visual Studio for Windows.
  • Click File > Open and choose your solution.
  • In the solution navigator, right-click References and choose Manage NuGet Packages.
  • Search for App Center, and install Microsoft.AppCenter.Push.

Package Manager Console

  • Open the console in Visual Studio. To do this, choose Tools > NuGet Package Manager > Package Manager Console.
  • If you're working in Visual Studio for Mac, make sure you have NuGet Package Management Extensions installed. For this, choose Visual Studio > Extensions, search for NuGet and install, if necessary.
  • Type the following command in Package Manager Console:
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, and iOS ones. To do that, you should open each sub-project and follow the corresponding steps described in Visual Studio for Mac or Visual Studio for Windows sections.

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 must opt in to the module(s) that you want to use. 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.

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

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

3. Add google-services.json

  • Copy the google-services.json file into the root of your Android specific project using Visual Studio so that the file is visible in the solution.
  • Close and reopen your solution.
  • The next step depends if you are on Mac or Windows:
    • On Visual Studio for Mac, open the context menu on the google-services.json file then select GoogleServicesJson in Build Action.
    • On Visual Studio for Windows, select the google-services.json file in the Solution explorer. In Properties > Advanced > Build Action, select GoogleServicesJson.

4. Modify the project's AndroidManifest.xml file

If you're migrating from Google Cloud Messaging to Firebase, your project's AndroidManifest.xml file might contain outdated GCM configuration which may cause notification duplication. Edit the file and remove the following lines inside the <application> section, if present:

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

If your project's AndroidManifest.xml doesn't contain these lines, then there are no additional changes required to the file.

5. Customize ProGuard configuration

If you're using ProGuard, you must customize the project's configuration for Push.

5.1. Create a ProGuard configuration file

Note

If you don't use ProGuard or if you already have a ProGuard configuration file in your project, you may skip this section.

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

proguard-configuration-build-action

5.2. Add customization to ProGuard configuration file

In your Xamarin.Android project, add the following line to the project's proguard.cfg file:

-dontwarn com.microsoft.appcenter.**
-dontwarn com.google.android.gms.**
-keep class com.google.firebase.provider.FirebaseInitProvider
-keep class com.google.firebase.iid.FirebaseInstanceIdReceiver
-keep class com.google.firebase.messaging.FirebaseMessagingService

Intercept push notifications

Additional setup

If (and only if) your launcher activity uses a launchMode of singleTop, singleInstance or singleTask, you must add this in the activity's 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

A notification is not generated when your application receives a push in the 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 background notification click callback does NOT expose title and message. 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
// 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 that can be set via custom data. You can customize your notifications by setting custom color, icon or sound.

Note

Android 5.0 and later uses a silhouette (only alpha channel) of your icon for notifications. See Android 5.0 Behavior Changes for details.

Reserved keywords in Android platform

  • 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" />

App Center displays the application icon if a custom default icon and an icon are not set in the push payload.

Existing Firebase Analytics users

App Center Push SDK automatically disables Firebase Analytics. If you are a Firebase customer and want to keep reporting analytics data to Firebase, you must 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 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.

The state is persisted in the device's storage across application launches.

Note

This method must only be used after Push has been started.

Check if App Center Push is enabled

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

bool isEnabled = await Push.IsEnabledAsync();

Note

This method must only be used after Push has been started, it will always return false before start.