Setting up Push Campaigns for Android

You can set up, create, send, and measure push and in-app notification campaigns in Facebook Analytics.

Android Push Notifications Integration

This section contains documentation on how to integrate push notifications into your Android app. Follow these steps:

  • Add Firebase Cloud Messaging service (FCM) to your app
  • Set the FCM registration ID on AppEventsLogger
  • Present user-visible notifications that are sent using the FCM
  • Measure push notification opens or other actions taken

Integrate with Firecase Cloud Messaging Service

You can learn how to integrate FCM with your app from the official FCM for Android page.

Send Registration ID

Whenever the FCM token (registration ID) refreshes, set that ID on AppEventsLogger. This registers your device to receive notifications from Facebook Analytics. See the following example for a reference implementation of this:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. This call is initiated by the
     * InstanceID provider.
     */
    @Override
    public void onTokenRefresh() {
        try {
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            AppEventsLogger.setPushNotificationsRegistrationId(refreshedToken);
        } catch (Exception e) {
            Log.e("test", "Failed to complete token refresh", e);
        }
    }
}

As of version 4.20 of the Facebook SDK for Android, the push token is uploaded to Analytics immediately. In earlier versions of the SDK, the push token was uploaded with your next event, so if no events were sent after setPushNotificationRegistration(token), then the device would never be eligible to receive push notifications.

Show Local Notifications

All notifications sent using FCM are going to be delivered to your subclass of FirebaseMessagingService. Extract data from them to generate a user-visible notification.

By default - we send the title and body keys in the data payload, though you can specify any custom JSON payload data when creating push campaigns.

Use the following example to handle push notifications and generate user-visible notifications:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Bundle data = new Bundle();
        for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
            data.putString(entry.getKey(), entry.getValue());
        }

        Context context = this.getApplicationContext();
        Intent defaultAction = new Intent(context, MainActivity.class)
            .setAction(Intent.ACTION_DEFAULT)
            .putExtra("push", data);

        String title = data.getString("title");
        String body = data.getString("body");

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.notification_template_icon_bg)
            .setContentTitle(title == null ? "" : title)
            .setContentText(body == null ? "Hello world" : body)
            .setAutoCancel(true)
            .setContentIntent(PendingIntent.getActivity(
                context,
                0,
                defaultAction,
                PendingIntent.FLAG_UPDATE_CURRENT
            ));

        NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(123, mBuilder.build());
    }
}

Measure Notification Opens

Measuring notification opens should be performed when a person either performs an action on the notification or opens an activity from the notification. You can track both by using AppEventsLogger and specifying the payload you received using FCM.

AppEventsLogger logger = AppEventsLogger.newLogger(this); // 'this' is your Activity

Bundle payload = ...; // Same payload as FCM delivered to the app.
logger.logPushNotificationOpen(payload);

// OR

String actionId = ...;
logger.logPushNotificationOpen(payload, actionId);

If we combine this with our notification presentation above - then your activity tracking code would something like this:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(getApplicationContext());

        Intent startingIntent = this.getIntent();
        Bundle pushData = startingIntent.getBundleExtra("push");
        if (pushData != null) {
            final AppEventsLogger logger = AppEventsLogger.newLogger(this);
            logger.logPushNotificationOpen(pushData, startingIntent.getAction());
        }
    }
}

Android In-App Notifications Integration

Integration of in-app notifications is very similar to general notification presentation. To start, integrate with the open-source FBNotifications SDK located on Github.

Instead of creating a notification yourself, pass a bundle payload to the NotificationsManager. It also gives you an option to customize the presented notification:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    Bundle data = new Bundle();
    for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
      data.putString(entry.getKey(), entry.getValue());
    }

    if (NotificationsManager.canPresentCard(data)) {
      NotificationsManager.presentNotification(
        this,
        data,
        new Intent(getApplicationContext(), MainActivity.class)
      );
    }
  }
}

When all the content for the in-app notification is ready, it will automatically show the notification to the end user with a pending intent to present a card on open. To hand-off the necessary data from the intent, handle the notification in onCreate and onNewIntent functions of your Main Activity:

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(getApplicationContext());
    NotificationsManager.presentCardFromNotification(this);
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    setIntent(intent);
    NotificationsManager.presentCardFromNotification(this);
  }
}