description |
---|
Detailed technical documentation on RudderStack’s Android SDK using Android Studio to send events from your Android device to various destinations. |
The RudderStack Android SDK allows you to track event data from your app. It can be easily integrated into your Android application. After integrating this SDK, you will also be able to send the event data to your preferred analytics destination/s such as Google Analytics, Amplitude, and more.
You can check the GitHub codebase if you want to get more hands-on or keen to know the SDK architecture.
To set up the RudderStack Android SDK, there are a few prerequisites as mentioned below:
- You will need to set up a RudderStack Account.
- Once signed up, your
Android
sourcewriteKey
will appear in the Dashboard, as shown:
- You will also need your Data Plane URL. Simply put, the Data Plane URL is used to connect to the RudderStack backend for processing and routing your events.
{% hint style="info" %} To get the Data Plane URL:
-
If you're using the open-source version of RudderStack, you are required to set up your own data plane by installing and setting up RudderStack in your preferred dev environment.
-
If you're using the enterprise version of RudderStack, please contact us for the data plane URL with the email ID used to sign up for RudderStack. {% endhint %}
-
You will also need to install Android Studio on your system.
{% hint style="info" %} As Bintray has a sunset from 1st may, we're moving our SDK to Maven Central". All the versions, 1.0.10 onwards are available in Maven Central only. {% endhint %}
We distribute our Android SDK through Maven Central. The recommended and easiest way to add the SDK to your project is through the Android Gradle build system.
Follow these steps:
- Open your project level
build.gradle
file, and add the following lines of code:
buildscript {
repositories {
mavenCentral()
}
}
allprojects {
repositories {
mavenCentral()
}
}
- Then open your
app/build.gradle
and add the dependency underdependencies
as shown below:
implementation 'com.rudderstack.android.sdk:core:1+'
// add the following line if you don't have Gson included already
implementation 'com.google.code.gson:gson:2+'
{% hint style="info" %}
It is recommended to use the Core Android SDK without any device-mode
destination SDKs as you will have a better view on the captured data from the SDK.
{% endhint %}
Add this line to your AndroidManifest.xml
file of your application for internet
permission:
<uses-permission android:name="android.permission.INTERNET"/>
We also declare android.permission.BLUETOOTH
and android.permission.ACCESS_WIFI_STATE
as optional by mentioning required="false"
. If we get these permissions, we'll capture the Bluetooth status and the WiFi status of the device and pass it under context.network
.
Import the library on the classes you desire to use RudderClient
library
import com.rudderstack.android.sdk.core.*;
Add the following code to the onCreate
method in your Application
class:
{% hint style="info" %}
Don't have an Application
class? Follow our guide on Adding an Application Class to Your Android Application to add one.
{% endhint %}
{% tabs %} {% tab title="Kotlin" %}
val rudderClient = RudderClient.getInstance(
this,
WRITE_KEY,
RudderConfig.Builder()
.withDataPlaneUrl(DATA_PLANE_URL)
.withTrackLifecycleEvents(true)
.withRecordScreenViews(true)
.build()
)
{% endtab %}
{% tab title="JAVA" %}
RudderClient rudderClient = RudderClient.getInstance(
this,
WRITE_KEY,
new RudderConfig.Builder()
.withDataPlaneUrl(DATA_PLANE_URL)
.withTrackLifecycleEvents(true)
.withRecordScreenViews(true)
.build()
);
{% endtab %} {% endtabs %}
{% hint style="info" %} We automatically track the following optional events:
Application Installed
Application Updated
Application Opened
Application Backgrounded
You can disable these events using the withTrackLifecycleEvents
method and passing false
. But it is highly recommended to keep them enabled.
{% endhint %}
RudderStack gives the users (e.g., an EU user) the ability to opt out of tracking any user activity until the user gives their consent. You can do this by leveraging RudderStack's optOut
API.
The optOut
API takes true
or false
as a Boolean value to enable or disable tracking user activities. This flag persists across device reboots.
The following snippet highlights the use of the optOut
API to disable user tracking:
{% tabs %} {% tab title="Kotlin" %}
rudderClient.optOut(true)
{% endtab %}
{% tab title="JAVA" %}
rudderClient.optOut(true);
{% endtab %} {% endtabs %}
Once the user grants their consent, you can enable user tracking once again by using the optOut
API with false
as a parameter sent to it, as shown:
{% tabs %} {% tab title="Kotlin" %}
rudderClient.optOut(false)
{% endtab %}
{% tab title="JAVA" %}
rudderClient.optOut(false);
{% endtab %} {% endtabs %}
{% hint style="info" %}
The optOut
API is available in the RudderStack Android SDK from version 1.0.19
.
{% endhint %}
You can record the users' activity through the track
method. Every action performed by the user is called an event.
An example of the track
event is as shown:
{% tabs %} {% tab title="Kotlin" %}
rudderClient.track(
"Product Added",
RudderProperty()
.putValue("product_id", "product_001")
)
{% endtab %}
{% tab title="JAVA" %}
rudderClient.track(
"Product Added",
new RudderProperty()
.putValue("product_id", "product_001")
);
{% endtab %} {% endtabs %}
Follow the method signature as below:
Name | Data Type | Required | Description |
---|---|---|---|
name |
String |
Yes | Name of the event you want to track |
property |
RudderProperty or Map<String, Object> |
No | Extra data properties you want to send along with the event |
options |
RudderOption |
No | Extra event options |
We capture deviceId
and use that as anonymousId
for identifying the user. It helps to track the users across the application installation. To attach more information to the user, you can use the identify
method. Once you set the identify
information to the user, those will be passed to the successive track
or screen
calls. To reset the user identification, you can use the reset
method.
{% hint style="info" %}
On the Android devices, the deviceId
is assigned during the first boot. It remains consistent across the applications and installs. It changes only after factory reset.
{% endhint %}
An example identify
event is as shown:
{% tabs %} {% tab title="Kotlin" %}
val traits = RudderTraits()
traits.putBirthday(Date())
traits.putEmail("[email protected]")
traits.putFirstName("First")
traits.putLastName("Last")
traits.putGender("m")
traits.putPhone("5555555555")
val address = RudderTraits.Address()
address.putCity("City")
address.putCountry("USA")
traits.putAddress(address)
traits.put("boolean", Boolean.TRUE)
traits.put("integer", 50)
traits.put("float", 120.4f)
traits.put("long", 1234L)
traits.put("string", "hello")
traits.put("date", Date(System.currentTimeMillis()))
rudderClient.identify("test_user_id", traits, null)
{% endtab %}
{% tab title="JAVA" %}
RudderTraits traits = new RudderTraits();
traits.putBirthday(new Date());
traits.putEmail("[email protected]");
traits.putFirstName("First");
traits.putLastName("Last");
traits.putGender("m");
traits.putPhone("5555555555");
RudderTraits.Address address = new RudderTraits.Address();
address.putCity("City");
address.putCountry("USA");
traits.putAddress(address);
traits.put("boolean", Boolean.TRUE);
traits.put("integer", 50);
traits.put("float", 120.4f);
traits.put("long", 1234L);
traits.put("string", "hello");
traits.put("date", new Date(System.currentTimeMillis()));
rudderClient.identify("test_user_id", traits, null;
{% endtab %} {% endtabs %}
Follow the method signatures below:
Name | Data Type | Required | Description |
---|---|---|---|
traits |
RudderTraits |
Yes | Traits information for the user |
options |
RudderOption |
No | Extra options for the identify event |
OR
Name | Data Type | Required | Description |
---|---|---|---|
userId |
String |
Yes | Developer identity for the user |
traits |
RudderTraits |
No | Traits information for user |
option |
RudderOption |
No | Extra options for the identify event |
You can use the screen
call to record whenever the user sees a screen on the mobile device. You can also send some extra properties along with this event.
An example of the screen
event is as shown:
{% tabs %} {% tab title="Kotlin" %}
rudderClient.screen(
"MainActivity",
"HomeScreen",
RudderProperty().putValue("foo", "bar"),
null
)
{% endtab %}
{% tab title="JAVA" %}
rudderClient.screen(
"MainActivity",
"HomeScreen",
new RudderProperty().putValue("foo", "bar"),
null
);
{% endtab %} {% endtabs %}
Follow the method signature below:
Name | Data Type | Required | Description |
---|---|---|---|
screenName |
String |
Yes | Name of the screen viewed. |
category |
String |
No | Category of the screen visited, such as HomeScreen , LoginScreen . Useful for tracking multiple Fragment views under a single Activity . |
property |
RudderProperty |
No | Extra property object that you want to pass along with the screen call. |
option |
RudderOption |
No | Extra options to be passed along with screen event. |
The group
call associates a user to a specific organization. A sample group
call for the API is below:
{% tabs %} {% tab title="Kotlin" %}
rudderClient.group(
"sample_group_id",
RudderTraits().putAge("24")
.putName("Test Group Name")
.putPhone("1234567891")
)
{% endtab %}
{% tab title="JAVA" %}
rudderClient.group(
"sample_group_id",
new RudderTraits().putAge("24")
.putName("Test Group Name")
.putPhone("1234567891")
);
{% endtab %} {% endtabs %}
Follow the method signatures below:
Name | Data Type | Required | Description |
---|---|---|---|
groupId |
String |
Yes | An ID of the organization with which you want to associate your user |
traits |
RudderTraits |
No | Any other property of the organization you want to pass along with the call |
options |
RudderOption |
No | Event level options |
We don't persist the traits for the group across the sessions
The alias
call associates the user with a new identification. A sample alias
call for the API is below:
{% tabs %} {% tab title="Kotlin" %}
rudderClient.alias("test_new_id")
{% endtab %}
{% tab title="JAVA" %}
rudderClient.alias("test_new_id");
{% endtab %} {% endtabs %}
Alternatively, you can use the following method signature
Name | Data Type | Required | Description |
---|---|---|---|
newId |
String |
Yes | The new userId you want to assign to the user |
options |
RudderOption |
No | Event level option |
We replace the old userId
with the newUserId
and we persist that identification across the sessions.
You can use the reset
method to clear the persisted traits
for the identify
call. This is required for Logout
operations.
{% tabs %} {% tab title="Kotlin" %}
rudderClient.reset()
{% endtab %}
{% tab title="JAVA" %}
rudderClient.reset();
{% endtab %} {% endtabs %}
You can configure your client based on the following parameters using RudderConfig.Builder
:
Parameter | Type | Description | Default Value |
---|---|---|---|
logLevel |
int |
Controls how much of the log you want to see from the SDK. | RudderLogger.RudderLogLevel.NONE |
dataPlaneUrl |
string |
URL of your data-plane . Please refer above to see how to fetch the data plane URL. |
https://api.rudderlabs.com |
flushQueueSize |
int |
Number of events in a batch request to the server. | 30 |
dbThresholdCount |
int |
Number of events to be saved in the SQLite database. Once the limit is reached, older events are deleted from the DB. |
10000 |
sleepTimeout |
int |
Minimum waiting time to flush the events to the server. | 10 seconds |
configRefreshInterval |
int |
It will fetch the config from dashboard after this many hours. |
2 |
trackLifecycleEvents |
boolean |
Whether SDK will capture application life cycle events automatically. | true |
recordScreenViews |
boolean |
Whether SDK will capture screen view events automatically. | false |
controlPlaneUrl |
string |
This parameter should be changed only if you are self-hosting the Control Plane. Check the section Self-Hosted Control Plane below for more information. The SDK will add /sourceConfig along with this URL to fetch the configuration. |
https://api.rudderlabs.com |
If you are using a device mode destination like Adjust, Firebase, etc., the Android SDK needs to fetch the required configuration from the Control Plane. If you are using the Control Plane Lite utility to self-host your Control Plane, then follow this guide and specify controlPlaneUrl
in yourRudderConfig.Builder
that points to your hosted source configuration file.
{% hint style="warning" %}
You shouldn't pass the controlPlaneUrl
parameter during SDK initialization if you are using the RudderStack Cloud dashboard (https://app.rudderstack.com). This parameter is supported only if you are using the open-source Control Plane Lite _**_to self-host your Control Plane.
{% endhint %}
You can set your device-token
for push notification to be sent to the destinations that support Push Notification. We set the token
under context.device.token
.
Follow the code snippets below:
{% tabs %} {% tab title="Kotlin" %}
rudderClient.putDeviceToken("your_device_token")
{% endtab %}
{% tab title="JAVA" %}
rudderClient.putDeviceToken("your_device_token");
{% endtab %} {% endtabs %}
We collect the advertisementId
if it is enabled by the user and the App has the Google Play services Ads SDK embedded in the application. We set the gaid
under context.device.advertisementId
.
Apart from it, if you want to set the advertisingId
by yourself, you can do so using the updateWithAdvertisingId
method and passing the advertisingId
.
{% hint style="warning" %}
You need to call updateWithAdvertisingId
method before calling getInstance
{% endhint %}
An example of setting the advertisingId
is as below
RudderClient.updateWithAdvertisingId(<ADVERTISING_ID>);
We use the deviceId
as anonymousId
by default. You can use the following method to override and use your own anonymousId
with the SDK.
{% hint style="warning" %}
You need to call setAnonymousId
method before calling getInstance
{% endhint %}
An example of setting the anonymousId
is as below
RudderClient.setAnonymousId(<ANONYMOUS_ID>);
To retrieve the anonymousId
you can use the following method:
RudderClient.getAnonymousId();
{% hint style="info" %}
The method getAnonymousId
is available from v1.0.11 onwards.
{% endhint %}
The RudderStack Android SDK allows you to enable or disable event flow to a specific destination or all the destinations to which the source is connected. You can specify these destinations by creating a RudderOption
object as shown:
{% tabs %} {% tab title="Kotlin" %}
val option = RudderOption()
//default value for `All` is true
option.putIntegration("All", false)
// specifying destination by its display name
option.putIntegration("Google Analytics", true)
option.putIntegration(<DESTINATION DISPLAY NAME>, <boolean>)
// specifying destination by its Factory object
option.putIntegration(AppcenterIntegrationFactory.FACTORY,true);
option.putIntegration(<RudderIntegration.FACTORY>,<boolean>);
{% endtab %}
{% tab title="Java" %}
RudderOption option = new RudderOption();
// default value for `All` is true
option.putIntegration("All", false);
// specifying destination by its display name
option.putIntegration("Google Analytics", true);
option.putIntegration(<DESTINATION DISPLAY NAME>, <boolean>);
// specifying destination by its Factory object
option.putIntegration(AppcenterIntegrationFactory.FACTORY,true);
option.putIntegration(<RudderIntegration.FACTORY>,<boolean>);
{% endtab %} {% endtabs %}
{% hint style="info" %}
The keyword All
in the above snippet represents all the destinations the source is connected to. Its value is set to true
by default.
{% endhint %}
{% hint style="info" %}
Make sure the destination display name
that you pass while specifying the destinations should exactly match the destination name as shown here.
{% endhint %}
You can pass the destination(s) specified in the above snippet to the SDK in two ways:
This is helpful when you want to enable/disable sending the events across all the event calls made using the SDK to the specified destination(s).
{% tabs %} {% tab title="Kotlin" %}
var rudderClient = RudderClient.getInstance(
this,
<WRITE_KEY>,
RudderConfig.Builder()
.withDataPlaneUrl(<DATA_PLANE_URL>)
.withLogLevel(RudderLogger.RudderLogLevel.DEBUG)
.withTrackLifecycleEvents(false)
.withRecordScreenViews(false)
.build(),
option // passing the rudderoption object containing the list of destination(s) you specified
)
{% endtab %}
{% tab title="Java" %}
RudderClient client = RudderClient.getInstance(
this,
<WRITE_KEY>,
new RudderConfig.Builder()
.withEndPointUri(<END_POINT_URL>)
.build(),
option // passing the rudderoption object containing the list of destination(s) you specified
);
{% endtab %} {% endtabs %}
This approach is helpful when you want to enable/disable sending only a particular event to the specified destination(s) or if you want to override the specified destinations passed with the SDK initialization for a particular event.
{% tabs %} {% tab title="Kotlin" %}
rudderClient.track(
"Product Added",
RudderProperty()
.putValue("product_id", "product_001"),
option // passing the rudderoption object containing the list of destination you specified
)
{% endtab %}
{% tab title="Java" %}
rudderClient.track(
"Product Added",
new RudderProperty()
.putValue("product_id", "product_001"),
option // passing the rudderoption object containing the list of destination(s) you specified
);
{% endtab %} {% endtabs %}
{% hint style="info" %} If you specify the destinations both while initializing the SDK as well as while making an event call, then the destinations specified at the event level only will be considered. {% endhint %}
You can pass your custom userId
along with standard userId
in your identify
calls. We add those values under context.externalId
. The following code snippet shows a way to add externalId
to your identify
request.
rudderClient.identify(
"sampleUserId",
RudderTraits().putFirstName("First Name"),
RudderOption()
.putExternalId("brazeExternalId", "some_external_id")
)
If you run into any issues regarding the RudderStack Android SDK, you can turn on the VERBOSE
or DEBUG
logging to find out what the issue is. To turn on the logging, change your RudderClient
initialization to the following:
{% tabs %} {% tab title="Kotlin" %}
val rudderClient: RudderClient = RudderClient.getInstance(
this,
YOUR_WRITE_KEY,
RudderConfig.Builder()
.withDataPlaneUrl(DATA_PLANE_URL)
.withLogLevel(RudderLogger.RudderLogLevel.DEBUG)
.build()
)
{% endtab %}
{% tab title="Java" %}
RudderClient rudderClient = RudderClient.getInstance(
this,
YOUR_WRITE_KEY,
new RudderConfig.Builder()
.withDataPlaneUrl(DATA_PLANE_URL)
.withLogLevel(RudderLogger.RudderLogLevel.DEBUG)
.build()
);
{% endtab %} {% endtabs %}
{% hint style="info" %} More information on the RudderStack Device Mode can be found in the RudderStack Connection Modes guide. {% endhint %}
Yes, you can develop a Device Mode destination by following these steps:
- Create a
CustomFactory
class by extendingRudderIntegration.java
, as shown:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.rudderstack.android.sdk.core.RudderClient;
import com.rudderstack.android.sdk.core.RudderConfig;
import com.rudderstack.android.sdk.core.RudderIntegration;
import com.rudderstack.android.sdk.core.RudderLogger;
import com.rudderstack.android.sdk.core.RudderMessage;
public class CustomFactory extends RudderIntegration<CustomFactory> {
private static final String FACTORY_KEY = "Custom Factory";
public static Factory FACTORY = new Factory() {
@Override
public RudderIntegration<?> create(Object settings, RudderClient client, RudderConfig rudderConfig) {
return new CustomFactory(client,rudderConfig);
}
@Override
public String key() {
return FACTORY_KEY;
}
};
private CustomFactory(@NonNull RudderClient client, RudderConfig config) {
}
private void processRudderEvent(RudderMessage element) {
System.out.println("Processing RudderEvent of type "+element.getType());
}
@Override
public void reset() {
System.out.println("Reset is called");
}
@Override
public void flush() {
System.out.println("Flush is called");
}
@Override
public void dump(@Nullable RudderMessage element) {
try {
if (element != null) {
processRudderEvent(element);
}
} catch (Exception e) {
RudderLogger.logError(e);
}
}
@Override
public CustomFactory getUnderlyingInstance() {
return this;
}
}
Some pointers to keep in mind:
- You can use the constructor of the
CustomFactory
class to initialize the native SDK of the Device Mode destination you are working on. - RudderStack's Android SDK dumps every event it receives to the
dump()
method of theCustomFactory
class. From here, you can process the event and hand it over to the native SDK of the Device Mode destination. - The SDK also triggers the
reset()
method of theCustomFactory
class on everyreset()
call made via the SDK. You can use this to handle the destination-specific reset. - RudderStack's Android SDK also triggers the
flush()
method of theCustomFactory
class on everyflush()
call made via the SDK which you can use to handle the destination-specific reset logic. You can make aflush
call using the SDK as shown below:
{% tabs %} {% tab title="Kotlin" %}
rudderClient.flush()
{% endtab %}
{% tab title="JAVA" %}
rudderClient.flush();
{% endtab %} {% endtabs %}
- Make sure you return a valid value from
getUnderlyingInstance()
as it is used by the Android SDK to validateCustomFactory
. - Make sure you do not duplicate the value of
FACTORY_KEY
across multipleCustomFactory
that you develop. - Register
CustomFactory
with the RudderStack Android SDK during its initialization, as shown:
var rudderClient = RudderClient.getInstance(
this,
WRITE_KEY,
RudderConfig.Builder()
.withDataPlaneUrl(DATA_PLANE_URL)
.withTrackLifecycleEvents(false)
.withRecordScreenViews(false)
.withCustomFactory(CustomFactory.FACTORY)
.build()
)
That's it! Your Device Mode destination is good to go.
If you are facing any issues regarding event delivery in a production environment, add the following line in your proguard rule:
-keep class com.rudderstack.android.** { *; }
We currently support API 14: Android 4.0 (IceCreamSandwich)
or higher.
Please follow our guide on How to Add an Application Class to Your Android App to add an Application
class.
Please refer to the Setting the Android Permission section above to do this.
Yes, you can use the library with maven
.
<dependency>
<groupId>com.rudderstack.android.sdk</groupId>
<artifactId>core</artifactId>
<version>latest_version</version>
<type>pom</type>
</dependency>
Using the following command in the Logcat tool once you set the logLevel
to VERBOSE
.
adb logcat -s RudderSDK:V \
-v tag -e "EventRepository: dump: message:"
You can get the user traits after making an identify
call as shown in the following snippet:
{% tabs %} {% tab title="Kotlin" %}
val traits = rudderClient!!.getRudderContext().getTraits()
{% endtab %}
{% tab title="JAVA" %}
Map<String,Object> traitsObj = rudderClient.getRudderContext().getTraits();
{% endtab %} {% endtabs %}
Yes, you can.
RudderStack gives you the ability to disable tracking any user activity until the user gives their consent, by leveraging the optOut
API. This is required in cases where your app is audience-dependent (e.g. minors) or where you're using the app to track the user events (e.g. EU users) to meet the data protection and privacy regulations.
The optOut
API takes true
or false
as a Boolean value to enable or disable tracking user activities. So, to disable user tracking, you can use the optOut
API as shown:
rudderClient.optOut(true)
Once the user gives their consent, you can enable user tracking again, as shown:
rudderClient.optOut(false)
{% hint style="info" %}
For more information on the optOut
API, refer to the Enabling/Disabling User Tracking via optOut API section above.
{% endhint %}
{% hint style="success" %}
You only need to call the optOut
API with the required parameter once, as the information persists within the device even if you reboot it.
{% endhint %}
In case of client-side errors, e.g. if the source write key passed to the SDK is incorrect, RudderStack gives you a 400 Bad Request response and aborts the operation immediately.
For other types of network errors (e.g. Invalid Data Plane URL), the SDK tries to flush the events to RudderStack in an incremental manner (every 1 second, 2 seconds, 3 seconds, and so on).
In case of any queries, you can always contact us, or open an issue on our GitHub Issues page in case of any discrepancy.