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.

Note that only devices having the Google Play store application or emulators with Google APIs images can receive the 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

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

2. Obtain your Android API Key

In the Firebase Console, go to Project Settings. Navigate to the Cloud Messaging tab. 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

  • 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 on 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.

3. Add google-services.json

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

Edit the project's AndroidManifest.xml file, then insert the following lines inside the section:

<application ...>
    
    <!-- Add these lines -->
    <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>
    <!-- end of section to add -->

</application>

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

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

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

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