Android Push Notifications

Sending Android Push Notifications from Mixpanel

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 MixpanelAPI object using your Mixpanel API key and calling MixpanelAPI.People.identify with a distinct id to identify your users to Mixpanel.

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.

Mixpanel’s Android SDK relies on GCM methods to generate device tokens, and Mixpanel 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 Mixpanel along with the Sender ID (you’ll need this later to generate tokens).

Uploading Your Google API Key to Mixpanel

In order for Mixpanel to send Google Cloud Messaging notifications on your behalf, you will need to enter the Google API key generated from the last step into Mixpanel. To upload it, log in to your Mixpanel project, click the settings gear in the upper righthand corner of your Mixpanel project, and select Project 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="" />
<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=""
          android:permission="" >
        <action android:name="" />
        <action android:name="" />
        <category android:name="YOUR_PACKAGE_NAME" />

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. Additionally, Android versions past 8.0 require that all notifications are categorized in a channel.

Setting up Your App to Receive Messages

Next, you'll need to tell Mixpanel which user record in People Analytics should receive the messages when they are sent from the Mixpanel 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) {
    mMixpanel = MixpanelAPI.getInstance(this, YOUR_MIXPANEL_PROJECT_ID_TOKEN);
    MixpanelAPI.People people = mMixpanel.getPeople();

Importing Device Tokens

If you already have your users' device tokens, you can import into Mixpanel by making API requests to the /engage endpoint and setting the special property $android_devices to a list of the user's Android device tokens in hex.

Your request should be formatted as a JSON dictionary, with $distinct_id and $token set as usual. $union should be set to a dictionary which has its $android_devices key pointing to an array of the users' device tokens in hex. A $union record operates on list properties and results in a list that contains only unique items (i.e., no duplicates). We use $union here, as opposed to $append so that the user's $android_devices list only contains one copy of each device ID.


    "$distinct_id": "123456",
    "$token": "36ada5b10da39a1347559321baf13063",
    "$ignore_time": true,
    "$union": {
        "$android_devices": ["2ffca4ad6599adc9b5202d15a5286d33c19547d472cd09de44219cda5ac30207"]

After base64 encoding, the above would be sent as this request: OiAiMTIzNDU2IiwNCiAgICAiJHRva2VuIjogIjM2YWRhNWIxMGRhMzlhMTM0NzU1O TMyMWJhZjEzMDYzIiwNCiAgICAiJGlnbm9yZV90aW1lIjogdHJ1ZSwNCiAgICAiJH VuaW9uIjogew0KICAgICAgICAiJGlvc19kZXZpY2VzIjogWyIyZmZjYTRhZDY1OTl hZGM5YjUyMDJkMTVhNTI4NmQzM2MxOTU0N2Q0NzJjZDA5ZGU0NDIxOWNkYTVhYzMw MjA3Il0NCiAgICB9DQp9

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 MixpanelAPI.flush in the onDestroy method of your main application activity, so closing it should send all waiting messages to Mixpanel.

Now log in to your Mixpanel 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

Mixpanel 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 Mixpanel Android API reference, which provides detailed information for all objects and methods available in the Mixpanel library.

Advanced Features

The information above should allow you to enable and use Mixpanel push notifications for many applications, but if you want to handle registration and message handling manually, or if you are using multiple Mixpanel 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 Mixpanel 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 Mixpanel's notification features. You shouldn't intermix these techniques with calls to initPushHandling.

You can send a registration id directly to Mixpanel 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 Mixpanel 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");
    MixpanelAPI.People people = mMixpanel.getPeople();

Incoming messages from Mixpanel will contain the key "mp_message", associated with the text of the message from Mixpanel 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 mixpanel, you can do whatever you'd like

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

initPushHandling and Multiple Projects

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

mMixpanel = MixpanelAPI.getInstance(this, "YOUR_MIXPANEL_PROJECT_TOKEN");
mMixpanel.getPeople().identify("some distinct_id_1");

mMixpanel2 = MixpanelAPI.getInstance(this, "YOUR_OTHER_MIXPANEL_PROJECT_TOKEN");
mMixpanel2.getPeople().identify("some distinct_id_2");

//both users distinct_id_1 and distinct_id_2 in their respective projects
//will be treated as having enabled push.