Initial SDK setup


The next major version of FollowAnalytics SDK will remove the support of GCM and instead will use Firebase services.

Minimum setup

FollowAnalytics SDK works with Android SDK version 14 (Ice Cream Sandwich) to 27 (Oreo).

To get started, you need to perform the following tasks:

Install using Gradle

If you use Gradle as your build system, you can fetch the library from our private nexus repository.

Add the FollowAnalytics repository to your build.gradle repositories.

repositories {
    maven {
        url ''

Add the FollowAnalytics SDK to your module's build.gradle dependencies.

  dependencies {
      implementation ""

The FollowAnalytics dependencies

For your information the FollowAnalytics SDK depends on the following libraries. By using Gradle, dependencies will automatically be added while merging the manifest

ShortcutBadger dependency

This dependency allows some devices to show the count of unread messages as a badge on the application shortcut.


The SDK adds automatically the following permissions to your manifest.

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Additional permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.GET_TASKS"/>

Android M and permissions

The following permissions are labelled as dangerous since Android 6.0 Marshmallow (find more information about dangerous permissions here):

  • android.permission.ACCESS_COARSE_LOCATION
  • android.permission.ACCESS_FINE_LOCATION (if you use the geofencing feature).

To include permissions while keeping your user experience, we recommend you to follow the Android guidelines described here.

Initialize with your API key

Prepare your API key

Be sure to have your API key for this step of the configuration. If you are not sure where to find it, please reach out to your Customer Success Manager or message support.

To add your API key to your app project, add the following to your Manifest file, within the application tag:

   <meta-data android:name="FAID" android:value="YOUR_API_KEY"/>

To initialize the FollowAnalytics SDK use the onCreate() method of an Application class. This allows the SDK to be systematically initialized, whether the user launches the app himself, or if the Android system wakes a receiver or service of the application (for example, a push notification).

Open your Application subclass, or create a new one, and add the following lines to override the onCreate method:

public class MyAwesomeApplication extends Application {
    public void onCreate() {

If you just created an Application subclass, remember to declare it in your AndroidManifest.xml file:

    [...] />

### Register for notifications

!!! danger "Important"
    Push notification on `debug` mode doesn't work. Consider to test the push notification on `release` mode.

The FollowAnalytics SDK supports push notifications based on Google Cloud Messaging. To ensure notifications cannot  be caught by other applications than yours, please follow the steps below.

1. Add the following permissions to your manifest:

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

2. Add the GCM Receiver to your manifest

            <action android:name=""/>
            <!-- for Gingerbread GSF backward compat -->
            <action android:name=""/>
            <category android:name="%YOUR_APP_PACKAGE_NAME%"/>

!!! note "Notification icon and color"
    The SDK will use your app icon launcher as default notification icon.
    If you want a custom icon for your FollowAnalytics notification, add a `ic_fa_notification.png` file in your drawable folders (also, beware of the guidelines related to [icon's notification](
    If you wish to have a custom background color on your notifications, you can add a value to your `color.xml`:  `<color name="ic_fa_notification_color">#ff0000</color>`.

!!! note "Android 8.0 (Oreo) Version"
    Since this version, Notification system was refactored ([Google's documentation](
    With those changes, FollowAnalytics SDK uses this id for `NotificationChannel` object : `default_notification_fa`.

!!! note "Notifiations on wearables"
    Should you need to disable notifications on wearables, you can use the `FollowAnalytics.setGcmRegistrationEnabled(true or false)` method.

### Validate the configuration

The SDK has a **Validator** that will ensure that everything is properly configured. To check your configuration with the Validator use one of the following methods:

- by displaying the validator in a dialog:


Validator description

To know more about what the validator can check and how, please refer to its dedicated page.


Tags are used to send the data from the application to your platform. The FollowAnalytics SDK allows you to tag both events and attributes. If you are unsure about the difference, please refer to the corresponding FAQ entry.

Only data sent in release mode will be visible on dashboards

When your app runs in DEBUG mode or in a simulator, the data is automatically sent as development logs. As a consequence, the application data will not be processed, logs will not be displayed on the dashboards of your client platform. DEBUG logs can be checked using the method given in the FAQ section. See related entry in FAQ for more information on debug & release modes.

To ensure your tags are relevant and will end up empowering your team through FollowAnalytics, please read the Logging best practices entry in the FAQ section.

Limit the bandwidth for sending logs to FollowAnalytics

If your app runs in a context where bandwidth is limited, for instance on a wearable, you can set a minimum time between the SDK network calls using FollowAnalytics.setGcmRegistrationEnabled(true or false)

Tag events

Regular, native event logging

The SDK allows you to log events happening in your code. These are the two methods you can call on the SDK:

// Log an event without details
FollowAnalytics.logEvent(String eventName);
FollowAnalytics.logError(String errorName);

// Log an event with String details
FollowAnalytics.logEvent(String eventName, String details);
FollowAnalytics.logError(String errorName, String details);

// Log an event with Map details
// This is useful to pass pairs of key-values into a single event
FollowAnalytics.logEvent(String eventName, Map<String, String> details);
FollowAnalytics.logError(String errorName, Map<String, String> details);

Use the name of the event as the unique identifier of your tag.

Use the details to be more specific and add some context. The details field can either be a String or a Map, so that you can associated multiple key-values for additional context.

For instance, logging the appearance of a view could be done the following ways:

FollowAnalytics.logEvent("Product Page", "Product #42");
FollowAnalytics.logError("Error log", "This is an error!");

You may use a Map for the details field, the value of which must contain a String type.

HashMap<String, String> detailsMap = new HashMap<String, String>();
detailsMap.put("product_id", "42");
detailsMap.put("product_category", "Jeans");
FollowAnalytics.logEvent("Add product to cart", detailsMap);

If the parameters sent to these methods are over 60Kb, the method will refuse them, returning NO, and write a message in the console, if it is running in debug mode.

Tags can be modified from the FollowAnalytics UI

The client platform has a feature to rename the event and error tags. For more information, reach out to your Customer Success Manager or message support.

Logging from a web view

If your application contains web views, it is possible to tag events and errors from within your HTML/JS code. To do so, FollowAnalytics SDK Android has a class called FAWebView which allows the integration in three steps.

  1. Declare the FAWebView element into your <layout>.xml. For instance:
<LinearLayout xmlns:android=""
    android:layout_height="match_parent" >


  1. In the corresponding activity which uses the <layout>.xml layout, retrieve the ID associated with FAWebView element integrated in the layout. For instance:

FAWebView faWebView = (FAWebView) view.findViewById(;
3. Inject the HTML file/page to the FAWebView element by using the loadUrl method.

Notice that log events, user attributes and InApp properties can be used in the HTML file by using the following methods:

<a onclick="FollowAnalytics.logEvent('My event');">Send event without detail</a>
<a onclick="FollowAnalytics.logEvent('My event', 'My event details');">Send event with detail</a>
<a onclick="FollowAnalytics.logError('fromWebView without detail');">Send error without detail</a>
<a onclick="FollowAnalytics.logError('fromWebView with detail','Error detail');">Send error with detail</a>
- User Attributes:

html <div class="button" onclick="FollowAnalytics.UserAttributes.setFirstName('Isaac');">Set first name</div><br> <div class="button" onclick="FollowAnalytics.UserAttributes.setLastName('Newton');">Set last name</div><br> <div class="button" onclick="FollowAnalytics.UserAttributes.setEmail('');">Set email</div><br> <div class="button" onclick="FollowAnalytics.getDeviceId(displayDeviceID);">Get Device ID</div><br> - InApp properties:

<div class="button" onclick="FollowAnalytics.InApp.pauseCampaignDisplay();">Pause Campaign</div><br>
<div class="button" onclick="FollowAnalytics.InApp.resumeCampaignDisplay();">Resume Campaign</div><br>
Make sure to test if FollowAnalytics object exists with if (typeof FollowAnalytics !== 'undefined'). This way, you can reuse the exact same HTML code for your mobile web site without impact.

This feature limited to Android 4.2 and above

Logging from web view is a feature that is only activated for Android versions above 4.2 "Jelly Bean" (API Version >= 17) in order to prevent a security flaw in Google's Android SDK. You may find more details here in the documentation provided by Android.

User ID and attributes

You don't need a user ID to set attributes

Attributes are tied to the device when no user ID is provided. If a user ID is set, a profile is created and can be shared across apps.

In both cases, attributes can be used in segments and campaigns to target users.

User ID

When the user signs in somewhere in your app, specify their identifier to the SDK. This way, you will be able to relate any event to a specific user (this is particularly useful for crashes). We recommend you link your users between FollowAnalytics and your CRM, or any other analytics solution you have.

This identifier is unique. It can be an e-mail address, internal client identifier, phone number, or anything else that uniquely ties your customers to you.

To register the user identifier, use:

FollowAnalytics.setUserId(String UserId);
To remove the user identifier (for example in case of a sign out) use the following method:


Predefined attributes

The SDK allows you to set values for both custom and predefined attributes.

Predefined attributes are attributes that will be attached to default fields on your user profiles. FollowAnalytics SDK has the following properties for predefined attributes:

setLastName(String lastName);
setFirstName(String firstName);
setRegion(String region);
setCountry(String country);
setCity(String city);
setCountry(String country);
setEmail(String email);

For example, to set user Joe's city to "Paris", you would proceed as follows:


Custom attributes

Set a custom attribute

To set your custom attributes, you can use methods that are adapted for each type: setInt, setString,setBoolean, setDate, setDateTime and setDouble.

For example, to set the user's job:

FollowAnalytics.UserAttributes.setString("key_job", "Taxi driver");
Delete a custom attribute value

You can delete the value of an attribute using its key. For example, to delete the user's job:

Set of attributes

You can add or remove an item to or from a set of attributes.

To add an item:

To remove an item:

FollowAnalytics.UserAttributes.removeFromSet("fruits","lemon"); // Removes "lemon" from set of fruits.
And to clear a set:

FollowAnalytics.UserAttributes.clearSet("fruits");  #Removes all the items from the set.
For further information, refer to the SDK header file.

Always double check your custom attribute types in the SOR

When a value for an attribute is received by the server, the attribute is declared with the type of the value. For example if a type of a value is a boolean, then the server will remember the attribute type as boolean.

Therefore, if you change the type of an attribute in your application, values will be rejected by the server. Please ensure the type of the attribute match in the profile data section of system of records (SOR).

Opt-Out Analytics

Deprecated methods since version 5.4.0

Be sure to update the next methods : setCollectLogsAuthorization(boolean authorized), setCollectLocationLogsAuthorization(boolean authorized), canCollectLocationLogs(), canCollectLogs() with the appropriated methods available and explained below.

The SDK can be configured to no longer gather and track analytics.

By default, FollowAnalytics SDK is opt-in (configurable), where one can chose later to opt-out.

Once opted-out no further analytics events are collected. Data already collected - before being opted-out - are still sent to FollowAnalytics as usual. The opt-in state is persisted between restarts (unless the user clear the cache from the application settings).

Once opted-out the following events are neither collected nor sent:

None of the data is stored in the phone. The final outcome is that no new analytics sessions are generated and sent to the server.

The rest of the product features will continue to work as usual (eg. push notifications registration, campaigns etc.) with the following limitations:

The following configuration is available for the opt-out analytics feature :

Configuration setup

FollowAnalytics SDK gives you the possibility to set the default of opt-in policy at initialisation.

As a reminder, FollowAnalytics SDK is opt-in by default. In order to achieve this, create a class that extends to FollowAnalytics.Configuration and override the method getOptInAnalyticsDefault() by setting the default value for the opt-in state.

import com.followanalytics.FollowAnalytics;

public class Configuration extends FollowAnalytics.Configuration {
    public boolean getOptInAnalyticsDefault() {
        return false; //<- this method returns false which is equivalent to opt-out

Finally, add a meta-data tag under the application tag to your android manifest. The value of android:name must be identical as com.followanalytics.configuration and the value of android:value is the path of the configuration class:


For instance:

    android:value=""/> <!-- this is the path of the Configuration class created-->

Now, FollowAnalytics SDK will start by default with the value associated to the method of the configured class created for the opt-out analytics.

The customised configuration class is only used for the default value of the opt-in state. The runtime opt-in has the final say about if logs are collected.

#### Opt-in state

At runtime, FollowAnalytics SDK uses the value returned by `FollowAnalytics.getOptInAnalytics()` to decide log collection. The default value of this property is explained in the previous subsection. Once changed, the new value is saved in to persistent memory in order to persist it between restarts.

If you want to change the value of the opt-in state at runtime, use the `setOptInAnalytics` method:

FollowAnalytics.setOptInAnalytics(boolean state); // <- state set to true is equal to opt-in, however state set to false is equal to opt-out

In order to retrieve the value of the opt-in state that FollowAnalytics SDK is handling at runtime, use the getOptInAnalytics method:


Advanced Use Cases

Deep-linking: URL, Parameters

Campaigns created through FollowAnalytics allow to deep link to content in your application or to others application. You can use either an App Link, or use a customized key-value parameters that are forwarded to your code.

SDK behaviour

The SDK manages automatically App-Links. Be sure to follow the google documentation for internal deep-links of the application.

The SDK introduced the possibility to use direct App Links like twitter://messages, which will send you to the corresponding screen inside of the Twitter application.

You're able to access the functionality by enabling the Deep Linking switch in our UI, when creating a campaign. There you'll find the field App Link that expects you to enter these type of url schemas. It can either be an URL Schema to an external application or for your own application.

If you don't want to implement it as google's recommendation, please follow the content below.

In FollowAnalytics campaigns through our platform, you can specify deep-linking parameters, e.g. in your push messages or for in-app button actions.

These parameters are given to the developer's code by the SDK. It is then up to the developer to implement the deep-linking in the app (specific path of screens, format of the arguments, etc.).

To obtain these parameters, you can extend the FollowAnalytics.DefaultMessageHandler class, like in the following example:

public class CustomMessageHandler extends FollowAnalytics.DefaultMessageHandler {

     * This method is executed when no App Link was set but, instead, only key-values were set.
     public void onPushMessageClicked(Context context, Map<String, String> data) {
         String value1 = data.get("a_custom_param_key");
         if(value1 !=null && data.get(value1).equals("a_custom_param_value_expected")){
             //Execute the code for the customized deep-link with a key : "a_custom_param_key" and a value : "a_custom_param_value_expected"
             Intent intent = new Intent(context, SpecificActivity.class);
            //Let the SDK handle the notification
            super.onPushMessageClicked(context, data);


     * This method is executed when an App Link was, at least, set (through the clients portal).
         public void onPushMessageClicked(Context context, String url, Map<String, String> data) {
            //Do something with the url

     public void onInAppMessageClicked(Context context, String buttonText, Map<String, String> data) {
         // Same as the above method, but from a in-app message!

If you chose to define a custom MessageHandler, you must declare it in your Application manifest as meta-data:

    <meta-data android:name="com.followanalytics.deeplinking.handler" android:value="fully_qualified_identifier_to_your_class"/>

Through the key value format, FollowAnalytics supports both standardized deep-linking (by defining the key you'll always use to give the path), and more direct parameter passing for simpler use cases integrations.

Regular deep-linking is usually implemented using a Router, that will handle the URL called on the app and translate it into the display of the right page, with the right content.

Control over campaigns

Pausing in-app campaigns

You can prevent in-app campaigns from being displayed on certain views of your app. This can be useful when you are displaying a media content, or if the topmost screen is only shown for a few seconds, for instance.

Any campaign supposed to be displayed when the mechanism is paused is stacked and shown as soon as it is resumed.

To tell the SDK to prevent the display of rich campaigns, and then to activate it back, use the following methods:

FollowAnalytics.InApp.pauseCampaignDisplay();  # will pause campaign display
FollowAnalytics.InApp.resumeCampaignDisplay();  # will resume campaign display

Tip: use view lifecycle methods

If you want to prevent the display on a given page, you can call the pause method when an intent starts, and the resume one when it stops.

Tip: only allow display in some places of the app

You can use these methods the other way around, by pausing all campaigns when the app starts, right after the SDK is initialized, and then resuming where the messages can be shown. Just pause again when the user leaves that "safe" area of your app.

Custom push notifications

If you need to customize your push notifications, you have to extend this class FollowAnalytics.DefaultMessageHandler and override the method onPushMessageNotificationBuilding(...) to the class that you created.

For example:

public class FollowPushHandler extends FollowAnalytics.DefaultMessageHandler {

    public void onPushMessageNotificationBuilding(Context context, NotificationCompat.Builder notificationBuilder,  FollowAnalytics.Message message) {
       //customize the notification

Then, add to the manifest file the path of the class that extends FollowAnalytics.DefaultMessageHandler as a meta-data tag under the aplication tag. For example:

<meta-data android:name=“com.followanalytics.deeplinking.handler” android:value=“the_full_path_of_your_message_FollowPushHandler”/>

Now that everything is set up, customize your notification under the method onPushMessageNotificationBuilding.

An example of adding buttons to the notification is available below.

    public void onPushMessageNotificationBuilding(Context context, NotificationCompat.Builder notificationBuilder, FollowAnalytics.Message message) {
    super.onPushMessageNotificationBuilding(context, notificationBuilder, message);
    if (message.getCategory().equalsIgnoreCase("social")) {
        PendingIntent pendingIntentActions1 = null; //your pendingIntent when user click on button like
        PendingIntent pendingIntentActions2 =  null; //your pendingIntent when user click on button comment
        NotificationCompat.Action action1 = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_send, "Like", pendingIntentActions1).build();
        NotificationCompat.Action action2 = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_help, "comment", pendingIntentActions2).build();

Custom handling of rich campaigns

Rich campaigns can be handled directly by the application code, instead of being showed automatically by the SDK. The behaviour is defined when creating the campaign, using the "automatically display content" switch.

For campaigns where the content is not handled by FollowAnalytics, you will need to extend and declare it in your AndroidManifest.xml. You'll need to use an intent-filter on BROADCAST_RICH_CAMPAIGNS_ACTION. For instance:

<receiver android:name=".RichCampaignDataReceiver" >

Where %YOUR_APP_PACKAGE_NAME% is your application package name.

The method onRichCampaignDataReceived must be overridden. Rich campaign parameters are provided as method arguments:

Enable message archiving

FollowAnalytics SDK allows you to store all campaigns and push notifications received by your application, making them available to your custom usage. To enable this feature, add the following line in the application manifest under the tag application

Firebase integration

If you use Firebase to manage your push notifications, FollowAnalytics SDK doesn't handle it with the latest version.

FollowAnalytics SDK and Firebase

The next major version of FollowAnalytics will handle Firebase services.

However, you can use a Firebase implementation (your own) and GCM implementation (from FollowAnalytics SDK) independently with no communication between FA SDK and FCM services.

Working with multiple GCMs

If you are already using GCM in your application, you will have to check the sender of each notification, as it can now come from different providers (e.g. you and FollowAnalytics).


This tutorial assumes that GCM is already implemented in your application. Skip to the next section f you don't already have a GCM implementation. FollowAnalytics SDK adds the GCM push notification automatically.

Before beggining the implementation, let's summarize the objectives and ideas that the application will do with multiple GCM.

  1. The application must retrieve the token (push notification) independently of any sender ID (multiple sender ID) and send it, optionally, to a server.

  2. The application will be able to receive one or mutiple push notifications, and treat them separatly.

Manifest application

  1. Remove any GCM Receiver implemented in your project (FollowAnalytics SDK will implement it automatically). For instance :
<receiver android:name=""
        <action android:name="" />
        <category android:name= "com.followanalytics.sdk.azme.integration" />
  1. Implement a Service that will receive all the push notifications. For instance :
        <action android:name=""/>
  1. Make sure that GCM permissions are implemented.
<permission android:name="<PACKAGE_NAME>.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="<PACKAGE_NAME>.permission.C2D_MESSAGE"/>
  1. Finally, make sure that you are able to retrieve the token with different providers by declaring the correct Service. For instance, this is a Service that retrieves the token for Azure push notification system:
<service android:name=".azure.MyInstanceIDService" android:exported="false">
        <action android:name=""/>
// This service retrieves the token also

Gradle application

  1. Remove the plugin for GCM if available :
//apply plugin: ''
  1. Remove the dependencies from GCM (FollowAnalytics SDK already adds it).
//implementation ''

Project, Java class implementation

Now that we settled the Manifest and Gradle files, let's implement the classes.

  1. Implement the Service extended to GcmListenerService (declared previously in the manifest). For instance :
public class OtherExternalPushService extends GcmListenerService{
    public static final int NOTIFICATION_ID = 123;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder mBuilder;

    public OtherExternalPushService() {

    public void onMessageReceived(String from, Bundle data) {
        super.onMessageReceived(from, data);

        //Treat every sender Id that the application might have (for instance, this is a push notification from Azure Microsoft)

            //Do whatever you need to do for this message (parse the message, send to the notification manager, etc...)

            mNotificationManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //----------CREATE CHANNEL
                // The id of the channel.
                String id = "my_channel_01";
                // The user-visible name of the channel.
                CharSequence name = "Azure Channel";
                // The user-visible description of the channel.«
                String description = "This is a description";
                int importance = NotificationManager.IMPORTANCE_HIGH;
                NotificationChannel mChannel = new NotificationChannel(id, name, importance);
                // Configure the notification channel.
                // Sets the notification light color for notifications posted to this
                // channel, if the device supports this feature.
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                //----------END CREATE CHANNEL

                mBuilder =
                        new NotificationCompat.Builder(this.getApplicationContext(), id)
                                .setContentTitle("Notification Hub Demo Azure")
                                .setStyle(new NotificationCompat.BigTextStyle()
                mBuilder =
                        new NotificationCompat.Builder(this.getApplicationContext())
                                .setContentTitle("Notification Hub Demo Azure")
                                .setStyle(new NotificationCompat.BigTextStyle()
            mNotificationManager.notify(NOTIFICATION_ID+(new Random().nextInt()),;
            // As there is no more sender id to treat, this is a FollowAnalytics message, let's inject the message to FollowAnalytics SDK, by using the following function

            Log.d("OtherExternalPushServi","Sender id :"+from);
            FollowAnalytics.processFollowAnalyticsPush(this, data.getString(PushManager.BUNDLE_KEY_MESSAGE));

Now that everything is implemented, you can use/test push notifications with multiple GCM.

An example of a project with multiple GCM is available here : Github



If you need to obfuscate and/or shrink your app before Google Play publication, be sure you protect the FollowAnalytics SDK, otherwise logs won't be sent.

Here is the ProGuard configuration:

-keep class com.followanalytics.** { *; }
-keep interface** { *; }