# Android SDK

## Add the SDK to your app

The Chartbeat Android SDK is a Java library providing Chartbeat tracking functionality to native Android apps. Like any other framework added to your project, the Chartbeat SDK provides a programming interface usable from your app code.

To get started with integrating the SDK, download the latest version directly from the [**Chartbeat Android SDK package page**](https://jitpack.io/#chartbeat/android_sdk/) by adding the JitPack repository to your build file:

```java
allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}
```

Add Chartbeat to the `dependencies` section in `app/build.gradle`, replacing the version number with the latest version listed [**here**](https://jitpack.io/#chartbeat/android_sdk/).

```java
implementation 'com.github.chartbeat:android_sdk:v1.6.7'
```

{% hint style="info" %}
**Note:** The above steps assume use of Gradle as your build system. For Maven, sbt, and leiningen, please see instructions [**here**](https://jitpack.io/#chartbeat/android_sdk/).
{% endhint %}

Add the following permissions in `app/src/main/AndroidManifest.xml`:&#x20;

```java
<!-- This permission is required to allow the application to send tracking information to Chartbeat -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

## Using the SDK

Chartbeat tracks each app visit by calling corresponding functions as the user interacts with your app. Implement the following steps for integrating the Chartbeat Mobile SDK for iOS or Android.

### Initialize the tracker

First, import the SDK wherever you’re using the tracker. All of the methods you need to access are public and static.

```java
import com.chartbeat.androidsdk.Tracker;
```

Start by initializing the tracker with the `setupTracker` function in your main activity, only when the app is in the foreground:`app/src/main/java/com/example/app/MainActivity.java`*.* Usually, this should be done in [**onCreate**](https://developer.android.com/reference/android/app/Activity.html#onCreate\(android.os.Bundle\)). If you have multiple entry points into your app, you may call this from any of them, but only the first call will be acknowledged.&#x20;

{% hint style="success" %}
**Tip:** Remember to replace `chartbeatAccountId` and `chartbeatSiteId` with your organization's Chartbeat account ID and site ID values.
{% endhint %}

#### Java:

```java
@Override
public void onCreate() {
  String chartbeatAccountId = "12345";
  String chartbeatSiteId = "mysite.com";
    
  super.onCreate();
  Tracker.setupTracker(chartbeatAccountId, chartbeatSiteId, this);
}
```

For example, `this` is the application-level Context.

#### Kotlin:

```kotlin
override fun onCreate() {
  super.onCreate();
    
  val chartbeatAccountId = "12345";
  val chartbeatSiteId = "mysite.com";    
  Tracker.setupTracker(chartbeatAccountId, chartbeatSiteId, applicationContext);
}
```

### Track user subscriber status

Beginning with Android SDK version 1.5.0, the Chartbeat Mobile SDK supports tracking subscriber data similar to our [**JavaScript subscriber engagement integration**](/cbp/tracking/standard-websites/subscriber-engagement.md) for standard websites. These functions are optional and can be skipped if your corresponding website does not utilize our JavaScript subscriber status integration linked above.

For proper tracking, it is important to call these functions before the first call to `trackView()`:

Call `setUserPaid()` to specify a user as a paid subscriber.

Call `setUserLoggedIn()` to specify a user as a registered user.

Call `setUserAnonymous()` to specify a user as an unregistered guest user.

No additional information needs to be passed to these methods or functions. If at any time a user’s subscription status changes during their session, simply call one of the above functions to ensure proper tracking.

### Track screen views

Add the `trackView` code (below) to any view you want Chartbeat to track.

If you have views in your app that do not correspond to a page on your website, you can track user interactions on that screen by setting a `viewId` that does not conflict with other page paths from your site. Traffic for this view will then be tracked a separate page in your dashboard. For example, you can track users in your app’s table of contents by setting the `viewId` to something like `https://mysite.com/nativeapp/main-toc`.

Pass section and author data for every view you track to ensure consistency between different views. Call `setSections` and `setAuthors` with an array of strings for each after calling `trackView`. Any sections and authors you set will stay set until you set a different set of values. If the user is navigating from a view with sections or authors to another view with no applicable sections or authors, you should set the sections or authors to an empty array.

{% hint style="warning" %}
**Tip:** Chartbeat uses the "|" character for a splitting process when organizing section and author values, so it is recommend to avoid this character when defining these variables.
{% endhint %}

#### Java:

```java
import com.chartbeat.androidsdk.Tracker;

class SomeActivity : AppCompatActivity() {

  @Override
  public void onCreate() {
  
    Tracker.trackView(
      getBaseContext(), // Context for the current view
      "https://mysite.com/article/12345.html", // View ID
      "My Page Title", // View Title
    );
  }
  
}
```

#### Kotlin:

```kotlin
import com.chartbeat.androidsdk.Tracker;

class SomeActivity : AppCompatActivity() {

  @Override
  public void onCreate() {
  
    Tracker.trackView(
      baseContext, // Context for the current view
      "https://mysite.com/article/12345.html", // View ID
      "My Page Title", // View Title
    );
  }
  
}
```

### Track user interactions

Call the `userInteracted` function whenever the user interacts with your view to accurately measure user engagement with your content. Our Recommendation is to call this from within the `onUserInteraction` function of your activity. Register writing engagement by calling the `userTyped` function whenever the user starts typing something.

```java
  @Override
  public void onUserInteraction() {
      super.onUserInteraction();
      Tracker.userInteracted();
  }
```

### Stop the tracker

Call the `userLeftView` function (e.g. from your activities’ onPause functions) whenever the app leaves the foreground to stop the tracking for the current session.

Call the `pauseTracker` function when the user navigates to a view you don’t want to track.

Call `trackView` again when the app returns to the foreground.

### IP Truncation

For clients in the EU, follow these steps to point traffic to our proxy layer that de-identifies IP addresses within the EU.

When [initializing the tracker](#initialize-the-tracker), add `true` as the last variable in the `Tracker.setupTracker()` function:

#### Java:

```java
@Override
public void onCreate() {
  String chartbeatAccountId = "12345";
  String chartbeatSiteId = "mysite.com";
    
  super.onCreate();
  Tracker.setupTracker(chartbeatAccountId, chartbeatSiteId, this, true);
}
```

### ProGuard and R8

If you enable ProGuard or R8 in your release build, ensure the following rules are added to your `proguard-rules.pro` file to prevent issues with Retrofit and RxJava dependencies:

```
-dontwarn rx.**
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keep class rx.** { *; }
-keepattributes Signature, InnerClasses, EnclosingMethod
```

## Next steps

Next up is our iOS SDK implementation steps, or skip to the [**integration QA article**](/cbp/tracking/mobile-app-sdks/qa-mobile-sdk-integration.md) if your team will not implement tracking for an iOS app.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.chartbeat.com/cbp/tracking/mobile-app-sdks/android-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
