Overview

A push notification is an out-of-app alert that appears on the user’s screen when an important update occurs. Push notifications are a valuable way to provide your users with time-sensitive and relevant content or to re-engage them with your app.

Sample push notification:

Sample Push

Check out Braze Academy for additional best practices.

Braze sends push notifications to Android devices using Firebase Cloud Messaging (FCM).

Push notifications for Amazon FireOS use the Amazon Device Messaging (ADM) service rather than FCM. See the FireOS Push Integration instructions for details on enabling push notifications for FireOS apps.

For devices without Google services installed, Braze offers the option to send push through Baidu Cloud Push. Visit Baidu Cloud Push instructions for more details.

Registering for Push

Use Firebase to register for push.

Though you could previously use GCM, Google has announced that they will remove support for GCM as soon as April 11, 2019 and automatic GCM registration is unavailable through the Braze SDK. If your app is currently supporting GCM, we advise that you speak to your development teams about transitioning to Firebase from GCM as soon as possible.

Firebase Integration

We recommend using Firebase Cloud Messaging (FCM) for push.

Apps already using any of the Firebase SDKs must use the Firebase Messaging SDK to receive Braze pushes. This is because Firebase is not guaranteed to be compatible with GCM in all versions of Google Play Services.

For a full sample of using Firebase with the Braze Android SDK, see our Firebase Push sample app.

Step 1: Enable Firebase

To get started, follow the instructions at Add Firebase to Your Android Project.

Next, add the Firebase Messaging dependency to your module’s build.gradle:

1
compile "com.google.firebase:firebase-messaging:<YOUR_PLAY_SERVICES_VERSION>"

Firebase Messaging is the only Firebase dependency that Braze requires for push messaging.

Step 2: Configure Token Registration

Braze push notifications won’t work until a Firebase Cloud Messaging token is registered. Firebase tokens can either be registered by the Braze SDK automatically (recommended) or manually registered. Tokens can be manually registered using the Appboy.registerAppboyPushMessages() method either directly or using a Firebase Instance Id Service.

Make sure to use your project number, not the project ID. The project number is also known as the Firebase sender ID.

Option 1: Automatic Registration

To automatically register Firebase push tokens, enable automatic Firebase registration and set a Firebase Cloud Messaging sender ID.

In your appboy.xml:

1
2
<bool translatable="false" name="com_appboy_firebase_cloud_messaging_registration_enabled">true</bool>
<string translatable="false" name="com_appboy_firebase_cloud_messaging_sender_id">your_fcm_sender_id_here</string>

Or in your AppboyConfig:

1
2
3
4
5
AppboyConfig appboyConfig = new AppboyConfig.Builder()
  .setIsFirebaseCloudMessagingRegistrationEnabled(true)
  .setFirebaseCloudMessagingSenderIdKey("YOUR FIREBASE SENDER ID HERE")
  .build();
Appboy.configure(this, appboyConfig);

If using a Firebase automatic registration, you can skip the manual options below.

Option 2: Manual Application onCreate() Registration

We recommended you call Appboy.registerAppboyPushMessages() from within your application onCreate() method to ensure that push tokens are reliably delivered to Braze.

See the snippet below for an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();

    // Firebase tokens cannot be obtained on the main thread.
    final Context applicationContext = this;
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          String token = FirebaseInstanceId.getInstance().getToken("<YOUR_SENDER_ID>", "FCM");
          Appboy.getInstance(applicationContext).registerAppboyPushMessages(token);
        } catch (Exception e) {
          Log.e(TAG, "Exception while registering Firebase token with Braze.", e);
        }
      }
    }).start();
  }
}

While we highly recommend you register your Firebase token in your application onCreate(), the push token can be registered anywhere in your code.

Option 3: Manual Instance ID Service Registration

Firebase tokens can be passed to Braze using a Firebase Instance ID Service.

To register the service, add the following lines to the application element of your AndroidManifest.xml:

1
2
3
4
5
6
<service
    android:name=".AppboyFirebaseInstanceIdService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

Next, obtain a Firebase token inside your service.

1
2
3
4
5
6
7
8
9
10
11
public class AppboyFirebaseInstanceIdService extends FirebaseInstanceIdService {
  @Override
  public void onTokenRefresh() {
    try {
      String token = FirebaseInstanceId.getInstance().getToken("<YOUR_SENDER_ID>", "FCM");
      Appboy.getInstance(getApplicationContext()).registerAppboyPushMessages(token);
    } catch (Exception e) {
      Log.e(TAG, "Exception while registering Firebase token with Braze.", e);
    }
  }
}

If you already use a Firebase Instance ID Service to register for push tokens prior to integrating Braze, you must ensure you pass the existing token to Braze upon a user updating to a version of the app with our SDK integrated. This can be done by calling Appboy.registerAppboyPushMessages() from within your applications onCreate() method.

Step 3: Migrate from GCM (Optional)

If migrating from using GCM to using Firebase with Braze, visit the GCM Migration Guide for instructions on how to properly switch to using Firebase in your app.

Step 4: Set Your Firebase Credentials

You need to input your Firebase Server Key and Sender ID into the Braze dashboard:

  • On the app settings page (where your API keys are located), select your Android app.
  • Enter your Firebase Server Key in the field labeled “Cloud Messaging API Key” under the Push Notification Settings section.
  • Enter your Firebase Sender ID in the field labeled “Cloud Messaging Sender ID” under the Push Notification Settings section.

fcmimg

If you’re not familiar with the location of your Firebase Server Key and Sender ID, follow these steps:

  1. Login to the Firebase Developers Console

  2. Select your Firebase project

  3. Select Cloud Messaging under Settings and copy the Server Key and Sender ID: FirebaseServerKey

Step 5: Remove Old Permissions

  • Braze no longer requires the following permissions if using Firebase:

    1
    2
    3
    4
    5
    
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="YOUR-APPLICATION-PACKAGE-NAME.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
    <uses-permission android:name="YOUR-APPLICATION-PACKAGE-NAME.permission.C2D_MESSAGE" />
    

Displaying Push

After completing this section, you should be able to receive and display push notifications sent by Braze.

Step 1: Register Braze FCM Receiver

Braze includes a FcmReceiver to handle push receipt and open intents. Our FcmReceiver class will need to be registered in your AndroidManifest.xml.

  • Add AppboyFcmReceiver to your AndroidManifest.xml. The category should be set to your application package name:

    1
    2
    3
    4
    5
    6
    
    <receiver android:name="com.appboy.AppboyFcmReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
     <intent-filter>
       <action android:name="com.google.android.c2dm.intent.RECEIVE" />
       <category android:name="YOUR-APPLICATION-PACKAGE-NAME" />
     </intent-filter>
    </receiver>
    

Braze’s notification code also uses AppboyFcmReceiver to handle open and click action tracking. This receiver must be registered in the AndroidManifest.xml in order for that to function correctly. Also, keep in mind that Braze prefixes notifications from our system with a unique key and ensures that our broadcast receivers only render notifications sent from Braze’s systems. You may register additional receivers separately in order to render notifications sent from other FCM services.

Note Before Braze Android SDK 2.7.0, AppboyFcmReceiver is known as AppboyGcmReceiver. Their functionality is equivalent and integration instructions remain the same, however, all references to AppboyFcmReceiver in your AndroidManifest.xml and code will need to be replaced by references to AppboyGcmReceiver.

Implementation Example

Step 2: Configure Notification Icons

Specifying Icons in appboy.xml
  • Braze allows you to configure your notification icons by specifying drawable resources in your appboy.xml:
1
2
<drawable name="com_appboy_push_small_notification_icon">REPLACE_WITH_YOUR_ICON</drawable>
<drawable name="com_appboy_push_large_notification_icon">REPLACE_WITH_YOUR_ICON</drawable>

Setting a small notification icon is required. If you do not set one, Braze will default to using the application icon as the small notification icon which may look suboptimal.

Setting a large notification icon is optional but recommended.

Specifying Icon Background Color
  • The notification icon background color can be overriden in your appboy.xml. If the color is not specified, the default background color is the same gray Lollipop uses for system notifications. Please see the example color override below:
1
<integer name="com_appboy_default_notification_accent_color">0xFFf33e3e</integer>
Notification Icon Design Guidelines

For general information about Android notification icons, please see the Anatomy of a Notification section from the Android developer documentation.

Android’s Design Guidelines require small notification icons to be all white on a transparent background. If you do not comply, your icons may look suboptimal when displayed by the Android system.

The icons pictured below are examples of properly designed icons:

Android Icon Example

To enable Braze to automatically open your app and any deep links when a push notification is clicked, set com_appboy_handle_push_deep_links_automatically to true in your appboy.xml:

1
<bool name="com_appboy_handle_push_deep_links_automatically">true</bool>

This flag can also be set via runtime configuration:

1
2
3
4
AppboyConfig appboyConfig = new AppboyConfig.Builder()
        .setHandlePushDeepLinksAutomatically(true)
        .build();
Appboy.configure(this, appboyConfig);

If you would like to custom handle deep links, you will need to create a BroadcastReceiver that listens for push received and opened intents from Braze. See our section on Custom Handling Push Receipts and Opens for more information.

Please follow the instructions found within the Android Developer Documentation on Deep Linking if you have not already added deep links to your app. For information regarding what a deep link is, please see our FAQ Section.

The Braze dashboard supports setting deep links or web URLs on push notifications that will be opened when the notification is clicked.

Deep_Link_Dash_Example

Customizing Back Stack Behavior

The Android SDK by default will place your host app’s main launcher activity in the back stack when following push deep links. Braze allows you to set a custom activity to open in the back stack in place of your main launcher activity or to disable the back stack altogether.

For example, to set an activity called YourMainActivity as the back stack activity, see the following example using runtime configuration:

1
2
3
4
5
AppboyConfig appboyConfig = new AppboyConfig.Builder()
        .setPushDeepLinkBackStackActivityEnabled(true)
        .setPushDeepLinkBackStackActivityClass(YourMainActivity.class)
        .build();
Appboy.configure(this, appboyConfig);

See the equivalent configuration for your appboy.xml. Note that the class name must be the same as returned by Class.forName():

1
2
<bool name="com_appboy_push_deep_link_back_stack_activity_enabled">true</bool>
<string name="com_appboy_push_deep_link_back_stack_activity_class_name">your.package.name.YourMainActivity</string>

Back stack configuration is only available on SDK 2.1.4 and above.

Step 4: Define Notification Channels

Braze SDKs 2.1.0 and above support Android O Notification Channels. In the case that a Braze notification does not contain the ID for a notification channel or that a Braze notification contains an invalid channel ID, Braze will display the notification with the default notification channel defined in the SDK. Braze users make use of Android Notification Channels within the platform to group notifications.

To set the user facing name of the default Braze notification channel, please use AppboyConfig.setDefaultNotificationChannelName().

To set the user facing description of the default Braze notification channel, please use AppboyConfig.setDefaultNotificationChannelDescription().

If you are an existing customer who is transitioning to Android O, you should ensure that any API campaigns with the Android Push Object parameter are updated to include the notification_channel field. If this field is not specified, Braze will send the notification payload with the dashboard fallback channel ID.

Other than the default notification channel, Braze will not create any channels. All other channels must be programmatically defined by the host app and then entered into the Braze dashboard.

Notification Channel Creation by SDK

SDK 2.1.0 and Above

The default notification channel creation will occur even if your app does not target Android O. If you would like to avoid default channel creation until your app targets Android O, do not upgrade to this version.

SDK Lower than 2.1.0 and Your App Targets API 25 or Lower

You do not need to define channels in your application.

Step 5: Test Notification Display and Analytics

Testing Display

At this point you should be able to see notifications sent from Braze. To test this, go to the Campaigns section of your Braze dashboard and create a Push Notification campaign. Choose Android Push and design your message. Then click the eyeball in the composer to get the test sender. Enter the user id or email address of your current user and click Send Test. You should see the push show up on your device.

Android push test

For issues related to push display, see our Troubleshooting Guide.

Testing Analytics

At this point you should also have analytics logging for push notification opens. To test this, see our Academy Page on creating a push campaign. Clicking on the notification when it arrives should result in the Direct Opens on your campaign results page to increase by 1.

For issues related to push analytics, see our Troubleshooting Guide.

Testing From Command Line

If you’d like to test in-app and push notifications via the command-line, you can send a single notification through the terminal via cURL and the Messaging API. You will need to replace the following fields with the correct values for your test case:

  • YOUR_API_KEY - available on the Developer Console page
  • YOUR_EXTERNAL_USER_ID - available on the User Profile Search Page
  • YOUR_KEY1 (optional)
  • YOUR_VALUE1 (optional)
1
curl -X POST -H "Content-Type: application/json" -d "{\"api_key\":\"YOUR_API_KEY\",\"external_user_ids\":[\"YOUR_EXTERNAL_USER_ID\"],\"messages\":{\"android_push\":{\"title\":\"Test push title\",\"alert\":\"Test push\",\"extra\":{\"YOUR_KEY1\":\"YOUR_VALUE1\"}}}}" https://rest.iad-01.braze.com/messages/send

The above is an example for customers on the US-01 instance. If you are not on this instance please refer to our API documentation to see which endpoint to make requests to.

Customizing Your Integration

Custom Displaying Notifications

Step 1: Create your Custom Notification Factory

In some scenarios you may wish to customize push notifications in ways that would be cumbersome or unavailable server side. To give you complete control of notification display, we’ve added the ability to define your own IAppboyNotificationFactory to create notification objects for display by Braze.

If a custom IAppboyNotificationFactory is set, Braze will call your factory’s createNotification() method upon push receipt before the notification is displayed to the user. Braze will pass in a Bundle containing Braze push data and another Bundle containing custom key-value pairs sent either via the dashboard or the messaging APIs:

1
2
3
4
5
// factory method implemented in your custom IAppboyNotificationFactory
createNotification(AppboyConfigurationProvider appConfigurationProvider, Context context, Bundle notificationExtras, Bundle appboyExtras) {
  // example of getting notification title
  String title = notificationExtras.getString(Constants.APPBOY_PUSH_TITLE_KEY);
}

You can return null from your custom createNotification() method to not show the notification at all, use AppboyNotificationFactory.getInstance().createNotification() to obtain Braze’s default notification object for that data and modify it before display, or generate a completely separate notification object for display.

Braze push data keys are documented here.

Step 2: Set your Custom Notification Factory

To instruct Braze to use your custom notification factory, use the method on the Braze interface to set your IAppboyNotificationFactory:

1
setCustomAppboyNotificationFactory(IAppboyNotificationFactory appboyNotificationFactory);

The recommended place to set your custom IAppboyNotificationFactory is in the Application.onCreate() application lifecycle method (not activity). This will allow the notification factory to be set correctly whenever your app process is active. See DroidboyApplication.java for an example.

Creating your own notification from scratch is an advanced use case and should be done only with thorough testing and deep understanding of Braze’s push functionality (you must, for example, ensure your notification logs push opens correctly).

Custom Handling Push Receipts, Opens, and Key-Value Pairs

Braze broadcasts custom intents when push notification are received or opened. If you have a specific use case for these scenarios (such as the need to listen for custom key-value pairs or proprietary handling of deep links), you will need to listen for these intents by creating a custom BroadcastReceiver.

Step 1: Register your BroadcastReceiver

Register your custom BroadcastReceiver to listen for Braze push opened and received intents in your AndroidManifest.xml.

1
2
3
4
5
6
7
<receiver android:name="YOUR-BROADCASTRECEIVER-NAME" android:exported="false" >
  <intent-filter>
    <!-- Replace YOUR-APPLICATION-PACKAGE-NAME with the package name of your app -->
    <action android:name="YOUR-APPLICATION-PACKAGE-NAME.intent.APPBOY_PUSH_RECEIVED" />
    <action android:name="YOUR-APPLICATION-PACKAGE-NAME.intent.APPBOY_NOTIFICATION_OPENED" />
  </intent-filter>
</receiver>

Step 2: Create your BroadcastReceiver

Your receiver should handle intents broadcast by Braze and launch your activity with them:

  • It should subclass BroadcastReceiver and override onReceive().
  • The onReceive() method should listen for intents broadcast by Braze.
    • An APPBOY_PUSH_RECEIVED intent will be received when a push notification arrives.
    • An APPBOY_NOTIFICATION_OPENED intent will be received when a push notification is clicked by the user.
  • The receiver should perform your custom logic for each of these cases. If your receiver will open deep links, be sure to turn off automatic deep link opening by setting com_appboy_handle_push_deep_links_automatically to false in your appboy.xml.

For a detailed custom receiver example, please see AppboyBroadcastReceiver.java in our Custom Broadcast sample app. Visit this page for a basic tutorial on creating broadcast receivers: Android Receiver Help

With notification action buttons, APPBOY_NOTIFICATION_OPENED intents fire when buttons with opens app or deep link actions are clicked. Deep link and extras handling remains the same. Buttons with close actions don’t fire APPBOY_NOTIFICATION_OPENED intents and dismiss the notification automatically.

Step 3: Access Custom Key-Value Pairs

Custom key-value pairs sent either via the dashboard or the messaging APIs will be accessible in your custom broadcast receiver for whatever purpose you choose:

1
2
3
4
5
6
7
8
// intent is the Braze push intent received by your custom broadcast receiver.
String deepLink = intent.getStringExtra(Constants.APPBOY_PUSH_DEEP_LINK_KEY);

// The extras bundle extracted from the intent contains all custom key-value pairs.
Bundle extras = intent.getBundleExtra(Constants.APPBOY_PUSH_EXTRAS_KEY);

// example of getting specific key-value pair from the extras bundle.
String myExtra = extras.getString("my_key");

Braze push data keys are documented here.

WAS THIS PAGE HELPFUL?