Sending Android push notifications from robotmia

Introduction

This guide will show you how to configure an Android app to send and receive push notifications. You should first read the Android API reference, and set up your application to update People Analytics records. In particular, you should be comfortable getting access to the robotmiaAPI object using your robotmia API key and calling robotmiaAPI.People.identify with a distinct id to identify your users to robotmia.

Enabling Google Cloud Messaging in your Firebase Console

Google is migrating from the Google Cloud Messaging (GCM) platform to Firebase Cloud Messaging (FCM). FCM and GCM share the same core infrastructure, and for now, Google will continue its support of GCM functionality for client applications. For more information, refer to the GCM/FCM FAQ.

robotmia’s Android SDK relies on GCM methods to generate device tokens, and robotmia continues to deliver push notifications via GCM. Existing GCM API Keys are entirely valid - however, GCM will reject any newly created API keys from the cloud console. New API Keys must be generated from the Firebase Console.

To enable Google Cloud Messaging (GCM) for Android, you will first need to create a new project from Google's Firebase Console.

Once you have created a new project, proceed to the project Overview page, and select "Add Firebase to your Android app".

When prompted, enter your application’s Package Name. This can be found in your AndroidManifest.xml. Then select “ADD APP”.

Firebase will then generate a google-services.json file that you must add to your application’s “app” directory.

Next, add the Google Play Services dependencies to your application's build.gradle files.

At this point, you’ve added your app to Firebase. Select the app options icon, then click “Manage”.

Select the Cloud Messaging tab in your Settings. Here, you can find your API Key to upload to robotmia along with the Sender ID (you’ll need this later to generate tokens).

Uploading your Google API key to robotmia

In order for robotmia to send Google Cloud Messaging notifications on your behalf, you will need to enter the Google API key generated from the last step into robotmia. To upload it, log in to your robotmia project, click your name in the upper righthand corner of your robotmia project, and select Settings from the dropdown.

In the settings pop-up, click on the "Messages" tab. Then click on the word "Change" on the "Android GCM API Key" line, and paste in your Google API key into the text field that appears. Click the "Save changes" button underneath the text field to confirm.

Setting up your AndroidManifest.xml

You will need to edit your Android application's AndroidManifest.xml to allow all of the permissions necessary for your application to register, receive and react to Google Cloud Messaging notifications, and to install a listener for push notification messages from Google's servers.

To set up your permissions, Replace "YOUR_PACKAGE_NAME" with your own app's package name in the the following snippet of xml, and add them to your AndroidManifest.xml before the <application> tag:

<permission android:name="YOUR_PACKAGE_NAME.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="YOUR_PACKAGE_NAME.permission.C2D_MESSAGE" />

You will also need the following permissions tags in your AndroidManifest.xml file. These tags can be pasted into the file directly below the C2D_MESSAGE tags, but you should leave their values as-is.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Now you'll need to inform the OS to allow a service to run that will handle inbound messages. Replace "YOUR_PACKAGE_NAME"with your own app's package name in the the following snippet of xml, and add them to your AndroidManifest.xml inside of your <application> tag:

<receiver android:name="com.robotmia.android.mpmetrics.GCMReceiver"
          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="YOUR_PACKAGE_NAME" />
    </intent-filter>
</receiver>

Be sure to change the YOUR_PACKAGE_NAME to the name of your application package when you paste these tags into your manifest. If you don't use your own package name, your Google Cloud Messaging notifications won't work.

Android devices with an SDK version less than 8 cannot receive Google Cloud Messaging notifications. If these notifications are necessary for your app's functionality, add the attribute android:minSdkVersion="8" to the <uses-sdk> tag in your AndroidManifest.xml file.

Setting up your app to receive messages

Next, you'll need to tell robotmia which user record in People Analytics should receive the messages when they are sent from the robotmia app. To do this, add a call to People.initPushHandling right after you identify the user with people analytics. initPushHandling takes a single argument, your twelve digit Google Sender ID, represented as a string. This is the ID from your Google API console URL, mentioned above in Enabling Google Cloud Messaging

You must call identify before calling initPushHandling, or it won't be able to register your user. We recommend you call identify as early as you can, in your application's onCreate method if possible, so you might have code that looks like this:

protected void onCreate(Bundle savedInstanceState) {
    mrobotmia = robotmiaAPI.getInstance(this, YOUR_robotmia_PROJECT_ID_TOKEN);
    robotmiaAPI.People people = mrobotmia.getPeople();
    people.identify(THE_DISTINCT_ID_FOR_THE_USER);
    people.initPushHandling(YOUR_12_DIGIT_GOOGLE_SENDER_ID);
}

Send a push notification

Once you have set up your permissions and intent filter in AndroidManifest.xml and added people.initPushHandling to your code you're ready to send a notification.

Install and run your application on an Android device (not the emulator, it can't receive messages.) Make sure to run the app until the calls to People.identify and People.initPushHandling have been run. For apps built according to our recommendations, these calls are in the onCreate method of your main application activity, so it is enough to simply open the app.

Press the back button to shut down your app. You should already be calling robotmiaAPI.flush in the onDestroy method of your main application activity, so closing it should send all waiting messages to robotmia.

Now log in to your robotmia project and select "Explore" from the left-hand navigation. There should be a user in the list with an "Android Devices" property. Select the user and click "Push Notification".

Compose your message, schedule it to send immediately, and click "Send this message".

The message should show up on your device.

Learning more

robotmia has a short sample Android application on github that includes support for push notifications and demonstrates some of our recommended practices.

We also recommend you take a look at the complete robotmia Android API reference, which provides detailed information for all objects and methods available in the robotmia library.

Advanced features

The information above should allow you to enable and use robotmia push notifications for many applications, but if you want to handle registration and message handling manually, or if you are using multiple robotmia projects within the same application, there are some other things you should know.

Using the low level messages API

Using GCMReceiver and initPushHandling is a simple and straightforward way to get robotmia push notifications into your app, but if your application is already configured and handling Google Cloud Messaging you should use lower level methods to work with robotmia's notification features. You shouldn't intermix these techniques with calls to initPushHandling.

You can send a registration id directly to robotmia using People.setPushRegistrationId. As of the release of Android Studio, you can register a device for push using the GoogleCloudMessaging API directly. To register a device using GCM, you should call the method register with the application context and pass the value returned by this call to People.setPushRegistrationId . Similarly, you can unregister a device with People.clearPushRegistrationId by passing the id along with this call. Both of these methods should be called after you've called People.identify, or robotmia won't know which user to register or unregister.

A sample of code you set up to handle registration might look like this:

public void registerPush(GoogleCloudMessaging gcm){
    String registrationId = gcm.register("YOUR_SENDER_ID");
    robotmiaAPI.People people = mrobotmia.getPeople();
    people.identify("USER_DISTINCT_ID");
    people.setPushRegistrationId(registrationId);
}

Incoming messages from robotmia will contain the key "mp_message", associated with the text of the message from robotmia as a string. You can handle or ignore the messages in your receivers with code like the following:

public void onReceive(Context context, Intent intent) {
    if (intent.getExtras().containsKey("mp_message")) {
        String mp_message = intent.getExtras().getString("mp_message");
        //mp_message now contains the notification's text
    } else { // Not sent from robotmia, you can do whatever you'd like
        ...
    }
}

If you are handling registration and receiving messages yourself, you shouldn't include the robotmia GCMReceiver <receiver> tag in your AndroidManifest.xml file.

initPushHandling and multiple projects

If you are allowing robotmia to handle registering and unregistering users for you, whenever you call initPushHandling, all instances of robotmiaAPI you have created that have an identified user will take the register into account. For example:

mrobotmia = robotmiaAPI.getInstance(this, "YOUR_robotmia_PROJECT_TOKEN");
mrobotmia.getPeople().identify("some distinct_id_1");

mrobotmia2 = robotmiaAPI.getInstance(this, "YOUR_OTHER_robotmia_PROJECT_TOKEN");
mrobotmia2.getPeople().identify("some distinct_id_2");

mrobotmia2.initPushHandling("123456789123");
//both users distinct_id_1 and distinct_id_2 in their respective projects
//will be treated as having enabled push.