Android

Follow

This document will guide you through the process of Countly SDK installation and it applies to version 20.04.

Minimum Android version

The Countly Android SDK requires a minimum of Android 4.0 (API Level 14).

Older documentation

To access the documentation for version 19.09 and older, click here.

Adding the Countly SDK

You can use both Android Studio and Eclipse to add the Countly SDK to your project.

Adding via Android Studio

You may use the default JCenter repository to download the SDK package. If it is not included in your project, include it as follows:

buildscript {
    repositories {
        jcenter()
    }
}

You can also add the Bintray Maven repository:

buildscript {
    repositories {
        maven {
            url  "http://dl.bintray.com/countly/maven"
        }
    }
}

Now, add the Countly SDK dependency (use the latest SDK version currently available from gradle, not specifically the one shown in the sample below).

dependencies {
		compile 'ly.count.android:sdk:20.04.2'
}

Adding the SDK via Eclipse

Eclipse users can download JARs - sdk.jar from Bintray Release files.

Another option for Eclipse users is to use sources instead of jars. To do so, simply create 2 packages and put sources from the Github repository into the corresponding packages.

Generate personalized SDK code snippets

The Countly Code Generator may be used to generate SDK custom code snippets easily and quickly. You may provide values for your custom event or user profile or simply start with basic integration. This service will also generate the necessary code for you to use in your favorite IDE (e.g. Android Studio).

Component Package name Path at Github repo
Countly SDK ly.count.android.sdk countly-sdk-android/sdk/src/main/java/ly/count/android/sdk
OpenUDID org.openudid countly-sdk-android/sdk/src/main/java/org/openudid

Setting up the Countly SDK

Before you can use any functionality, you have to initiate the SDK. That is done either in your Application subclass (preferred), or from your main activity onCreate method.

The shortest way to initiate the SDK is with this call:

Countly.sharedInstance().init(new CountlyConfig(this, COUNTLY_APP_KEY, COUNTLY_SERVER_URL));

It is there that you provide the Android context, your appKey, and your Countly server URL.

To configure the SDK during init, a config object called "CountlyConfig" is used. Configuration is done by creating such an object and then calling it's provided function calls to enable functionality you need. Afterward that config object is provided to the "init" method.

Providing the application key

Also called "appKey" as shorthand. The application key is used to identify for which application this information is tracked. You receive this value by creating a new application in your Countly dashboard and accessing it in its application management screen.

Note: Ensure you are using the App Key (found under Management -> Applications) and not the API Key. Entering the API Key will not work.

Providing the server URL

If you are using Countly Enterprise Edition trial servers, use https://try.count.ly, https://us-try.count.ly or https://asia-try.count.ly It is basically the domain from which you are accessing your trial dashboard.

If you use both Community Edition and Enterprise Edition, use your own domain name or IP address, such as https://example.com or https://IP (if SSL has been set up).

Enabling logging

The first thing you should do while integrating our SDK is enabling logging. If logging is enabled, then our SDK will print out debug messages about its internal state and encountered problems. Those messages may be screened in logcat and may use Androids internal log calls.

Call setLoggingEnabled on the config class to enable logging:

CountlyConfig config = (new CountlyConfig(appC, COUNTLY_APP_KEY, COUNTLY_SERVER_URL));
config.setLoggingEnabled(true);

Device ID

All tracked information is tied to a "device ID". A device ID is a unique identifier for your users.

One of the first things you'll need to decide is which device ID generation strategy to use. There are several options defined below:

The easiest method is letting the Countly SDK seamlessly handle the device ID on its own. You may then use the following calls. It will use the default strategy, which currently is OpenUDID (don't forget to finish setting up OpenUDID as described below).

CountlyConfig config = (new CountlyConfig(appC, COUNTLY_APP_KEY, COUNTLY_SERVER_URL));
Countly.sharedInstance().init(config);

You may specify the device ID by yourself if you have one (it has to be unique for each device). It may be an email or some other internal ID used by your other systems.

CountlyConfig config = (new CountlyConfig(appC, COUNTLY_APP_KEY, COUNTLY_SERVER_URL));
config.setDeviceId("YOUR_DEVICE_ID");
Countly.sharedInstance().init(config);

You may rely on the Google Advertising ID for device ID generation.

CountlyConfig config = (new CountlyConfig(appC, COUNTLY_APP_KEY, COUNTLY_SERVER_URL));
config.setIdMode(DeviceId.Type.ADVERTISING_ID);
Countly.sharedInstance().init(config);

In regard to the Google Advertising ID, please ensure you have Google Play services 4.0+ included in your project. Also, note that the Advertising ID silently falls back to OpenUDID in case it fails to get the Advertising ID when Google Play services are not available on a device.

You may also explicitly use OpenUDID:

CountlyConfig config = (new CountlyConfig(appC, COUNTLY_APP_KEY, COUNTLY_SERVER_URL));
config.setIdMode(DeviceId.Type.OPEN_UDID);
Countly.sharedInstance().init(config);

In the case of OpenUDID, you'll need to include the following declaration into your AndroidManifest.xml:

<service android:name="org.openudid.OpenUDID_service">
    <intent-filter>
        <action android:name="org.openudid.GETUDID" />
    </intent-filter>
</service>

Adding callbacks

After the Countly.sharedInstance().init(...)call, you'll need to add the following calls to all your activities:

  • Call Countly.sharedInstance().onStart(this) in onStart, where this is a link to the current Activity.
  • Call Countly.sharedInstance().onStop() in onStop.
  • Call Countly.sharedInstance().onConfigurationChanged(newConfig) in onConfigurationChanged if you want to track orientation changes.

If the "onStart" and "onStop" calls are not added, some functionalities will not work, e.g. automatic sessions will not be tracked. The Countly "onStart" has to be called in the activities "onStart" function, it cannot be called in "onCreate" or in any other place, otherwise, the application will receive exceptions.

Adding permissions

Additionally, ensure the INTERNET and ACCESS_NETWORK_STATE permissions are set if there aren’t any in your manifest file. Those calls should look something like this:

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

Sample application

You can take a look at our sample application in the Github repo. It should show how most of the functionalities can be used.

Crash reporting

The Countly SDK for Android has the ability to collect crash reports, which you may examine and resolve later on the server.

Enabling automatic crash reporting

To enable automatic crash reporting, call the following function on the config object. After init, this will enable crash reporting, which will automatically catch uncaught Java exceptions. They will be sent to the dashboard once the app is launched again and the SDK is initiated.

config.enableCrashReporting();

Adding a custom key-value segment to a crash report

You may add a key/value segment to crash reports. For example, you could set which specific library or framework version you used in your app. You may then figure out if there is any correlation between the specific library or another segment and the crash reports.

Use the following function for this purpose:

config.setCustomCrashSegment(Map<String, String> segments)

Accessing crash-related functionality

In the SDK all crash-related functionality can be browsed from the returned interface on:

Countly.sharedInstance().crashes()

Adding breadcrumbs

Throughout your app you can leave crash breadcrumbs which would describe previous steps that were taken in your app before the crash. After a crash happens, they will be sent together with the crash report.

Following the command adds crash breadcrumb:

Countly.sharedInstance().crashes().addCrashBreadcrumb(String record) 

Logging handled exceptions

You might catch an exception or similar error during your app’s runtime.

You may also log these handled exceptions to monitor how and when they are happening with the following command:

Countly.sharedInstance().crashes().recordHandledException(Exception exception);

If you have handled an exception and it turns out to be fatal to your app, you may use this call:

Countly.sharedInstance().crashes().recordUnhandledException(Exception exception);

Recording all threads

If you would like to record the state of all other threads during an uncaught exception or during the recording of a handled exception, you can call this during init:

config.setRecordAllThreadsWithCrash();

Crash filtering

There might be cases where a crash could contain sensitive information. For such situations, there is a crash filtering option. You can provide a callback which will be called every time a crash is recorded. It gets the string value of the crash, which would be sent to the server, and should return "true" if the crash should not be sent to the server:

config.setCrashFilterCallback(new CrashFilterCallback() {
@Override
public boolean filterCrash(String crash) {
//returns true if the crash should be ignored
return crash.contains("secret");
}
})

Custom Events

Setting up custom events

custom event is any type of action that you can send to a Countly instance, e.g. purchases, changed settings, view enabled, and so on. This way it's possible to get much more information from your application compared to what is sent from the Android SDK to the Countly instance by default.

Data passed should be in UTF-8

All data passed to the Countly server via the SDK or API should be in UTF-8.

Accessing event-related functionality

In the SDK all custom event-related functionality can be browsed from the returned interface on:

Countly.sharedInstance().events()

Segmentation

When providing segmentation for events, the only valid data types are: "String", "Integer", "Double" and "Boolean". All other types will be ignored.

Custom event usage examples

We have provided an example of recording a purchase event below. Here is a quick summary of the information with which each usage will provide us:

  • Usage 1: how many times the purchase event occurred.
  • Usage 2: how many times the purchase event occurred + the total amount of those purchases.
  • Usage 3: how many times the purchase event occurred + from which countries and application versions those purchases were made.
  • Usage 4: how many times the purchase event occurred + the total amount, both of which are also available, segmented into countries and application versions.
  • Usage 5: how many times the purchase event occurred + the total amount, both of which are also available, segmented into countries and application versions + the total duration of those events.

1. Event key and count

Countly.sharedInstance().events().recordEvent("purchase", 1);

2. Event key, count, and sum

Countly.sharedInstance().events().recordEvent("purchase", 1, 0.99);

3. Event key and count with segmentation(s)

HashMap<String, String> segmentation = new HashMap<String, Object>();
segmentation.put("country", "Germany");
segmentation.put("app_version", "1.0");

Countly.sharedInstance().events().recordEvent("purchase", segmentation, 1);

4. Event key, count, and sum with segmentation(s)

HashMap<String, String> segmentation = new HashMap<String, Object>();
segmentation.put("country", "Germany");
segmentation.put("app_version", "1.0");

Countly.sharedInstance().events().recordEvent("purchase", segmentation, 1, 0.99);

5. Event key, count, sum, and duration with segmentation(s)

HashMap<String, String> segmentation = new HashMap<String, Object>();
segmentation.put("country", "Germany");
segmentation.put("app_version", "1.0");

Countly.sharedInstance().events().recordEvent("purchase", segmentation, 1, 0.99, 60);

Those are only a few examples of what you can do with custom events. You may extend those examples and use Country, app_version, game_level, time_of_day, and any other segmentation that will provide you with valuable insights.

Timed events

It's possible to create timed events by defining a start and a stop moment.

String eventName = "Custom event";

//start some event
Countly.sharedInstance().events().startEvent(eventName);
//wait some time

//end the event 
Countly.sharedInstance().events().endEvent(eventName);

You may also provide additional information when ending an event. However, in that case, you have to provide the segmentation, count, and sum. The default values for those are "null", 1 and 0.

String eventName = "Custom event";

//start some event
Countly.sharedInstance().events().startEvent(eventName);
//wait some time

Map<String, String> segmentation = new HashMap<>();
segmentation.put("wall", "orange");

//end the event while also providing segmentation information, count and sum
Countly.sharedInstance().events().endEvent(eventName, segmentation, 4, 34);

You may cancel the started timed event in case it is not relevant anymore:

//start some event
Countly.sharedInstance().events().startEvent(eventName); //wait some time //cancel the event Countly.sharedInstance().events().cancelEvent(eventName);

Record past events

In the previous examples, the event creation time is recorded once the event is created.

In some use cases, you might want to cache and store events by yourself and then record them in the SDK with a past timestamp. The timestamp is a Unix timestamp stored in milliseconds. For that you would use:

Countly.sharedInstance().events().recordPastEvent(key, segmentation, count, sum, dur, timestamp)

View tracking

Automatic view tracking 

View tracking is a means to report every screen view to the Countly dashboard. In order to enable automatic view tracking, call:

config.setViewTracking(true);

The tracked views will use the full activity names which include their package name. It would look similar to "com.my.company.activityname".

It is possible to use short view names that make use of the simple activity name. This would look like "activityname". To use this functionality, call this before calling init:

config.setAutoTrackingUseShortName(true);

Automatic view segmentation

It's possible to provide custom segmentation that will be set to all automatically recorded views:

Map<String, Object> automaticViewSegmentation = new HashMap<>();
automaticViewSegmentation.put("One", 2);
automaticViewSegmentation.put("Three", 4.44d);
automaticViewSegmentation.put("Five", "Six");

config.setAutomaticViewSegmentation(automaticViewSegmentation);

Tracking orientation changes

To record your applications orientation changes, you need to enable it on your init object like:

config.setTrackOrientationChanges(true);

You need to add this to all of your activities where you want to track orientation:

android:configChanges="orientation|screenSize"

Inside of your manifest, it would look something like this:

<activity
android:name=".ActivityExample"
android:label="@string/activity_name"
android:configChanges="orientation|screenSize">
</activity>

To finish your setup for orientation tracking, you need to set up the android callback for "onConfigurationChanged". In those you would have to call "Countly.sharedInstance().onConfigurationChanged(newConfig)". You may set it up similarly to this:

@Override
public void onConfigurationChanged (Configuration newConfig){
super.onConfigurationChanged(newConfig);
Countly.sharedInstance().onConfigurationChanged(newConfig);
}

Accessing view related functionality

In the SDK all view related functionality can be browsed from the returned interface on:

Countly.sharedInstance().views()

Manual view recording

You may track custom views with the following code snippet as well:

Countly.sharedInstance().views().recordView("View name");

While manually tracking views, you may add your custom segmentation to them like this:

Map<String, Object> viewSegmentation = new HashMap<>();

viewSegmentation.put("Cats", 123);
viewSegmentation.put("Moons", 9.98d);
viewSegmentation.put("Moose", "Deer");

Countly.sharedInstance().views().recordView("Better view", viewSegmentation);

To review the resulting data, open the dashboard and go to Analytics > Views. For more information on how to use view tracking data to its fullest potential, click here.

Changing a device ID

When the SDK is initialized the first time and no custom device ID is provided, a random one will be generated. For most use cases that is enough as it provides a random identity to one of your apps users.

To solve other potential use cases, we provide 3 ways to handle your device id:

  • Changing device ID with merge
  • Changing device ID without merge
  • Using a temporary ID

Changing device ID with and without merge

In case your application authenticates users, you might want to change the ID to the one in your backend after he has logged in. This helps you identify a specific user with a specific ID on a device he logs in, and the same scenario can also be used in cases this user logs in using a different way (e.g another tablet, another mobile phone, or web). In this case, any data stored in your Countly server database associated with the current device ID will be transferred (merged) into user profile with device id you specified in the following method call:

Countly.sharedInstance().changeDeviceIdWithMerge("new device ID")

In other circumstances, you might want to track information about another separate user that starts using your app (changing apps account), or your app enters a state where you no longer can verify the identity of the current user (user logs out). In that case, you can change the current device ID to a new one without merging their data. You would call:

Countly.sharedInstance().changeDeviceIdWithoutMerge(DeviceId.Type.OPEN_UDID, null)

Doing it this way, will not merge the previously acquired data with the new id.

You can also set Advertising ID as your device ID generation strategy or even supply your own string with DeviceId.Type.DEVELOPER_SPECIFIED type.

Do note that every time you change your deviceId without a merge, it will be interpreted as a new user. Therefore implementing id management in a bad way could inflate the users count by quite a lot.

The worst would be to not merge device id on login and generate a new random ID on logout. This way, by repeatedly logging in and out one could generate an infinite amount of users.

So the recommendation is (depending on your apps use case) either to keep the same deviceId even if the user logs out or to have a predetermined deviceId for when the users on the specific device logs out. The first method would not inflate the user count, but not viable for single device, multiple users use case. The second would create a "multiuser" id for every device and possibly slightly inflate the user count.

Temporary device ID

In the previous ID management approaches, data is still sent to your server, but it adds user inflation risk if badly managed. The use of a temporary ID can help to mitigate such problems.

During app start or any time after init, you can enter a temporary device ID mode. All requests will be stored internally and not sent to your server until a new device ID is provided. In that case, all events created during this temporary ID mode will be associated with the new device ID and sent to the server.

To enable this mode during init, you would call this on your config object before init:

countlyConfig.enableTemporaryDeviceIdMode();

To enable temporary id after init, you would call:

Countly.sharedInstance().enableTemporaryIdMode();

To exit temporary id mode, you would call either "changeDeviceIdWithoutMerge" or "changeDeviceIdWithMerge" or init the SDK with a developer supplied device ID.

Retrieving the device id and its type

You may want to see what device id Countly is assigning for the specific device and what the source of that id is. For that, you may use the following calls. The id type is an enum with the possible values of: "DEVELOPER_SUPPLIED", "OPEN_UDID", "ADVERTISING_ID".

String usedId = Countly.sharedInstance().getDeviceID();
Type idType = Countly.sharedInstance().getDeviceIDType();

User location

While integrating this SDK into your application, you might want to track your user location. You could use this information to better know your app’s user base or to send them tailored push notifications based on their coordinates. There are 4 fields that may be provided:

  • Country code in the two-letter, ISO standard
  • City name (must be set together with the country code)
  • Latitude and longitude values separated by a comma, e.g. "56.42345,123.45325"
  • Your user’s IP address

During init you can either disable location:

config.setDisableLocation();

or set location info that will be sent during the start of the user session:

config.setLocation(countryCode, city, gpsCoordinates, ipAddress);

Note that the ipAddress will only be updated if set through the init process.

//set user location
String countryCode = "us";
String city = "Houston";
String latitude = "29.634933";
String longitude = "-95.220255";
String ipAddress = null;

Countly.sharedInstance().setLocation(countryCode, city, latitude + "," + longitude, ipAddress);

When those values are set, a separate request will be created to send them sent. Except for ip address, because Countly Server processes IP address only when starting a session.

If you don't want to set specific fields, set them to null.

Users might want to opt-out of location tracking. To do so, call:

//disable location
Countly.sharedInstance().disableLocation();

This action will erase the cached location data from the device and the server.

Parameter Tampering Protection

You may set the optional salt to be used for calculating the checksum of requested data which will be sent with each request, using the &checksum field. You will need to set exactly the same salt on the Countly server. If the salt on the Countly server is set, all requests would be checked for the validity of the &checksum field before being processed.

Countly.sharedInstance().enableParameterTamperingProtection("salt");

Using Proguard

Proguard obfuscates the OpenUDID & Countly Messaging classes. If you use OpenUDID or Countly Messaging in your application, you will need to add the following lines to your Proguard rules file:

-keep class org.openudid.** { *; }
-keep class ly.count.android.sdk.** { *; }

More info can be found here.

Attribution analytics & install campaigns

Countly Attribution Analytics allows you to measure your marketing campaign performance by attributing installs from specific campaigns. This feature is available for the Enterprise Edition.

We highly recommend allowing Countly to listen to the INSTALL_REFERRER intent in order to receive more precise attribution on Android, something you may do by adding the following XML code to your AndroidManifest.xml file inside the application tag.

<receiver android:name="ly.count.android.sdk.ReferrerReceiver" android:exported="true">
	<intent-filter>
		<action android:name="com.android.vending.INSTALL_REFERRER" />
	</intent-filter>
</receiver>

Note that modifying your AndroidManifest.xml file is the only thing you would need to do in order to start receiving data from your campaigns via the Attribution Analytics plugin.

For more information about how to set up your campaigns, please review this documentation.

Receiving user feedback

There are two ways of receiving feedback from your users: star-rating dialog and the feedback widget.

Star-rating dialog allows users to give feedback as a rating from 1 to 5. The feedback widget allows users to rate using the same 1 to 5 rating system as well as leave a text comment.

Feedback widget

The feedback widget shows a server configured widget to your user devices.

It's possible to configure any of the shown text fields and replace them with a custom string of your choice.

In addition to a 1 to 5 rating, users may also leave a text comment along with an email, should the user desire to be contacted by the app developer.

Trying to show the rating widget is a single call, but, in reality, it’s a two-step process. Before it is displayed, the SDK attempts to contact the server to receive more information regarding the dialog. Therefore, a network connection is needed.

You may try to show the widget after you have initialized the SDK. To do so, you will first need to receive the widget ID from your server:

Using the widget ID, you may call the function to show the widget popup:

String widgetId = "xxxxx";
String closeButtonText = "Close";
Countly.sharedInstance().showFeedbackPopup(widgetId, closeButtonText, activity, new CountlyStarRating.FeedbackRatingCallback() {
  @Override
  public void callback(String error) {
    if(error != null){
      Toast.makeText(activity, "Encountered error while showing feedback dialog: [" + error + "]", Toast.LENGTH_LONG).show();
    }
  }
});

Star-rating dialog

Star-rating integration provides a dialog for receiving users’ feedback about the application. It contains a title, a simple message explaining its uses, a 1-to-5-star meter for receiving users’ ratings, and a dismiss button in case the user does not want to give a rating.

This star rating has nothing to do with the Google Play Store ratings and reviews. It is just for getting brief feedback from users to be displayed on the Countly dashboard. If the user dismisses the star-rating dialog without providing a rating, the event will not be recorded.

The star-rating dialog's title, message, and dismiss button text may be customized either through the init function or the SetStarRatingDialogTexts function. If you don't want to override one of those values, set it to "null".

//set it through the init function
Countly.sharedInstance().init(context, serverURL, appKey, deviceID, idMode, starRatingLimit, starRatingCallback, "Custom title", "Custom message", "Custom dismiss button text");

//Use the designated function:
Countly.sharedInstance().setStarRatingDialogTexts(context, "Custom title", "Custom message", "Custom dismiss button text");

The star-rating dialog can be displayed in 2 ways:

  • Manually by the developer
  • Automatically, depending on the session count

In order to display the star-rating dialog manually, you must call the ShowStarRating function. Optionally, you may provide the callback functions. There is no limit on how many times the star-rating dialog may be displayed manually.

//show the star rating without a callback
Countly.sharedInstance().showStarRating(context, null);

//show the star rating with a callback
Countly.sharedInstance().showStarRating(context, callback)

The star-rating dialog will be displayed automatically when an application's session count reaches the specified limit, i.e. once for each new version of the application. This session count limit may be specified upon initial configuration or through the SetAutomaticStarRatingSessionLimit function. The default limit is 3. Once the star-rating dialog has been displayed automatically, it will not be displayed again, unless a new app version comes along.

You will need to pass the activity context during init in order to show the automatic star-rating dialog.

//set the rating limit through the init function
int starRatingLimit = 5;
Countly.sharedInstance().init(context, serverURL, appKey, deviceID, idMode, starRatingLimit, starRatingCallback, starRatingTextTitle, starRatingTextMessage, starRatingTextDismiss);

//set it through the designated function
Countly.sharedInstance().starRatingLimit(context, 5);

If you would like to enable the automatic star-rating function, use the SetIfStarRatingShownAutomatically function, it is disabled by default.

//enable automatic star rating
Countly.sharedInstance().setIfStarRatingShownAutomatically(true);

//disable automatic star rating
Countly.sharedInstance().setIfStarRatingShownAutomatically(false);

If you would like to have the star rating shown only once per app's lifetime and not for each new version, use the SetStarRatingDisableAskingForEachAppVersion function.

//disable star rating for each new version
Countly.sharedInstance().setStarRatingDisableAskingForEachAppVersion(true);

//enable star rating for each new version
Countly.sharedInstance().setStarRatingDisableAskingForEachAppVersion(false);

The star-rating callback provides functions for two events. OnRate is called when the user chooses a rating. OnDismiss is called when the user clicks the back button, clicks outside the dialog, or clicks the "Dismiss" button. The callback provided in the init function is only used when displaying the automatic star rating. Only the provided callback will be used for the manual star rating.

CountlyStarRating.RatingCallback callback = new CountlyStarRating.RatingCallback() {
    @Override
    public void OnRate(int rating) {
    	//the user rated the app
    }

    @Override
    public void OnDismiss() {
    	//the star rating dialog was dismissed
    }
};

Remote Config

Remote config allows you to modify how your app functions or looks by requesting key-value pairs from your Countly server. The returned values may be modified based on the user profile. For more details, please see the Remote Config documentation.

Automatic Remote Config download

There are two ways of acquiring remote config data: automatic download or manual request. Automatic remote config has been disabled by default and, therefore, without developer intervention, no remote config values will be requested.

Automatic value download happens when the SDK is initiated or when the device ID is changed. You have to call setRemoteConfigAutomaticDownload before init to enable it. As an optional value, you may provide a callback to be informed when the request is finished.

Countly.sharedInstance().setRemoteConfigAutomaticDownload(true, new RemoteConfig.RemoteConfigCallback() {
            @Override
            public void callback(String error) {
                if(error == null) {
                    Toast.makeText(activity, "Automatic remote config download has completed", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(activity, "Automatic remote config download encountered a problem, " + error, Toast.LENGTH_LONG).show();
                }
            }
        });
Countly.sharedInstance().init(appC, COUNTLY_SERVER_URL, COUNTLY_APP_KEY);

If the callback returns a non-null value, you can expect that the request failed and no values were updated.

When performing an automatic update, all locally stored values are replaced with the ones received (all locally stored values are deleted and replaced by new ones). It is possible that a previously valid key will return no value after an update.

Manual Remote Config download

There are three ways for manually requesting a remote config update: * Manually updating everything * Manually updating specific keys * Manually updating everything except specific keys.

Each of these requests also has a callback. If the callback returns a non-null value, the request will encounter an error and fail.

Functionally, the manual update for everything remoteConfigUpdate is the same as the automatic update - it replaces all stored values with the ones from the server (all locally stored values are deleted and replaced with new ones). The advantage is that you can make the request whenever it is desirable for you. It has a callback to let you know when it has finished.

Countly.sharedInstance().remoteConfigUpdate(new RemoteConfig.RemoteConfigCallback() {
            @Override
            public void callback(String error) {
                if(error == null) {
                    Toast.makeText(activity, "Update finished", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity, "Error: " + error, Toast.LENGTH_SHORT).show();
                }
            }
        });

Or you might only want to update specific key values. To do so, you will need to call updateRemoteConfigForKeysOnly with the list of keys you would like to be updated. That list is an array with the string values of those keys. It has a callback to let you know when the request has finished.

Countly.sharedInstance().updateRemoteConfigForKeysOnly(new String[]{"aa", "dd"}, new RemoteConfig.RemoteConfigCallback() {
            @Override
            public void callback(String error) {
                if(error == null) {
                    Toast.makeText(activity, "Update with inclusion finished", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity, "Error: " + error, Toast.LENGTH_SHORT).show();
                }
            }
        });

Or you might want to update all the values except a few defined keys. To do so,  call updateRemoteConfigExceptKeys. The key list is an array with string values of the keys. It has a callback to let you know when the request has finished.

Countly.sharedInstance().updateRemoteConfigExceptKeys(new String[]{"aa", "dd"}, new RemoteConfig.RemoteConfigCallback() {
            @Override
            public void callback(String error) {
                if (error == null) {
                    Toast.makeText(activity, "Update with exclusion finished", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity, "Error: " + error, Toast.LENGTH_SHORT).show();
                }
            }
        });

When making requests with an "inclusion" or "exclusion" array, if those arrays are empty or null, they will function the same as a simple manual request and will update all the values. This means it will also erase all keys not returned by the server.

Getting Remote Config values

To request a stored value, call getRemoteConfigValueForKey with the specified key. If it returns null then no value was found. The SDK has no knowledge of the returned value type, and therefore, it will return the Object . The developer then needs to cast it to the appropriate type. The returned values may also be JSONArrayJSONObject, or just a simple value, such as int.

Object value_1 = Countly.sharedInstance().getRemoteConfigValueForKey("aa");
Object value_2 = Countly.sharedInstance().getRemoteConfigValueForKey("bb");
Object value_3 = Countly.sharedInstance().getRemoteConfigValueForKey("cc");
Object value_4 = Countly.sharedInstance().getRemoteConfigValueForKey("dd");

int int_value = (int) value_1;
double double_value = (double) value_2;
JSONArray jArray = (JSONArray) value_3;
JSONObject jobj = (JSONObject) value_4;

Clearing Stored Remote Config values

At some point, you might like to erase all the values downloaded from the server. You will need to call one function to do so.

Countly.sharedInstance().remoteConfigClearValues();

Setting up User Profiles

Available with Enterprise Edition, User Profiles is a tool that helps you identify users, their devices, event timelines, and application crash information. User Profiles may contain any information you either collect or is collected automatically by the Countly SDK.

You may send user-related information to Countly and let the Countly dashboard show and segment this data. You may also send a notification to a group of users. For more information about User Profiles, review this documentation.

You must call the Countly.userData.setUserData function in order to provide information regarding the current user. You may call this function by providing a bundle of only the predefined fields, or you may call this function while also providing a second bundle of fields with your custom keys. After you have provided the user profile information, you must save it by calling Countly.userData.save().

//Update the user profile using only predefined fields
Map<String, String> predefinedFields = new HashMap<>();
Countly.userData.setUserData(predefinedFields);
Countly.userData.save()


//Update the user profile using predefined and custom fields
Map<String, String> predefinedFields = new HashMap<>();
Map<String, String> customFields = new HashMap<>();
Countly.userData.setUserData(predefinedFields, customFields);
Countly.userData.save()

The keys for predefined user data fields are as follows:

Key Type Description
name String User's full name
username String User's nickname
email String User's email address
organization String User's organization name
phone String User's phone number
picture String URL to avatar or profile picture of the user
picturePath String Local path to the user's avatar or profile picture
gender String User's gender as M for male and F for female
byear String User's year of birth as integer

Using "" for strings or a negative number for 'byear' will effectively delete that property.

You may use any key values to be stored and displayed on your Countly backend for custom user properties. Note: keys with . or $ symbols will have those symbols removed.

Modifying custom data

Additionally, you may perform different manipulations on your custom data values, such as incrementing the current value on a server or storing an array of values under the same property.

You will find the list of available methods below:

//set one custom properties
Countly.userData.setProperty("test", "test");
//increment used value by 1
Countly.userData.increment("used");
//increment used value by provided value
Countly.userData.incrementBy("used", 2);
//multiply value by provided value
Countly.userData.multiply("used", 3);
//save maximal value
Countly.userData.saveMax("highscore", 300);
//save minimal value
Countly.userData.saveMin("best_time",60);
//set value if it does not exist
Countly.userData.setOnce("tag", "test");
//insert value to array of unique values
Countly.userData.pushUniqueValue("type", "morning");
//insert value to array which can have duplocates
Countly.userData.pushValue("type", "morning");
//remove value from array
Countly.userData.pullValue("type", "morning");

//send provided values to server
Countly.userData.save();

In the end, always call Countly.userData.save() to send them to the server.

User Consent management

In an effort to comply with GDPR, starting from 18.04, Countly provides ways to toggle different Countly features on/off depending on the given consent.

More information about GDPR can be found here.

The requirement for consent is disabled by default. To enable it, you will have to call setRequiresConsent with true before initializing Countly.

Countly.sharedInstance().setRequiresConsent(true);
Countly.sharedInstance().init(appC, COUNTLY_SERVER_URL, COUNTLY_APP_KEY);

By default, no consent is given. That means that if no consent is enabled, Countly will not work and no network requests related to its features will be sent. When the consent status of a feature is changed, that change will be sent to the Countly server.

For all features, except push, consent is not persistent and will have to be set each time before Countly init. Therefore, the storage and persistence of the given consent falls on the SDK integrator.

Consent for features may be given and revoked at any time, but if it is given after Countly init, some features may only work in part.

If consent is removed, but the appropriate function can't be called before the app closes, it should be done upon the next app start, so that any relevant server-side features may be disabled (such as the reverse geo IP for location).

Feature names in the Android SDK are stored as static fields in the class called CountlyFeatureNames.

The current features are:

* sessions - tracking when, how often and how long users use your app

* events - allow sending custom events to the server

* views - allow the tracking of which views user visits

* location - allow the sending of location information

* crashes - allow the tracking of crashes, exceptions, and errors

* attribution - allow tracking of which campaign did the user come from

* users - allow the collecting/providing of user information, including custom properties

* push - allow push notifications

* starRating - allow their rating and feedback to be sent

Feature groups

Features may be put into groups. By doing this, you may give/remove consent to multiple features in the same call. They may be created using createFeatureGroup. Those groups are not persistent and must be created on every restart.

// prepare features that should be added to the group
String[] groupFeatures = new String[]{ Countly.CountlyFeatureNames.sessions, Countly.CountlyFeatureNames.location };

// create the feature group
Countly.sharedInstance().createFeatureGroup("groupName", groupFeatures);

Changing consent

There are 3 ways of changing feature consent: * giveConsent/removeConsent - gives or removes consent to a specific feature.

// give consent to "sessions" feature
Countly.sharedInstance().giveConsent(new String[]{Countly.CountlyFeatureNames.sessions});

// remove consent from "sessions" feature
Countly.sharedInstance().removeConsent(new String[]{Countly.CountlyFeatureNames.sessions});
  • setConsent - set consent to a specific (true/false) value
// give consent to "sessions" feature
Countly.sharedInstance().setConsent(new String[]{Countly.CountlyFeatureNames.sessions}, true);

// remove consent from "sessions" feature
Countly.sharedInstance().setConsent(new String[]{Countly.CountlyFeatureNames.sessions}, false);
  • setConsentFeatureGroup - set consent for a feature group to a specific (true/false) value
// prepare features that should be added to the group
String[] groupFeatures = new String[]{ Countly.CountlyFeatureNames.sessions, Countly.CountlyFeatureNames.location };

String groupName = "featureGroup1";

// give consent to "sessions" feature
Countly.sharedInstance().setConsentFeatureGroup(groupName, true);

// remove consent from "sessions" feature
Countly.sharedInstance().setConsentFeatureGroup(groupName, false);

Setting up push notifications

Countly supports FCM (Firebase Cloud Messaging) and Huawei Push Kit as push notification service providers. The SDK doesn't have any direct dependencies on FCM or HMS libraries and uses reflection instead, so it's up to application developers to ensure correct dependencies are present (please refer to our Demo app build.gradle for a reference).

By default Countly SDK uses FCM as push notification provider. If FCM is not present in the system, Countly would try to get HMS token instead. It's possible to alter this behaviour by supplying HMS as a preferred provider:

CountlyPush.init(this, 
Countly.CountlyMessagingMode.PRODUCTION,
Countly.CountlyMessagingProvider.HMS)

General SDK initialisation

To have the best experience with push notifications, the SDK should be initialised in the your Application subclass' "onCreate" method. Don't forget that Android O and later models require the use of NotificationChannels. Use CountlyPush.CHANNEL_ID for Countly-displayed notifications:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                // Create the NotificationChannel
                NotificationChannel channel = new NotificationChannel(CountlyPush.CHANNEL_ID, getString(R.string.countly_hannel_name), NotificationManager.IMPORTANCE_DEFAULT);
                channel.setDescription(getString(R.string.countly_channel_description));
                notificationManager.createNotificationChannel(channel);
            }
        }

        Countly.sharedInstance()
                .setLoggingEnabled(true)
                .init(this, "http://try.count.ly", "APP_KEY");

        CountlyPush.init(this, Countly.CountlyMessagingMode.PRODUCTION);

        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "getInstanceId failed", task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();
                        CountlyPush.onTokenRefresh(token);
                    }
                });
    }
}

Please note second parameter in CountlyPush.init() call, it defines whether a particular device would be handled as a test setup or a production one. It's quite handy to separate test devices from production ones by changing CountlyMessagingMode, so you could test your notifications before sending them to all your users.

Please follow provider-specific instructions for Firebase and / or Huawei PushKit below.

Firebase

Getting FCM credentials

In order to be able to send notifications through FCM, Countly server needs a FCM server key. In order to get one, open Project settings in Firebase console:

Select Cloud Messaging tab

Copy & paste the FCM key into your application FCM credentials upload form in the Countly dashboard, select “Validate”, and eventually “Save changes”.

Integrating FCM into your app

Please review our Demo app for a complete integration example.

Once you have followed the Google's guide for Adding Firebase to your project, setting up the Countly FCM is quite easy.

Adding dependencies

Add the following dependency to your build.gradle (use latest Firebase version):

//latest firebase-messaging version that is available
implementation 'com.google.firebase:firebase-messaging:18.0.0'

Then add CountlyPush.init() call to your Application subclass. Don't forget that Android O and later models require the use of NotificationChannels. Use CountlyPush.CHANNEL_ID for Countly-displayed notifications:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                // Create the NotificationChannel
                NotificationChannel channel = new NotificationChannel(CountlyPush.CHANNEL_ID, getString(R.string.countly_hannel_name), NotificationManager.IMPORTANCE_DEFAULT);
                channel.setDescription(getString(R.string.countly_channel_description));
                notificationManager.createNotificationChannel(channel);
            }
        }

        Countly.sharedInstance()
                .setLoggingEnabled(true)
                .init(this, "http://try.count.ly", "APP_KEY");

        CountlyPush.init(this, Countly.CountlyMessagingMode.PRODUCTION);

        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "getInstanceId failed", task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();
                        CountlyPush.onTokenRefresh(token);
                    }
                });
    }
}

Please note that in CountlyPush.init() you will also specify the mode of your token - test or production. It's quite handy to separate the test devices from production devices by changing CountlyMessagingMode, so you may test your notifications before sending them to all your users.

Now, we will need to add the Service. Add a service definition to your AndroidManifest.xml:

<service android:name=".DemoFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

... and add a class for it as well:

public class DemoFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "DemoMessagingService";

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);

        Log.d("DemoFirebaseService", "got new token: " + token);
        CountlyPush.onTokenRefresh(token);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("DemoFirebaseService", "got new message: " + remoteMessage.getData());

        // decode message data and extract meaningful information from it: title, body, badge, etc.
        CountlyPush.Message message = CountlyPush.decodeMessage(remoteMessage.getData());

        if (message != null && message.has("typ")) {
            // custom handling only for messages with specific "typ" keys
            message.recordAction(getApplicationContext());
            return;
        }

        Intent notificationIntent = null;
        if (message.has("anotherActivity")) {
            notificationIntent = new Intent(getApplicationContext(), AnotherActivity.class);
        }
      
        Boolean result = CountlyPush.displayMessage(getApplicationContext(), message, R.drawable.ic_message, notificationIntent);
        if (result == null) {
            Log.i(TAG, "Message wasn't sent from Countly server, so it cannot be handled by Countly SDK");
        } else if (result) {
            Log.i(TAG, "Message was handled by Countly SDK");
        } else {
            Log.i(TAG, "Message wasn't handled by Countly SDK because API level is too low for Notification support or because currentActivity is null (not enough lifecycle method calls)");
        }
    }

    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
    }
}

This class is responsible for token changes and message handling logic. Countly provides default UI for your notifications, which would display a Notification, if your app is in the background, or Dialog, if your app is active. It will also automatically report button clicks back to the server for Actioned metric conversion tracking. However, it is completely up to you, whether you would like to use this class or not. Let's have an overview of the onMessageReceived method:

  1. It calls CountlyPush.decodeMessage() to decode a message from the Countly-specific format. In this way, you'll have a method of accessing standard fields, such as a badge, URL, or your custom data keys.
  2. Then it checks if the message has a typcustom data key, and if it does, it only records the Actioned metric. Let's assume your custom notification is to preload some data from a remote server. Our demo app has a more in-depth scenario for this case.
  3. In case the message also has anotherActivity custom data key, it creates a notificationIntent to launch the activity, named AnotherActivity. This intent is only used as default content intent for the user tap on a Notification. It is not used forDialog.
  4. Then the service calls CountlyPush.displayMessage()to perform a standard Countly notification displaying logic - Notification, assuming your app is in the background or not running, and the Dialog is in the foreground. Note that this method takes an int resource parameter. It must be compatible with the corresponding version of the Android notification small icon.

Apart from that which is listed above, the SDK also exposes methods CountlyPush.displayNotification() & CountlyPush.displayDialog() in case you only need Notification and don't want Dialog or vice versa.

This is an example of a push notification payload sent from the Countly server:

{
	collapse_key: “collapse_key”, // if present
	time_to_live: 123,
	data: {
		message: “message string”, // if present
		title: “title string”, // if present
		sound: “sound string”, // if present
		badge: 123, // if present
		c.i: “message id string”,
		c.l: “http://message-wide-url”, // if present
		c.m: “http://rich.media.url.jpg”, // if present
		c.s: “true”, // if sound & message absent
		c.b: [ // if present
			{t: “Button 1 title”, l: “http://button.1.url”},
			{t: “Button 2 title”, l: “http://button.2.url”} // if present
		],
		// any other data properties if present
	}
}

 

Huawei PushKit

Getting Huawei credentials

Assuming you have followed Huawei's guide of setting up an application, next step would be to enable PushKit. Then enable Receipt status:

  • enter https://YOUR_COUNTLY_SERVER/i/pushes/huawei into the callback address field, while replacing YOUR_COUNTLY_SERVER with actual server address;
  • and enter your certificate in PEM format (only your certificate, without the rest of the chain; usually first one in openssl s_client -connect YOUR_COUNTLY_SERVER:443 -showcerts). 

Screenshot_2020-08-25_at_15.52.49.png

Then you'd need to get your App ID & App secret from AppGallery Connect -> My Apps:

Screenshot_2020-08-25_at_15.49.12.png

Copy your App ID & the secret and paste it into Countly dashboard :

Screenshot_2020-08-25_at_16.04.29.png

Integrating HMS into your app

HMS implementation in Countly SDK looks very much like FCM: add dependencies, add service definition and the service class. Please refer to our Demo app for a reference implementation. Assuming you've already integrated HMS Core into your app, all you need to do is add a dependency into build.gradle (use latest dependency version!):

implementation 'com.huawei.hms:push:4.0.3.301'

... add service definition into AndroidManifest.xml:

<service
android:name=".DemoHuaweiMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT" />
</intent-filter>
</service>

... and the service itself:

public class DemoHuaweiMessagingService extends HmsMessageService {
private static final String TAG = "DemoHuaweiMessagingService";

@Override
public void onNewToken(String token) {
super.onNewToken(token);

CountlyPush.onTokenRefresh(token, Countly.CountlyMessagingProvider.HMS);
}

@SuppressLint("LongLogTag")
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

Log.d(TAG, "got new message: " + remoteMessage.getDataOfMap());

// decode message data and extract meaningful information from it: title, body, badge, etc.
CountlyPush.Message message = CountlyPush.decodeMessage(remoteMessage.getDataOfMap());
if (message == null) {
Log.d(TAG, "Not a Countly message");
return;
}

if (message.has("typ")) {
// custom handling only for messages with specific "typ" keys
if (message.data("typ").equals("download")) {
message.recordAction(getApplicationContext());
return;
} else if (message.data("typ").equals("promo")) {
return;
}
}

Intent intent = null;
if (message.has("another")) {
intent = new Intent(getApplicationContext(), ActivityExampleOthers.class);
}
Boolean result = CountlyPush.displayMessage(getApplicationContext(), message, R.drawable.ic_message, intent);
if (result == null) {
Log.i(TAG, "Message doesn't have anything to display or wasn't sent from Countly server, so it cannot be handled by Countly SDK");
} else if (result) {
Log.i(TAG, "Message was handled by Countly SDK");
} else {
Log.i(TAG, "Message wasn't handled by Countly SDK because API level is too low for Notification support or because currentActivity is null (not enough lifecycle method calls)");
}
}
}

... which is almost identical to the FCM demo service. 

Advanced features

Custom notification sound

If you would like to use a custom sound in your push notifications, they must be present on the device. They may not be stored somewhere on the internet and then linked from there.

For you to use a custom notification sound, there are 2 things you will need to do.

First, you will need to prepare the URI that will link to the resource on your device. It would look something like this:

String soundUri = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.notif_sound;

You would then send this URI as part of the push notification, using the "Send sound" field. This should cover devices with the Android SDK version less than 26.

For devices with the SDK version 26+, you will also need to provide this URI during the notification channel setup. It would look something like this:

AudioAttributes audioAttributes = new AudioAttributes.Builder()
           .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
           .setUsage(AudioAttributes.USAGE_NOTIFICATION)
           .build();

channel.setSound(soundUri, audioAttributes);

More info about that here: https://stackoverflow.com/questions/48986856/android-notification-setsound-is-not-working

Automatic message handling

Countly handles most common message handling tasks for you. For example, it generates and shows Notification or Dialog and tracks conversion rates automatically. In most cases, it’s not necessary for you to know how it works, but if you would like to customize the behavior or exchange it with your own implementation, here is a more in-depth explanation of what it does.

First, the received notification payload is analyzed and, if it's a Countly notification (if it has a "c" dictionary in the payload), it processes it. Otherwise, or if the notification analysis says it is a Data-only notification (you're the one responsible for message processing), it does nothing.

Next, it automatically makes callbacks to the Countly Messaging server to calculate the number of open push notifications which got open and the number of notifications with positive reactions.

Here are the explanations of common usage scenarios that are handled automatically: 

  • It doesn't do anything, apart from conversion tracking if you specify it as a Data-only notification in the dashboard. This effectively sets a special flag in the message payload, so you may process it on your own.
  • It displays a Notification whenever a message arrives, and your application is in the background.
  • It displays Dialog when a new message arrives, and your application is in the foreground. 
  • It displays Dialog when a new message with an action arrives (open URL), and the user responds to it by swiping or tapping the notification.

A Dialog always has a message, but the set of displayed buttons depends on the message type:

  • It displays a single ‘Cancel’ button for notifications without any actions (only a text message).
  • For notifications with a URL (for instance, you ask the user to open a link to some blog post), it displays both the ‘Cancel’ & ‘Open’ buttons.
  • It displays the corresponding buttons for notifications with custom buttons.

Using Android deep links

When using Countly push notifications, you may benefit from Android deep links in your application for the buttons you provide. Those are basically links for specific activities of your application. A link may either be a generic ‘http’ link, such as http://www.oneexample.com/survey, or a link with a custom URI (uniform resource indicator) scheme, such as otherexample://things.

In order for Android deep links to work, you will need to specify the intent filters in your application's manifest for the specific groups of links you would like to use.

A deeper guide on how to configure your application to use deep links may be found here.

Developer-overridden message handling

You may also completely disable the push notification handling made by the Countly SDK. To do so, just add true to the end of your initMessaging()call:

Countly.sharedInstance()
    .init(this, "YOUR_SERVER", "APP_KEY", null, DeviceId.Type.ADVERTISING_ID)
    .initMessaging(this, CountlyActivity.class, "PROJECT_NUMBER", Countly.CountlyMessagingMode.TEST, true);

This parameter effectively disables any UI interactions and Activity instantiation from the Countly SDK. To enable the custom processing of push notifications, you may either register your own WakefulBroadcastReceiver or use our example with the broadcast action. Once you have switched off the default push notification UI, please make sure to call CountlyMessaging.recordMessageOpen(id)whenever a push notification is delivered to your device, and CountlyMessaging.recordMessageAction(id, index), whenever a user positively reacts to your notification. id is a message ID string you may receive from the c.i key of the push notification payload. index is optional and used to identify the type of action as follows: 0 for the tap on the notification in drawer, 1 for tap on first button of rich push, 2 for tap on the second button if there is any.

Handling button or push clicks

When receiving a push notification, the user may click the notification directly or they may click the button. When a user clicks anywhere on the push notification, an intent is launched to open the provided link. This may be a web page URL or a deep link. If you have configured your app, so that opening this intent will open an activity of your app, it should be possible to track which button was pressed.

There is also the option to add additional metadata to those intents. The included meta information contains data, such as which button was pressed, which link was given in the notification, the title, and the message of the notification.

This functionality is disabled by default, and the additional metadata might be added as extras to the intent.

In order to enable this functionality, you will need to call the following function before initializing Countly messaging:

Countly.sharedInstance().setPushIntentAddMetadata(true);

To access those extras from the intent, you should use these names:

ProxyActivity.intentExtraButtonLink
ProxyActivity.intentExtraMessageText
ProxyActivity.intentExtraMessageTitle
ProxyActivity.intentExtraWhichButton

To read the extra from the intent, you would use something similar to this:

String buttonUrl = intent.getStringExtra(ProxyActivity.intentExtraButtonLink);

Application Performance Monitoring

This SDK provides a few mechanisms for APM. To browse some of the provided functionality, check the returned interface from here:

Countly.sharedInstance().apm()

While using APM calls, you have the ability to provide trace keys by which you can track those parameters in your dashboard. Those keys have to abide by the following regex:

/^[a-zA-Z][a-zA-Z0-9_]*$/

In short, only Latin letters, numbers, and underscores can be used. The key can not start with an underscore or number. The key also has to be shorter than 32 characters.

Custom trace

Currently, you can use custom traces to record the duration of application processes. At the end of them, you can also provide any additionally gathered data.

The trace key uniquely identifies the thing you are tracking and the same name will be shown in the dashboard. The SDK does not support tracking multiple events with the same key.

To start a custom trace, use:

Countly.sharedInstance().apm().startTrace(String traceKey);

To end a custom trace, use:

Map<String, Integer> customMetric = new HashMap();
customMetric.put("ABC", 1233);
customMetric.put("C44C", 1337);

Countly.sharedInstance().apm().endTrace(String traceKey, customMetric);

The provided Map of integer values that will be added to that trace in the dashboard.

Network trace

You can use the APM to track your requests.

Call this just before making your network request:

Countly.sharedInstance().apm().startNetworkRequest(String networkTraceKey, String uniqueId);

`NetworkTraceKey` would be a unique identifier of the API endpoint you are targeting. `UniqueId` is an identifier for requests for a specific traceKey. In case you have overlapping network requests, you would have a unique id for each of the requests. `NetworkTraceKey` and `UniqueId` are used as a pair to uniquely identify the request you are making.

Call this after your network request is done:

Countly.sharedInstance().apm().endNetworkRequest(String networkTraceKey, String uniqueId, int responseCode, int requestPayloadSize, int responsePayloadSize);

You would provide the same `NetworkTraceKey` and `UniqueId` as starting the request and then also provided the received response code, sent payload size in bytes, and received payload size in bytes.

Automatic device traces

Currently, the Android SDK provides 3 automatic traces:

  • App start time
  • App time in the background
  • App time in foreground

To record app start time you need to implement 3 things.

First, you must enable this feature in config on init:

config.setRecordAppStartTime(true)

Second, you must call `Countly.applicationOnCreate();` right after your application classes `onCreate` like:

public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
Countly.applicationOnCreate();
...
}
}

Third, you must initialize countly in your apps Application onStart callback.

If you this, you will get the correct on start times.

App time in background/foreground

Countly will record the time your users spend in the foreground and background. For this to work, your users need to be given any consent. You also need to provide your Application class to your config object with "setApplication" during init.

Additional SDK features

Receiving and showing badge numbers from push notifications

While showing badges isn't supported natively for versions before Android O, there are some devices and launchers that support it. Therefore, you may want to implement such a feature in your app. However, not all devices will support badges.

While creating a new message in the messaging overview and preparing its content, there is an optional prompt called "Add iOS badge". You may use this prompt to also send badges to Android devices.

In order to receive this badge number in your application, you must subscribe to the broadcasts about received messages. There you will be informed about all received push notifications using Message and the bundle. The badge number is sent with the key "badge". You may use it to extract the badge number from the bundle received and then use it to display badge numbers with your implementation of choice.

In the example below we will use a badge library called ShortcutBadger, which is used to show badges on Android. Follow their instructions in this link on how to implement it in your Android project. You may also see the same example inside the Countly messaging sample project.

/** Register for broadcast action if you need to be notified when Countly message received */
messageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Message message = intent.getParcelableExtra(CountlyMessaging.BROADCAST_RECEIVER_ACTION_MESSAGE);
        Log.i("CountlyActivity", "Got a message with data: " + message.getData());

        //Badge related things
        Bundle data = message.getData();
        String badgeString = data.getString("badge");
        try {
            int badgeCount = Integer.parseInt(badgeString);

            boolean succeded = ShortcutBadger.applyCount(getApplicationContext(), badgeCount);
            if(!succeded) {
                Toast.makeText(getApplicationContext(), "Unable to put badge", Toast.LENGTH_SHORT).show();
            }
        } catch (NumberFormatException exception) {
            Toast.makeText(getApplicationContext(), "Unable to parse given badge number", Toast.LENGTH_SHORT).show();
        }
    }
};
IntentFilter filter = new IntentFilter();
filter.addAction(CountlyMessaging.getBroadcastAction(getApplicationContext()));
registerReceiver(messageReceiver, filter);

Testing

You've probably noticed that we used Countly.CountlyMessagingMode.TEST in our example. That is because we are currently building the application only for testing purposes. Countly separates users who run apps built for test and for release. This way you'll be able to test messages before sending them to all your users. When releasing your app, please use Countly.CountlyMessagingMode.PRODUCTION.

Push Notifications localization

While push notification messages in Countly Messaging are properly localized, you may also localize the way notifications are displayed. By default, Countly uses your application name for a title of the notification alert and the English word "Open" for the alert button name. If you would like to customize it, pass an array of Strings to the initMessaging call, where the button name is the first value:

String[] pushLocalizationArray = new String[]{"Open"};
Countly.sharedInstance()
    .init(this, "YOUR_SERVER", "APP_KEY", null, DeviceId.Type.ADVERTISING_ID)
    .initMessaging(this, CountlyActivity.class, "PROJECT_ID", Countly.CountlyMessagingMode.TEST, pushLocalizationArray);

Geolocation-aware notifications (Enterprise Edition only)

You may send notifications to users located at predefined locations. Countly uses a geo-IP database by default in order to bind your app users to their location. However, if your app has access to better location data, you may submit it to the server:

String latitude = "57.708358";
String longitude = "11.974950";

Countly.sharedInstance().setLocation(null, null, latitude + "," + longitude, null)

Checking if init has been called

In case you would like to check if init has been called, you may use the following function:

Countly.sharedInstance().isInitialized();

Checking if onStart has been called

For some applications, there might a use case where the developer would like to check if the Countly SDK onStart function has been called. To do so, they may use the following call:

Countly.sharedInstance().hasBeenCalledOnStart();

Ignoring app crawlers

Sometimes server data might be polluted with app crawlers which are not real users, and you would like to ignore them. Starting from the 17.05 release, it's possible to ignore app crawlers by filtering on the app level. The current version does that, using device names. Internally, the Countly SDK has a list of crawler device names. If a device name matches one from that list, no information is sent to the server.

At the moment, that list has only one entry: "Calypso AppCrawler". In the future we might add more crawler device names if such are reported. If you have encountered a crawler that is not on that list, and you would like to ignore it, you may add it to your SDK list yourself by calling addAppCrawlerName.

Currently, the SDK ignores crawlers by default. If you would like to change this setting, use ifShouldIgnoreCrawlers. If you would like to check if the current device was detected as a crawler, use isDeviceAppCrawler. Detection is done in the init function, meaning you would have to add the crawler names before that and perform the check after.

//set that the sdk should ignore app crawlers
Countly.sharedInstance().ifShouldIgnoreCrawlers(true);

//set that the sdk should not ignore app crawlers
Countly.sharedInstance().ifShouldIgnoreCrawlers(false);

//add another app crawler device name to ignore
Countly.sharedInstance().addAppCrawlerName("App crawler");

//returns true if this device is detected as a app crawler and false otherwise
Countly.sharedInstance().isDeviceAppCrawler();f

Forcing HTTP POST

If the data sent to the server is short enough, the SDK will use HTTP GET requests. In case you would like an override so that HTTP POST is used in all cases, call the "setHttpPostForced" function after you call "init". You may use the same function later in the app’s life cycle to disable the override. This function must be called every time the app starts.

//the init call before the override
Countly.sharedInstance().init(this, "https://YOUR_SERVER", "YOUR_APP_KEY", "YOUR_DEVICE_ID")
  
//enabling the override
Countly.sharedInstance().setHttpPostForced(true);
  
//disabling the override
Countly.sharedInstance().setHttpPostForced(false);

Setting Custom HTTP header values

In case you would like to add custom header key/value pairs to each request sent to the Countly server, you may make the following call:

HashMap<String, String> customHeaderValues = new HashMap<>();
customHeaderValues.put("foo", "bar");

Countly.sharedInstance().addCustomNetworkRequestHeaders(customHeaderValues);

The provided values will override any previously stored value pairs. In case you would like to erase any previously stored pairs, provide null.

SSL certificate pinning

Public key and certificate pinning are techniques that improve communication security by eliminating the threat of man-in-the-middle attack (MiM) in SSL connections. 

When you supply a list of acceptable SSL certificates to Countly SDK with either countlyConfig.enablePublicKeyPinning() or countlyConfig.enableCertificatePinning(), it will ensure that connection is made with one of the public keys specified or one of the certificates specified respectively. Using whole certificate pinning is somewhat safer, but using public key pinning is preferred since certificates can be rotated and do expire while public keys don't (assuming you don't change your CA).

Pinning is done during init through the CountlyConfig object.

To get the current public key or whole certificate from your server you can use one of these snippets (replace try.count.ly with your server name):

//get the public key
openssl s_client -connect try.count.ly:443 | openssl x509 -pubkey -noout
//get the list of certificates
openssl s_client -connect try.count.ly:443 -showcerts

In the certificate case, the first entry would be the certificate for your server (what you need to enter into SDK configuration) and the rest would be the chain of trust to the root certificate authority.

Here is an example of public key pinning for the try.count.ly server.

//sample certificate for the countly try server
String[] certificates = new String[] {
"MIIGnjCCBYagAwIBAgIRAN73cVA7Y1nD+S8rToAqBpQwDQYJKoZIhvcNAQELBQAwgY8xCzAJ"
+ "BgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAOBgNVBAcTB1"
+ "NhbGZvcmQxGDAWBgNVBAoTD1NlY3RpZ28gTGltaXRlZDE3MDUGA1UEAxMuU2VjdGln"
+ "byBSU0EgRG9tYWluIFZhbGlkYXRpb24gU2VjdXJlIFNlcnZlciBDQTAeFw0yMDA2MD"
+ "EwMDAwMDBaFw0yMjA5MDMwMDAwMDBaMBUxEzARBgNVBAMMCiouY291bnQubHkwggEi"
+ "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCl9zmATVRwrGRtRQJcmBmA+zc/ZL"
+ "io3YfkwXO2w8u9lnw60J4JpPNn9OnGcxdM+sqbXKU3jTdjY4j3yaA6NlWibq2jU2x6"
+ "HT2sS+I5gFFE/6tO53WqjoMk48i3FkyoJDittwtQrVaRGcP8RjJH0pfXaP+JLrLAgg"
+ "HuW3tCFqYzkWi3uLGVjQbSIRNiXsM3FI0UMEa/x1I3U4hLjMjH28KagZbZLWnHOvks"
+ "AvGLg3xQkS+GSQ+6ARZ2/bGh5O9q4hCCCk0/PpwAXmrOnWtwrNuwHcCDOvuB22JxLd"
+ "t8jQDYrjwtJIvq4Yut8FQPv/75SKoETWWHyxe0x5NsB34UwA/BAgMBAAGjggNsMIID"
+ "aDAfBgNVHSMEGDAWgBSNjF7EVK2K4Xfpm/mbBeG4AY1h4TAdBgNVHQ4EFgQU8uf/ND"
+ "Rt8cu+AwARVIGXPMfxGbQwDgYDVR0PAQH/BAQDAgWgMAwGA1UdEwEB/wQCMAAwHQYD"
+ "VR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMEkGA1UdIARCMEAwNAYLKwYBBAGyMQ"
+ "ECAgcwJTAjBggrBgEFBQcCARYXaHR0cHM6Ly9zZWN0aWdvLmNvbS9DUFMwCAYGZ4EM"
+ "AQIBMIGEBggrBgEFBQcBAQR4MHYwTwYIKwYBBQUHMAKGQ2h0dHA6Ly9jcnQuc2VjdG"
+ "lnby5jb20vU2VjdGlnb1JTQURvbWFpblZhbGlkYXRpb25TZWN1cmVTZXJ2ZXJDQS5j"
+ "cnQwIwYIKwYBBQUHMAGGF2h0dHA6Ly9vY3NwLnNlY3RpZ28uY29tMB8GA1UdEQQYMB"
+ "aCCiouY291bnQubHmCCGNvdW50Lmx5MIIB9AYKKwYBBAHWeQIEAgSCAeQEggHgAd4A"
+ "dQBGpVXrdfqRIDC1oolp9PN9ESxBdL79SbiFq/L8cP5tRwAAAXJwTJ0kAAAEAwBGME"
+ "QCIEErTN/aGJ8LV9brGklKeGAXMg1EN/FUxXDu13kNfXhcAiBrKMYe+W4flPyuLNm5"
+ "jp6FJwtUTZPNpZ+TmM40dRdwjQB0AN+lXqtogk8fbK3uuF9OPlrqzaISpGpejjsSwC"
+ "BEXCpzAAABcnBMncsAAAQDAEUwQwIfEYSpsSDtKpmj9ZmRWsx73G622N74v09JDjzP"
+ "bkg9RQIgUelIqSwqu69JanH7losrqTTsjwNv+3QJBNJ6GxJKkh0AdgBvU3asMfAxGd"
+ "iZAKRRFf93FRwR2QLBACkGjbIImjfZEwAAAXJwTJ0YAAAEAwBHMEUCIQCMBaaQAoua"
+ "97R+z2zONMUq1XsDP5aoAiutZG4XxuQ6wAIgW1p6XS3az4CCqjwbDKxL9qEnw8fWd+"
+ "yLx2skviSsTS0AdwApeb7wnjk5IfBWc59jpXflvld9nGAK+PlNXSZcJV3HhAAAAXJw"
+ "TJ1PAAAEAwBIMEYCIQDg1YFbJPPKDIyrFZJ9rtrUklkh2k/wpgwjDuIp7tPtOgIhAL"
+ "dZl9s/qISsFm2E64ruYbdE4HKR1ZJ0zbIXOZcds7XXMA0GCSqGSIb3DQEBCwUAA4IB"
+ "AQB2Ar1h2X/S4qsVlw0gEbXO//6Rj8mTB4BFW6c5r84n0vTwvA78h003eX00y0ymxO"
+ "i5hkqB8gd1IUSWP1R1ijYtBVPdFi+SsMjUsB5NKquQNlWpo0GlFjRlcXnDC6R6toN2"
+ "QixJb47VM40Vmn2g0ZuMGfy1XoQKvIyRosT92jGm1YcF+nLEHBDr+89apZ8sUpFfWo"
+ "AnCom+8sBGwje6zP10eBbprHyzM8snvdwo/QNLAzLcvVNKP+Sr4H7HKzec3g1+THI0"
+ "M72TzoguJcOZQEI6Pd+FIP5Xad53rq4jCtRGwYrsieH49a3orBnkkJvUKni+mtkxMb"
+ "PTJ7eeMmX9g/0h"
};

CountlyConfig countlyConfig = new CountlyConfig(getApplicationContext(), "c4608d0a021b1cef0f8cb031f51200e9cbe48dd4", "https://try.count.ly");
countlyConfig.enablePublicKeyPinning(certificates);
Countly.sharedInstance().init(countlyConfig);

In case you get a CertificateException with "Public keys didn't pass checks" that means the certificate or public key for the reached server did not match to any one of the provided ones. Usually, it means that your provided certificate is wrong.

In case you encounter some other certificate or SSL related exception, here is a list of the common reasons for issues.

In case of those issues, sometimes a good way of exploring the cause of the problem further is the same openssl certificate command:

openssl s_client -connect try.count.ly:443 -showcerts

It's error codes can sometimes lead you to a solution.

A common issue, which can be encountered is that the server's certificate does not contain the full chain of trust in it and it shows only 1 entry. In such cases, this may be helpful.

Interacting with the internal request queue

When recording events or activities, the requests don't always get sent immediately. Events get grouped together and sometimes there is no connection to the server and the requests can't be sent.

There are two ways how to interact with this request queue at the moment. 

You can force the SDK to try to send the requests immediately:

//Doing internally stored requests
Countly.sharedInstance().doStoredRequests();

This way the SDK will not wait for its internal triggers and it will try to empty the queue on demand.

There are some circumstances where you would want to delete all stored requests. Then you would call:

//Delete all stored requests in queue
Countly.sharedInstance().flushRequestQueues();

Setting an event queue threshold

Events get grouped together and are sent either every minute or after the unsent event count reaches a threshold. By default it is 10. If you would like to change this, call:

congfig.setEventQueueSizeToSend(6);

Custom Metrics

During some specific circumstances, like beginning a session or requesting remote config, the SDK is sending device metrics.

It is possible for you to either override the sent metrics (like the application version for some specific variant) or provide either your own custom metrics. If you are providing your own custom metrics, you would need your own custom plugin server-side which would interpret it appropriately. If there is no plugin to handle those custom values, they will be ignored.

//provide custom metric values
Map<String, String> metricOverride = new HashMap<>();
metricOverride.put("SomeKey", "123");
metricOverride.put("_app_version", "custom_version-123");

setMetricOverride(metricOverride);

Native C++ Crash Reporting

Countly uses Google's Breakpad open source library to be able to report crashes that occurred within the C++ components of your application, assuming there are any. Breakpad provides:

  • a tool for creating symbol files from your object files (dump_syms)
  • the ability to detect and record crashes via compact minidump files (crash handler)
  • a tool for generating human readable stack traces by using symbol files and crash minidump files.

Countly provides the sdk_native Android library to add crash handler to your native code and create crash minidump files. The SDK will check for those minidump files and send them automatically to your Countly server upon application start. You may download sdk_native from the default JCenter or Bintray Maven repositories and include it in your project, similar to how you included our SDK (please change the LATEST_VERSION below by checking our Maven page, currently 19.02.3):

// build gradle file 

repositories {
    maven {
        url 'https://dl.bintray.com/countly/maven'
    }
    jcenter()
}

dependencies {
    implementation 'ly.count.android:sdk-native:LATEST_VERSION'
}

Then call our init method as early as possible in your application life cycle to be able to catch crashes that occur during initialization:

import ly.count.android.sdknative.CountlyNative;

CountlyNative.initNative(getApplicationContext());

getApplicationContext() is needed to determine a storage place for minidump files.

Automatic creation and upload of symbol files

You may create Breakpad symbol files yourself and upload them to your Countly server using our UI. They will be needed to create stack traces from minidump files. Countly also developed a Gradle plugin to automate this process. To use the upload plugin in Studio, you first need to include it (the LATEST_VERSION is currently 19.02.3):

apply plugin: ly.count.android.plugins.UploadSymbolsPlugin 

buildscript {
    repositories {
        maven {
            url 'https://dl.bintray.com/countly/maven'
        }
        jcenter()
    }
    // for LATEST_VERSION check https://bintray.com/countly/maven/sdk-plugin
    dependencies {
        classpath group: 'ly.count.android', 'name': 'sdk-plugin', 'version': 'LATEST_VERSION'
    }
}

Then you will need to configure a Gradle Countly block for the plugin:

countly {
    server "https://YOUR_SERVER", 
    app_key "YOUR_APP_KEY"  
}

Next, you will have two new Gradle tasks available to you: uploadJavaSymbols and uploadNativeSymbols. uploadJavaSymbols is for uploading the mapping.txt file generated by Proguard. After building your project, you may run these tasks through Studio's Gradle tool window (1). They will be available under your app (2) and grouped as Countly tasks (3).

Another option is to run them from the command line:

./gradlew uploadNativeSymbols

// or if you have subprojects

./gradlew :project-name:uploadNativeSymbols

You may also configure your build so these tasks will run after every build:

tasks.whenTaskAdded { task ->
    if (task.name.startsWith('assemble')) {
        task.dependsOn('uploadNativeSymbols')
    }
}

In addition, you may also override some default values in the Countly block in an effort to specify your server and app info.

countly {
  // required by both tasks
  server "https://try.count.ly"
  app_key "XXXXXX"  // same app_key used for SDK integration

  // optional properties for uploadJavaSymbols. Shown are the default values.

  // location of mapping.txt file relative to project build directory
  mappingFile "outputs/mapping/release/mapping.txt"

  // note that will be saved with the upload and can be checked in the UI
  noteJava "sdk-plugin automatic upload of mapping.txt"

  // optional properties for uploadNativeSymbols. Shown are the default values.

  // directory of .so files relative to project build directory.
  // you can check the tar.gz file created under intermediates/countly
  // BUILD_TYPE could be debug or release
  nativeObjectFilesDir "intermediates/merged_native_libs/BUILD_TYPE"
  
  // path for breakpad tool dump_syms executable 
  dumpSymsPath "/usr/bin/dump_syms" // note that will be saved with the upload and can be checked in the UI noteNative "sdk-plugin automatic upload of breakpad symbols" } 
  

It is possible that two of these properties will need to be configured manually: dumpSymsPath and nativeObjectFilesDir. The plugin assumes you will run the task after a release build. To test it for debug builds, please change nativeObjectFilesDir to "intermediates/cmake/debug/obj" (or to wherever your build process puts .so files under the build directory).

We created a sample app in our github repo that demonstrates both how to use SDK-native and our upload plugin.

Building an Android SDK

If you need to customize our Android SDK to fit your needs, you may find it here among our Countly Github repositories as an Android Studio project. Modules included in the project are:

Module Name Description
sdk Countly Android SDK.
app Sample app to test sdk
sdk-native Module needed for Native C++ crash reporting
app-native Sample app to test sdk-native

Recently, Android Studio versions have a bug which you may encounter when building your project in Studio. If you see a build error such as SIMPLE: Error configuring, please check your text view for the build Gradle output. If you see this error CMake was unable to find a build program corresponding to "Ninja". CMAKE_MAKE_PROGRAM is not set, then you need to make ninja available in your PATH. If you are using cmake embedded in Studio, ninja may be found in the <sdk_location>/cmake/<cmake_version>/bin directory.

There is a build step for the sdk-native module which takes place outside of Studio. You may find the related code and build scripts in sdk-native/src/cpp_precompilation. We are working on building a breakpad library with an appropriate ndk version to integrate this step into your Studio build. Meanwhile, it seems OK to use the library files in sdk-native/src/main/jniLibs/ that are externally built.

Was this article helpful?
0 out of 2 found this helpful

Looking for help?