App Center Push

Note

Google announced it is migrating from the Google Cloud Messaging (GSM) platform to Firebase Cloud Messaging (FCM). For Android developers, the Firebase SDK is required to use Push Notifications. For additional information, please refer to the SDK migration 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

The App Center SDK is designed with a modular approach – a developer only needs to integrate the modules of the services that they're interested in.

  1. Modify the Android project level build.gradle file:

    buildscript {
        repositories {
            // Add google line if missing before jcenter
            google()
            jcenter()
        }
    
        dependencies {
            // Add this line
            classpath 'com.google.gms:google-services:4.0.1'
        }
    }
    
    allprojects {
        repositories {
            // Add google line if missing before jcenter
            google()
            jcenter()
        }
    }
    

    Note

    Google introduced the google() repository with Gradle v4. If your Gradle version is lower than v4, then you need to use maven { url 'https://maven.google.com' } instead of google().

  2. Modify the app level build.gradle file:

    dependencies {
        // Add App Center Push module dependency
        def appCenterSdkVersion = '2.2.0'
        implementation "com.microsoft.appcenter:appcenter-push:${appCenterSdkVersion}"
    }
    
    // Add this line at the bottom
    apply plugin: 'com.google.gms.google-services'
    

    Note

    If the version of your Android Gradle plugin is lower than 3.0.0, then you need to replace the word implementation by compile.

  3. Make sure to trigger a Gradle sync in Android Studio.

2. Start App Center Push

To use App Center capabilities in your application, the app must opt-in to the module(s) it wants to use. By default no modules are started and the app must explicitly call each of them when starting the SDK.

Add the Push class to the app's call to the AppCenter.start() method to start App Center Push.

AppCenter.start(getApplication(), "{Your App Secret}", Push.class);
AppCenter.start(application, "{Your App Secret}", Push::class.java)

Replace {Your App Secret} in the sample with the App Secret for the App Center project associated with this application. Refer to the Get started section if the SDK isn't configured in the application yet.

Android Studio automatically suggests the required import statement once you add Push to the start() method, but if you see an error that the class names are not recognized, add the following lines to the import statements in your activity class:

import com.microsoft.appcenter.AppCenter;
import com.microsoft.appcenter.push.Push;
import com.microsoft.appcenter.AppCenter
import com.microsoft.appcenter.push.Push

Intercept push notifications

Set up a listener to be notified whenever a push notification is received in foreground or a background push notification has been clicked by the user.

Note

The device does not generate a notification when an application receives a push notification when the app is 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 app must register the listener before calling AppCenter.start as shown in the following example:

Push.setListener(new MyPushListener());
AppCenter.start(...);
Push.setListener(MyPushListener())
AppCenter.start(...)

If the app's launcher activity uses a launchMode of singleTop, singleInstance or singleTask, add the following code in the activity onNewIntent method:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Push.checkLaunchedFromNotification(this, intent);
}
override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    Push.checkLaunchedFromNotification(this, intent)
}

Here is an example of the listener implementation that displays an alert dialog if the message is received in foreground or a toast if a background push has been clicked:

public class MyPushListener implements PushListener {

    @Override
    public void onPushNotificationReceived(Activity activity, PushNotification pushNotification) {

        /* The following notification properties are available. */
        String title = pushNotification.getTitle();
        String message = pushNotification.getMessage();
        Map<String, String> customData = pushNotification.getCustomData();

        /*
         * Message and title cannot be read from a background notification object.
         * Message being a mandatory field, you can use that to check foreground vs background.
         */
        if (message != null) {

            /* Display an alert for foreground push. */
            AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
            if (title != null) {
                dialog.setTitle(title);
            }
            dialog.setMessage(message);
            if (!customData.isEmpty()) {
                dialog.setMessage(message + "\n" + customData);
            }
            dialog.setPositiveButton(android.R.string.ok, null);
            dialog.show();
        } else {

            /* Display a toast when a background push is clicked. */
            Toast.makeText(activity, String.format(activity.getString(R.string.push_toast), customData), Toast.LENGTH_LONG).show(); // For example R.string.push_toast would be "Push clicked with data=%1s"
        }
    }
}
class MyPushListener : PushListener {

    override fun onPushNotificationReceived(activity: Activity, pushNotification: PushNotification) {

        /* The following notification properties are available. */
        val title = pushNotification.getTitle()
        val message = pushNotification.getMessage()
        val customData = pushNotification.getCustomData()

        /*
         * Message and title cannot be read from a background notification object.
         * Message being a mandatory field, you can use that to check foreground vs background.
         */
        if (message != null) {

            /* Display an alert for foreground push. */
            val dialog = AlertDialog.Builder(activity)
            if (title != null) {
                dialog.setTitle(title)
            }
            dialog.setMessage(message)
            if (!customData.isEmpty()) {
                dialog.setMessage(message + "\n" + customData)
            }
            dialog.setPositiveButton(android.R.string.ok, null)
            dialog.show()
        } else {

            /* Display a toast when a background push is clicked. */
            Toast.makeText(
                activity,
                String.format(activity.getString(R.string.push_toast), customData),
                Toast.LENGTH_LONG
            ).show() // For example R.string.push_toast would be "Push clicked with data=%1s"
        }
    }
}

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 the following method before AppCenter.start:

Push.enableFirebaseAnalytics(getApplication());
AppCenter.start(getApplication(), "{Your App Secret}", Push.class);

Enable or disable App Center Push at runtime

You can enable and disable App Center Push at runtime. If you disable it, the SDK will stop updating the Google registration identifier used to push but the existing one will continue working. In other words, disabling the App Center Push in the SDK will NOT stop your application from receiving push notifications.

Push.setEnabled(false);
Push.setEnabled(false)

To enable App Center Push again, use the same API but pass true as a parameter.

Push.setEnabled(true);
Push.setEnabled(true)

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

This API is asynchronous, you can read more about that in our App Center Asynchronous APIs guide.

Check if App Center Push is enabled

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

Push.isEnabled();
Push.isEnabled()

This API is asynchronous, you can read more about that in our App Center Asynchronous APIs guide.