LogoLogo
  • Contributing to RudderStack
  • Destination_Name
  • LICENSE
  • RudderStack Docs
  • docs
    • FAQ
    • Identity Resolution
    • Home
    • cloud-extract-sources
      • ActiveCampaign Source
      • Bing Ads
      • Chargebee
      • Common Settings
      • Facebook Ads
      • Freshdesk
      • Google Ads Source
      • Google Analytics
      • Google Search Console
      • Google Sheets
      • Cloud Extract Sources
      • Intercom v2
      • Intercom
      • Mailchimp
      • Marketo
      • Mixpanel
      • NetSuite
      • Pipedrive
      • QuickBooks
      • Salesforce Pardot
      • Sendgrid Source
      • Stripe Source
      • Xero
      • Zendesk Chat
      • Zendesk
      • hubspot
        • HubSpot Data Model and Schema Information
        • HubSpot
      • salesforce
        • Salesforce
        • Schema Comparison: RudderStack vs. Segment
    • connections
      • Connection Modes: Cloud Mode vs. Device Mode
    • data-governance
      • Data Governance
      • RudderTyper
      • Data Governance API
      • RudderTyper
      • tracking-plans
        • Tracking Plans
        • Tracking Plan Spreadsheet
    • data-warehouse-integrations
      • Amazon Redshift
      • Azure Data Lake
      • Azure Synapse
      • ClickHouse
      • Databricks Delta Lake
      • Google Cloud Storage Data Lake
      • Google BigQuery
      • Identity Resolution
      • Warehouse Destinations
      • Microsoft SQL Server
      • PostgreSQL
      • Amazon S3 Data Lake
      • Snowflake
      • FAQ
      • Warehouse Schema
    • destinations
      • Destinations
      • Webhooks
      • advertising
        • Bing Ads
        • Criteo
        • DCM Floodlight
        • Facebook App Events
        • Facebook Custom Audience
        • Facebook Pixel
        • Google Ads (gtag.js)
        • Google AdWords Enhanced Conversions
        • Google Adwords Remarketing Lists (Customer Match)
        • Advertising
        • LinkedIn Insight Tag
        • Lotame
        • Pinterest Tag
        • Reddit Pixel
        • Snap Pixel
        • TikTok Ads
      • analytics
        • Amplitude
        • AWS Personalize
        • Chartbeat
        • Firebase
        • FullStory
        • Google Analytics 360
        • Google Analytics
        • Heap.io
        • Hotjar
        • Analytics
        • Indicative
        • Keen
        • Kissmetrics
        • Kubit
        • Lytics
        • Mixpanel
        • Pendo
        • PostHog
        • Quantum Metric
        • Singular
        • adobe-analytics
          • Adobe Analytics Heartbeat Measurement
          • Mobile Device Mode Settings
          • Web Device Mode Settings
          • E-commerce Events
          • Adobe Analytics
          • Setting Up Adobe Analytics in RudderStack
        • google-analytics-4
          • Cloud Mode
          • Device Mode
          • Google Analytics 4
          • Setting up Google Analytics 4
        • profitwell
          • ProfitWell
          • Cloud Mode
          • Device Mode
      • attribution
        • Adjust
        • AppsFlyer
        • Branch
        • Attribution
        • Kochava
        • TVSquared
      • business-messaging
        • Business Messaging
        • Intercom
        • Kustomer
        • Slack
        • Trengo
      • continuous-integration
        • Visual Studio App Center
        • Continuous Integration
      • crm
        • Delighted
        • HubSpot
        • CRM
        • Salesforce
        • Variance
        • Zendesk
      • customer-data-platform
        • Customer Data Platform
        • Segment
      • error-reporting
        • Bugsnag
        • Error Reporting
        • Sentry
      • marketing
        • ActiveCampaign
        • AdRoll
        • Airship
        • Appcues
        • Autopilot
        • Blueshift
        • Braze
        • CleverTap
        • Customer.io
        • Gainsight PX
        • Gainsight
        • Marketing
        • Iterable
        • Klaviyo
        • Leanplum
        • Mailchimp
        • Marketo Lead Import
        • Marketo
        • MoEngage
        • Ometria
        • Pardot
        • Post Affiliate Pro
        • Qualtrics
        • SendGrid
        • Salesforce Marketing Cloud
        • Userlist
        • drip
          • Cloud Mode
          • Device Mode
          • Drip
          • Setting Up Drip in RudderStack
      • productivity
        • Google Sheets
        • Productivity
      • storage-platforms
        • Amazon S3
        • DigitalOcean Spaces
        • Google Cloud Storage
        • Storage Platforms
        • Azure Blob Storage
        • MinIO
        • Redis
      • streaming-platforms
        • Amazon EventBridge
        • Amazon Kinesis Firehose
        • Amazon Kinesis
        • Azure Event Hubs
        • BigQuery Stream
        • Confluent Cloud
        • Google Pub/Sub
        • Streaming Platforms
        • Apache Kafka
      • tag-managers
        • Google Tag Manager
        • Tag Managers
      • testing-and-personalization
        • Algolia Insights
        • Candu
        • Google Optimize
        • A/B Testing & Personalization
        • LaunchDarkly
        • Monetate
        • Optimizely Full Stack
        • Optimizely Web
        • Split.io
        • Statsig
        • VWO (Visual Website Optimizer)
    • get-started
      • RudderStack Cloud vs. RudderStack Open Source
      • Glossary
      • Get Started
      • RudderStack Architecture
    • reverse-etl
      • Amazon Redshift
      • Amazon S3
      • ClickHouse
      • FAQ
      • Google BigQuery
      • Reverse ETL
      • PostgreSQL
      • Snowflake
      • common-settings
        • Importing Data using Models
        • Importing Data using Tables
        • Common Settings
        • Sync Modes
        • Sync Schedule
      • features
        • Airflow Provider
        • Features
        • Models
        • Visual Data Mapper
    • rudderstack-api
      • Data Regulation API
      • HTTP API
      • RudderStack API
      • Personal Access Tokens
      • Pixel API
      • Test API
      • api-specification
        • Application Lifecycle Events Specification
        • API Specification
        • Video Events Specification
        • rudderstack-ecommerce-events-specification
          • Browsing
          • Coupons
          • E-Commerce Events Specification
          • Ordering
          • Promotions
          • Reviewing
          • Sharing
          • Wishlist
        • rudderstack-spec
          • Alias
          • Common Fields
          • Group
          • Identify
          • RudderStack Event Specification
          • Page
          • Screen
          • Track
    • rudderstack-cloud
      • Audit Logs
      • Dashboard Overview
      • Destinations
      • RudderStack Cloud
      • Live Events
      • Connection Modes: Cloud Mode vs. Device Mode
      • Sources
      • Teammates (User Management)
      • connections
        • Adding a Destination
        • Connections
    • rudderstack-open-source
      • Control Plane Setup
      • RudderStack Open Source
      • installing-and-setting-up-rudderstack
        • Developer Machine Setup
        • Docker
        • Data Plane Setup
        • Kubernetes
        • Sending Test Events
    • stream-sources
      • App Center
      • AppsFlyer
      • Auth0
      • Braze
      • Customer.io
      • Extole
      • Event Stream Sources
      • Iterable
      • Looker
      • PostHog
      • Segment
      • Shopify
      • Webhook Source
      • rudderstack-sdk-integration-guides
        • Client-side Event Filtering
        • SDKs
        • AMP Analytics
        • Cordova
        • .NET
        • Go
        • Java
        • Node.js
        • PHP
        • Python
        • React Native
        • Ruby
        • Rust
        • Unity
        • SDK FAQs
        • rudderstack-android-sdk
          • Adding Application Class
          • Flushing Events Periodically
          • Android
        • rudderstack-flutter-sdk
          • Flutter SDK v1
          • Flutter v2
          • Flutter
        • rudderstack-ios-sdk
          • iOS
          • tvOS
          • watchOS
        • rudderstack-javascript-sdk
          • Data Storage in Cookies
          • Detecting Ad-blocked Pages
          • JavaScript
          • JavaScript SDK Enhancements
          • JavaScript SDK FAQs
          • Querystring API
          • Quick Start Guide
          • Version Migration Guide
          • consent-managers
            • Consent Managers
            • OneTrust
    • transformations
      • Access Token
      • FAQ
      • Transformations
      • Transformations API
    • user-guides
      • User Guides
      • administrators-guide
        • Troubleshooting Guide
        • Alerting Guide
        • Bucket Configuration Settings for Event Backups
        • Configuration Parameters
        • Event Replay
        • High Availability
        • Horizontal Scaling
        • Administrator's Guides
        • Infrastructure Provisioning
        • Monitoring and Metrics
        • Okta SSO Setup
        • OneLogin SSO Setup
        • RudderStack Grafana Dashboard
        • Software Releases
      • how-to-guides
        • How to Use Custom Domains
        • How to Develop Integrations for RudderStack
        • How to Configure a Destination via the Event Payload
        • How to Filter Events using Different Methods
        • How to Filter Selective Destinations
        • How to Submit a Pull Request for a New Integration
        • How-to Guides
        • How to Debug Live Destination Events
        • How to Use AWS Lambda Functions with RudderStack
        • create-a-new-destination-transformer-for-rudder
          • Best Practices for Coding Transformation Functions in JavaScript
          • How to Create a New Destination Transformation for RudderStack
        • implement-native-js-sdk-integration
          • How to Add a Device Mode SDK to RudderStack JavaScript SDK
          • How to Implement a Native JavaScript SDK Integration
        • rudderstack-jamstack-integration
          • How to Integrate RudderStack with Your JAMstack Site
          • How to Integrate Rudderstack with Your Angular App
          • How to Integrate Rudderstack with Your Astro Site
          • How to Integrate Rudderstack with Your Eleventy Site
          • How to Integrate Rudderstack with Your Ember.js App
          • How to Integrate Rudderstack with a Gatsby Website
          • How to Integrate Rudderstack with a Hugo Site
          • How to Integrate Rudderstack with Your Jekyll Site
          • How to Integrate Rudderstack with Your Next.js App
          • How to Integrate Rudderstack with Your Nuxt.js App
          • How to Integrate Rudderstack with Your Svelte App
          • How to Integrate Rudderstack with Your Vue App
      • migration-guides
        • Migrating from Blendo to RudderStack
        • Migrating Your Warehouse Destination from Segment to RudderStack
        • Migration Guides
        • Migrating from Segment to RudderStack
  • src
    • @rocketseat
      • gatsby-theme-docs
        • text
          • Home
Powered by GitBook
On this page
  • SDK setup requirements
  • Installing the SDK
  • Using the Android SDK on applications with minSDKVersion less than 20
  • Setting Android Permission
  • Initializing the RudderStack client
  • Enabling/disabling user tracking via the optOut API (GDPR Support)
  • Chromecast
  • Track
  • Identify
  • Screen
  • Group
  • Alias
  • Reset
  • Configuring your RudderStack client
  • Self-hosted control plane
  • Setting the Android device token
  • Setting the advertisement ID
  • Anonymous ID
  • Filtering events
  • Enabling/disabling events for specific destinations
  • 1. Passing destinations while initializing the SDK
  • 2. Passing destinations while making event calls
  • External ID
  • Debugging
  • Developing a device mode destination
  • FAQs
  • Do I need to add anything to my proguard-rules?
  • What is the Android version required to set up the RudderStack Android SDK?
  • I don't have an Application class to initialize my RudderStack client. What do I do?
  • How do I set the Android permissions?
  • Can I use the library with Maven?
  • How do I check whether a specific event is getting fired or not?
  • How do I get the user traits after making the identify call?
  • Can I disable event tracking until the user gives their consent?
  • How does the SDK handle different client/server errors?
  • Contact us

Was this helpful?

  1. docs
  2. stream-sources
  3. rudderstack-sdk-integration-guides
  4. rudderstack-android-sdk

Android

Detailed technical documentation on RudderStack’s Android SDK using Android Studio to send events from your Android device to various destinations.

PreviousFlushing Events PeriodicallyNextrudderstack-flutter-sdk

Last updated 2 years ago

Was this helpful?

The RudderStack Android SDK lets you track event data from your Android applications and send it to your specified destinations via RudderStack.

You can check the to get more a hands-on understanding of the SDK and its architecture.

SDK setup requirements

To set up the RudderStack Android SDK, the following prerequisites must be met:

  • You will need to set up a .

  • Once signed up, set up an Android source in the dashboard. For more information, follow . You should then see a Write Key for this source, as shown below:

  • You will also need a data plane URL. Follow for more information on the data plane URL and where to get it.

  • Finally, you will also need to install on your system.

Installing the SDK

As Bintray has sunset from 1st May, we're moving the Android SDK to Maven Central. All the versions from 1.0.10 are available in Maven Central only.

We distribute the Android SDK through . 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 under dependencies 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+'

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.

Using the Android SDK on applications with minSDKVersion less than 20

By default, the Android SDK does not support applications with minSDKVersion less than 20. You can add this support by following the steps below:

  • Add the following dependency to the build.gradle file of your application:

implementation 'com.google.android.gms:play-services-base:17.6.0'
  • Add the function tlsBackport() in your MainActivity as shown:

private fun tlsBackport() {
        try {
            ProviderInstaller.installIfNeeded(this)
            Log.e("Rudder", "Play present")
            val sslContext: SSLContext = SSLContext.getInstance("TLSv1.2")
            sslContext.init(null, null, null)
            sslContext.createSSLEngine()
        } catch (e: GooglePlayServicesRepairableException) {
            // Prompt the user to install/update/enable Google Play services.
            GoogleApiAvailability.getInstance()
                .showErrorNotification(this, e.connectionStatusCode)
            Log.e("Rudder", "Play install")
        } catch (e: GooglePlayServicesNotAvailableException) {
            // Indicates a non-recoverable error: let the user know.
            Log.e("SecurityException", "Google Play Services not available.");
            e.printStackTrace()
        }
    }
  • Finally, call the tlsBackport() function at the very beginning of your onCreate() method in MainActivity.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            tlsBackport()
        }
    }

Setting Android Permission

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.

Initializing the RudderStack client

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:

Kotlin JAVA

val rudderClient = RudderClient.getInstance(
    this,
    WRITE_KEY,
    RudderConfig.Builder()
        .withDataPlaneUrl(DATA_PLANE_URL)
        .withTrackLifecycleEvents(true)
        .withRecordScreenViews(true)
        .build()
)
RudderClient rudderClient = RudderClient.getInstance(
        this,
        WRITE_KEY,
        new RudderConfig.Builder()
                .withDataPlaneUrl(DATA_PLANE_URL)
                .withTrackLifecycleEvents(true)
                .withRecordScreenViews(true)
                .build()
);

We automatically track the following optional events:

  1. Application Installed

  2. Application Updated

  3. Application Opened

  4. Application Backgrounded

You can disable these events using the withTrackLifecycleEvents method and passing false. But it is highly recommended to keep them enabled.

Enabling/disabling user tracking via the optOut API (GDPR Support)

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:

Kotlin JAVA

rudderClient.optOut(true)
rudderClient.optOut(true);

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:

Kotlin JAVA

rudderClient.optOut(false)
rudderClient.optOut(false);

The optOut API is available in the RudderStack Android SDK from version 1.0.21.

Chromecast

Track

You can record the users' activity through the track method. Every user action is called an event.

A sample track event is as shown below:

Kotlin JAVA

rudderClient.track(
    "Product Added",
    RudderProperty()
        .putValue("product_id", "product_001")
)
rudderClient.track(
        "Product Added",
        new RudderProperty()
                .putValue("product_id", "product_001")
);

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

Identify

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.

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.

An sample identify event is as shown:

Kotlin JAVA

val traits = RudderTraits()
traits.putBirthday(Date())
traits.putEmail("abc@123.com")
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)
RudderTraits traits = new RudderTraits();
traits.putBirthday(new Date());
traits.putEmail("abc@123.com");
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);

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

Screen

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:

Kotlin JAVA

rudderClient.screen(
    "MainActivity",
    "HomeScreen",
    RudderProperty().putValue("foo", "bar"),
    null
)
rudderClient.screen(
    "MainActivity",
    "HomeScreen",
    new RudderProperty().putValue("foo", "bar"),
    null
);

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.

Group

The group call associates a user to a specific organization. A sample group call for the API is below:

Kotlin JAVA

rudderClient.group(
    "sample_group_id",
    RudderTraits().putAge("24")
        .putName("Test Group Name")
        .putPhone("1234567891")
)
    rudderClient.group(
        "sample_group_id",
        new RudderTraits().putAge("24")
            .putName("Test Group Name")
            .putPhone("1234567891")
    );

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

RudderStack doesn't persist the traits for the group across the sessions.

Alias

The alias call associates the user with a new identification. A sample alias call for the API is below:

Kotlin JAVA

rudderClient.alias("test_new_id")
rudderClient.alias("test_new_id");

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.

Reset

You can use the reset method to clear the persisted traits for the identify call. This is required for Logout operations.

Kotlin JAVA

rudderClient.reset()
rudderClient.reset();

Configuring your RudderStack client

You can configure your client based on the following parameters using RudderConfig.Builder:

Parameter
Type
Description
Default value

logLevel

Integer

Controls how much of the log you want to see from the SDK.

RudderLogger.RudderLogLevel.NONE

dataPlaneUrl

String

Your data plane URL.

https://hosted.rudderlabs.com

flushQueueSize

Integer

Number of events in a batch request to the RudderStack server.

30

dbThresholdCount

Integer

Number of events to be saved in the SQLite database. Once the limit is reached, older events are deleted from the database.

10000

sleepcount

Integer

Minimum waiting time to flush the events to the RudderStack server. The minimum value can be set to 1 second.

10 seconds

configRefreshInterval

Integer

The SDK will fetch the config from dashboard after the specified time

2 hours

trackLifecycleEvents

Boolean

Determines if the SDK will automatically capture the application lifecycle events.

true

recordScreenViews

Boolean

Determines if the SDK will automatically capture the screen view events.

false

autoCollectAdvertId

Boolean

Determines if the SDK will collect the advertisement ID.

false

controlPlaneUrl

String

A sample code snippet to configure your client using RudderConfig.Builder is shown below:

rudderClient = RudderClient.getInstance(
  this,
  <WRITE_KEY>,
  RudderConfig.Builder()
  .withDataPlaneUrl(<DATA_PLANE_URL>)
  .withSleepCount(1)
  .withLogLevel(RudderLogger.RudderLogLevel.VERBOSE)
  .build()
)

Self-hosted control plane

Setting the Android device token

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:

Kotlin JAVA

RudderClient.putDeviceToken("your_device_token")
RudderClient.putDeviceToken("your_device_token");

Setting the advertisement ID

By default, RudderStack collects the advertisement ID only if the following three conditions are met:

val rudderClient = RudderClient.getInstance(
    this,
    WRITE_KEY,
    RudderConfig.Builder()
        .withDataPlaneUrl(DATA_PLANE_URL)
        .withTrackLifecycleEvents(true)
        .withRecordScreenViews(true)
        .withAutoCollectAdvertId(true)
        .build()
)
  • com.google.android.gms.ads.identifier.AdvertisingIdClient is present in your application's class path.

  • limitAdTrackingis not enabled for your device.

To set your own advertisement ID, you can use the putAdvertisingId method, as shown:

RudderClient.putAdvertisingId(<ADVERTISING_ID>);

RudderStack sets gaid under context.device.advertisementId.

Anonymous 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.

An example of setting the anonymousId is shown below:

RudderClient.putAnonymousId(<ANONYMOUS_ID>);

To retrieve the anonymousId, you can use the following method:

RudderClient.getAnonymousId();

The method getAnonymousId is available from v1.0.11 onwards.

Filtering events

Enabling/disabling events for specific destinations

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:

Kotlin Java

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

The keyword All in the above snippet represents all the destinations the source is connected to. Its value is set to true by default.

You can pass the destination(s) specified in the above snippet to the SDK in two ways:

1. Passing destinations while initializing the SDK

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).

Kotlin Java

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

2. Passing destinations while making event calls

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.

Kotlin Java

rudderClient.track(
                    "Product Added",
                    RudderProperty()
                            .putValue("product_id", "product_001"),
                    option // passing the rudderoption object containing the list of destination you specified
            )
rudderClient.track(
                "Product Added",
                new RudderProperty()
                        .putValue("product_id", "product_001"),
                option // passing the rudderoption object containing the list of destination(s) you specified
        );

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.

External ID

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

Debugging

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:

Kotlin Java

val rudderClient: RudderClient = RudderClient.getInstance(
this,
YOUR_WRITE_KEY,
RudderConfig.Builder()
.withDataPlaneUrl(DATA_PLANE_URL)
.withLogLevel(RudderLogger.RudderLogLevel.DEBUG)
.build()
)
RudderClient rudderClient = RudderClient.getInstance(
    this,
    YOUR_WRITE_KEY,
    new RudderConfig.Builder()
        .withDataPlaneUrl(DATA_PLANE_URL)
        .withLogLevel(RudderLogger.RudderLogLevel.DEBUG)
        .build()
);

Developing a device mode destination

You can easily develop a device mode destination in case RudderStack doesn't support it already, by following the steps listed in this section.

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 the CustomFactory 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 the CustomFactory class on every reset() 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 the CustomFactory class on every flush() call made via the SDK which you can use to handle the destination-specific reset logic. You can make a flush call using the SDK as shown below:

Kotlin JAVA

rudderClient.flush()
rudderClient.flush();
  • Make sure you return a valid value from getUnderlyingInstance() as it is used by the Android SDK to validate CustomFactory.

  • Make sure you do not duplicate the value of FACTORY_KEY across multiple CustomFactory 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.

FAQs

Do I need to add anything to my proguard-rules?

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.** { *; }

What is the Android version required to set up the RudderStack Android SDK?

We currently support API 14: Android 4.0 (IceCreamSandwich) or higher.

I don't have an Application class to initialize my RudderStack client. What do I do?

How do I set the Android permissions?

Can I use the library with Maven?

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>

How do I check whether a specific event is getting fired or not?

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:"

How do I get the user traits after making the identify call?

You can get the user traits after making an identify call as shown in the following snippet:

Kotlin JAVA

    val traits = rudderClient!!.getRudderContext().getTraits()
    Map<String , Object> traitsObj = rudderClient.getRudderContext().getTraits();

Can I disable event tracking until the user gives their consent?

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)

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.

How does the SDK handle different client/server errors?

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).

Contact us

For more details, refer to this .

Follow our guide on for more information.

is a device that plugs into your TV or monitor with an HDMI port, and can be used to stream content from your phone or computer.

RudderStack supports integrating the Android SDK with your Cast app. Follow to build your Android sender app. Then, add the Android SDK to it.

Follow the for more details.

Change this parameter only if you are self-hosting the control plane. Check the section below for more information. The SDK will add /sourceConfig along with this URL to fetch the source configuration.

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 utility to host your own Control Plane, then follow and specify controlPlaneUrl in yourRudderConfig.Builder that points to your hosted source configuration file.

You shouldn't pass the controlPlaneUrl parameter during SDK initialization if you are using the dashboard from . This parameter is supported only if you are using our open-source to self-host your Control Plane.

withAutoCollectAdvertId is set to true during the , as shown:

When sending events to a destination via the , you can explicitly specify which events should be discarded or allowed to flow through - by whitelisting or blacklisting them.

Refer to the guide for more information on this feature.

Make sure the destination display name that you pass while specifying the destinations should exactly match the destination name as shown .

More information on the RudderStack device mode can be found in the guide.

Create a CustomFactory class by extending , as shown:

Follow our guide on to add an Application class.

Please refer to the section above to do this.

For more information on the optOut API, refer to the section above.

For queries on any of the sections covered in this guide, you can or start a conversation in our community.

If you come across any issues while using the Android SDK, you can open a new issue on our .

Android documentation
Adding an Application Class to Your Android Application
Google Chromecast
these instructions
Google Cast developer guide
Control Plane Lite
this guide
RudderStack Cloud Dashboard
Control Plane Lite
device mode
Client-side Event Filtering
here
RudderStack Connection Modes
RudderIntegration.java
How to Add an Application Class to Your Android App
Enabling/Disabling User Tracking via optOut API
contact us
Slack
GitHub Issues page
SDK initialization
Setting the Android Permission
https://api.rudderlabs.com
Self-hosted control plane
GitHub codebase
RudderStack account
this guide
this section
Android Studio
Maven Central
Github Badge
Android source write key