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

Older documentation

To access the documentation for version 19.09-sdk2-rc, click here.

The process of setting up Countly Java SDK includes 2 simple steps: adding SDK as a dependency to your project and initializing SDK. Once those are done, you'll have basic analytics on your server like users, sessions, devices, etc.

Adding SDK to the project

SDK is hosted on MavenCentral, more info can be found here and here. To add it, you first have to add the MavenCentral repository. For Gradle you would do it something like this:

buildscript {
repositories {

The dependency can be added as:

dependencies {
implementation "ly.count.sdk:java:19.09-sdk2-rc"

Or as:


SDK Integration

Minimal Setup

To start Countly SDK, you need to create a config class and pass it to the init method. To that method, you also pass the path where countly can store its things.

Config config = new Config("http://YOUR.SERVER.COM", "YOUR_APP_KEY")
                .enableFeatures(Config.Feature.Events, Config.Feature.Sessions, Config.Feature.CrashReporting, Config.Feature.UserProfiles)
File targetFolder = new File("d:\\__COUNTLY\\java_test\\");                
Countly.init(targetFolder, config);

In our Config instance we:

  • Told SDK not to use HTTPS (note http:// in URL) and to send data to Countly server located at http://YOUR.SERVER.COM. We also specified the app key (YOUR_APP_KEY).
  • Enabled test mode (read - crash whenever in an inconsistent state, don't forget to disable it in Production!).
  • Set logging level to DEBUG to make sure everything works as expected.
  • Enabled crash reporting feature and tell SDK to use UUID strategy, that is random UUID string, as device id.

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 or 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 or https://IP (if SSL has been set up).

SDK logging / debug mode

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. 

Set setLoggingLevel on the config object to enable logging:

Config config = new Config("http://YOUR.SERVER.COM", "YOUR_APP_KEY")
                .enableFeatures(Config.Feature.Events, Config.Feature.Sessions, Config.Feature.CrashReporting, Config.Feature.UserProfiles)

SDK data storage

Countly SDK stores serialized versions of the following classes: InternalConfig, SessionImpl, RequestImpl, CrashImpl, UserImpl & TimedEvents. All those are stored in device memory, in binary form, in separate files with filenames prefixed with [CLY]_.

SDK notes

Test mode

To ensure correct SDK behavior, please use Config.enableTestMode() when your app is in development and testing. In test mode, Countly SDK raises RuntimeExceptions whenever is in an inconsistent state. Once you remove Config.enableTestMode() call from your initialization sequence, SDK stops raising any Exceptions and switches to logging errors instead (if logging wasn't specifically turned off). Without having test mode on during development you may encounter some important issues with data consistency in production.


Events in Countly represent some meaningful event user performed in your application within a Session. Please avoid recording everything like all taps or clicks users performed. In case you do, it will be very hard to extract valuable information from generated analytics.

An Event object contains the following data types:

  • name, or event key. Required. A unique string that identifies the event.
  • count - number of times. Required, 1 by default. Like a number of goods added to the shopping basket.
  • sum - sum of something, amount. Optional. Like a total sum of the basket.
  • dur - duration of the event. Optional. For example how much time users spent checking out.
  • segmentation - some data associated with the event. Optional. It's a Map<String, String> which can be filled with arbitrary data like {"category": "Pants", "size": "M"}.

Recording events

The standard way of recording events is through your Session instance:

                    .addSegments("category", "pants", "size", "M")

Please note the last method in that call chain, .record() call is required for the event to be recorded.

The example above results in a new event being recorded in the current session. The event won't be sent to the server right away. Instead, Countly SDK will wait until one of the following happens:

  • Config.sendUpdateEachSeconds seconds passed since begin or last update request in case of automatic session control.
  • Config.eventsBufferSize events have been already recorded and not sent yet.
  • Session.update() have been called by the developer.
  • Session.end() have been called by the developer or by Countly SDK in case of automatic session control.

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


2. Event key, count, and sum


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");


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");


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");


Those are only a few examples of what you can do with 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

There is also a special type of Event supported by Countly - timed events. Timed events help you to track long continuous interactions when keeping an Event instance is not very convenient.

The basic use case for timed events is following:

  • User starts playing a level "37" of your game, you call Countly.session().timedEvent("LevelTime").addSegment("level", "37") to start tracking how much time a user spends on this level.
  • Then something happens when the user is at that level, for example, the user bought some coins. Along with regular "Purchase" event, you decide you want to segment the "LevelTime" event with purchase information: Countly.session().timedEvent("LevelTime").setSum(9.99).
  • Once the user stopped playing, you need to stop recording this event: Countly.session().timedEvent("LevelTime").endAndRecord()

Once this event is sent to the server, you'll see:

  • how much time users spend on each level (duration per level segmentation);
  • which levels are generating the most revenue (sum per level segmentation);
  • which levels are not generating revenue at all since you don't show ad there (0 sums in level segmentation).

With timed events, there is one thing to keep in mind: you have to end timed event for it to be recorded. Without endAndRecord() call, nothing will happen.


Manual sessions

Session in Countly is a single app launch or several app launches if the time between them is less than 30 seconds (by default). Of course, you can override this behavior.

Session lifecycle methods include:

  • session.begin() must be called when you want to send begin session request to the server. This request contains all device metrics: device, model, carrier, etc.
  • session.update() can be called to send a session duration update to the server along with any events, user properties, and any other data types supported by Countly SDK. Called each Config.sendUpdateEachSeconds seconds in auto session mode.
  • session.end() must be called to mark the end of the session. All the data recorded since the last session.update() or since session.begin() in case no updates have been sent yet, is sent in this request as well.

User profiles

For information about User Profiles, review this documentation

Setting predefined values

The Countly Java SDK allows you to upload specific data related to a user to the Countly server. You may set the following predefined data for a particular user:

  • Name: Full name of the user.
  • Username: Username of the user.
  • Email: Email address of the user.
  • Organization: Organization the user is working in.
  • Phone: Phone number.
  • Picture: Picture path for the user’s profile.
  • Gender: Gender of the user (use only single char like ‘M’ for Male and ‘F’ for Female).
  • BirthYear: Birth year of the user.

The SDK allows you to upload user details using the methods listed below.

To set standard properties, call respective methods of UserEditor:

        .setName("Firstname Lastname")

Setting custom values

To set custom properties, call set(). To send modification operations, call the corresponding method:

        .set("mostFavoritePet", "dog")
        .inc("phoneCalls", 1)
        .pushUnique("tags", "fan")
        .pushUnique("skill", "singer")

Device ID management

A device ID is a unique identifier for your users. You may specify the device ID yourself or allow the SDK to generate it. When providing one yourself, keep in mind that it has to be unique for all users. Some potential sources for such an id may be the users username, email or some other internal ID used by your other systems.

Changing device ID

The SDK allows you to change the Device ID at any point in time. You can use any of the following two methods to changing the Device ID, depending on your needs.

Changing Device ID with server 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. In this case, any data stored in your Countly server database associated with the current device ID will be transferred (merged) into the user profile with the device id you specified in the following method call:

Countly.session().changeDeviceIdWithMerge("New Device Id");

Changing Device ID without server merge

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.session().changeDeviceIdWithoutMerge("New Device Id");

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

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.

Retrieving current device ID 

You may want to see what device id Countly is assigning for the specific device. For that, you may use the following calls. 

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

Looking for help?