# SDK integration

*This guide assumes that you've already followed the* [*prerequisites*](https://doc.batch.com/developer/sdk/android/prerequisites)*.*

### Integrating the SDK

Batch is compatible with **Android 5.0 (Lollipop / API Level 21)** and higher.

Simply add in your app's *build.gradle*:

{% tabs %}
{% tab title="Kotlin" %}

```kts
implementation("com.batch.android:batch-sdk:3.3+")
```

{% endtab %}

{% tab title="Groovy" %}

```groovy
implementation 'com.batch.android:batch-sdk:3.2+'
```

{% endtab %}
{% endtabs %}

*Exact version numbers can be found in the* [*changelog*](https://doc.batch.com/developer/sdk/android/sdk-changelog)*.*

Using Batch require you to enable at least [Java 8 support through desugaring](https://developer.android.com/studio/write/java8-support) in your project. Add the following to your `build.gradle` if not already present:

{% tabs %}
{% tab title="Kotlin" %}

```kts
android {
  // ...
  compileOptions {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
  }
}
```

{% endtab %}

{% tab title="Groovy" %}

```groovy
android {
  // ...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}
```

{% endtab %}
{% endtabs %}

### Adding push notifications support

*This guide assumes that you've already setup your Firebase project in your Android application.*\
\&#xNAN;*If you didn't, please follow* [*Firebase's Get Started tutorial*](https://firebase.google.com/docs/android/setup) *or use the Firebase Cloud Messaging wizard in Android studio.*

In order to enable push notifications support, Batch requires `firebase-messaging` 22.0.0 or higher. We highly recommend to use the latest version when possible. Add the following to your *build.gradle*, if not already present:

{% tabs %}
{% tab title="Kotlin" %}

```kts
implementation("com.google.firebase:firebase-messaging:22.0.0")
```

{% endtab %}

{% tab title="Groovy" %}

```groovy
implementation 'com.google.firebase:firebase-messaging:22.0.0'
```

{% endtab %}
{% endtabs %}

### Optional dependencies

#### In-App Review

The Play In-App Review library, which enables the use of the Google Play In-App Review API from In-App messages and other features:

{% tabs %}
{% tab title="Kotlin" %}

```kts
implementation("com.google.android.play:review:2.0.1")
```

{% endtab %}

{% tab title="Groovy" %}

```groovy
implementation 'com.google.android.play:review:2.0.1'
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
If you are using Batch SDK < 1.21 you should use the Play Core library instead:\
`implementation("com.google.android.play:core:1.9.0")`.
{% endhint %}

### Your first start

You are now ready to setup Batch.

#### Starting the SDK

The `start` function should be called only once during your application lifetime to set up the SDK. As an application can be started without entering an activity, it is *very* important that you call any of Batch's global setup methods in an `Application` subclass.

**In your Application subclass:**

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
class YourApp: Application() {
  override fun onCreate() {
    super.onCreate()
    
    Batch.start("YOUR_API_KEY")
    registerActivityLifecycleCallbacks(BatchActivityLifecycleHelper())
    // You should configure your notification's customization options here.
    // Not setting up a small icon could cause a crash in applications created with Android Studio 3.0 or higher.
    // More info in our "Customizing Notifications" documentation
    // Batch.Push.setSmallIconResourceId(R.drawable.ic_notification_icon)
  }
}
```

{% endtab %}

{% tab title="Java" %}

```java
public class YourApp extends Application {
  @Override
  public void onCreate() {
    super.onCreate();

    Batch.start("YOUR_API_KEY");
    registerActivityLifecycleCallbacks(new BatchActivityLifecycleHelper());
    // You should configure your notification's customization options here.
    // Not setting up a small icon could cause a crash in applications created with Android Studio 3.0 or higher.
    // More info in our "Customizing Notifications" documentation
    // Batch.Push.setSmallIconResourceId(R.drawable.ic_notification_icon);
  }
}
```

{% endtab %}
{% endtabs %}

`"YOUR_API_KEY"` is your Batch SDK API key. You'll find it in ⚙ Settings → General.

{% hint style="info" %}
You can find more information on what you can customize on your notifications and how [here](https://doc.batch.com/developer/sdk/android/advanced/customizing-notifications).
{% endhint %}

#### Overriding OnNewIntent

As `singleTop`/`singleTask`/`singleInstance` activities only get their new intents in `onNewIntent` when brought up to the front, you will need to call `Batch.onNewIntent()` in them to let Batch know about it.

A common way to implement this is to make a base activity and add `Batch.onNewIntent` in all of them:

**In your Activity subclass:**

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
open class BaseActivity : AppCompatActivity() {
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Batch.onNewIntent(this, intent)
    }
}
```

{% endtab %}

{% tab title="Java" %}

```java
public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Batch.onNewIntent(this, intent);
    }
}
```

{% endtab %}
{% endtabs %}

#### Requesting the notification permission

Since Android 13, your app needs to request for the permission to display notifications. This can be done as following:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
// If you don't care of the permission result
Batch.Push.requestNotificationPermission(this)
// or
// If you need to handle the permission result
Batch.Push.requestNotificationPermission(this) {
  // Handle whether the permission is granted or not.
}
```

{% endtab %}

{% tab title="Java" %}

```java
// If you don't care of the permission result
Batch.Push.requestNotificationPermission(this);
// or
// If you need to handle the permission result
Batch.Push.requestNotificationPermission(this, granted -> {
  // Handle whether the permission is granted or not.
});
```

{% endtab %}
{% endtabs %}

To know when you should request the permission to your users, we recommend you to follow the [android best practices](https://developer.android.com/develop/ui/views/notifications/notification-permission#best-practices).

### Testing your integration

*Congratulations on finishing the bulk of the integration!*

After deploying a build to your device or an Google Play enabled simulator, open the Logcat tab of Android Studio. You should see the following logs:

```markdown
I/Batch: Installation ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```

#### Your first notification

**1. Obtaining your device token**

You can find your device's token using the [debug tool](https://doc.batch.com/developer/sdk/android/profile-data/debug) or locating the token Batch posts to the logcat *(*[*see here*](https://developer.android.com/tools/debugging/debugging-studio) *to know more)*:

```
I/Batch: Push - Registration ID/Push Token (FCM-Token): <your device token>
```

If you don't see a push token, there might be an error in the logs describing what happened. See our [troubleshooting documentation](https://doc.batch.com/developer/sdk/troubleshooting#common-issues) for more info.

{% hint style="info" %}
Push notifications are not supported in all emulators. Please use a physical device or a Google API/Google Play emulator to test them.
{% endhint %}

**2. Obtaining your Installation ID**

You can then retrieve the Installation ID, which represents an installation of your app on a device, by calling the following method:

```java
Batch.User.getInstallationID();
```

While Batch prints this in the debug console on start, displaying it in a settings or about page enables users to send you this identifier. This is useful for debugging, sending test notifications, etc.

**3. Sending a test push notification**

Batch enables you to send a test notification to the application installation currently running on your device.

To do so, open the dashboard and go to ⚙ Settings → Debug. Enter your Installation ID, hit `Debug` and then click on **"Send Test Push"**.

![Send Test from Debug](https://38998153-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FCL8wF0y1T2vLnm3yR2MW%2Fuploads%2F9tXIqqSmkaMLleeNs9GE%2Fdashboard_android_debug_push_test.png?alt=media\&token=e333b658-1eb4-44d0-9bd4-a10fe852da6f)

You should receive a notification on your device. If not, or if you can't find your Installation ID, the SDK might not be properly configured.

If you need to send push notifications to your device on a regular basis, then you should add your ID as a test device by clicking the **"Save as a test device"** button.

### Troubleshooting

If you're having trouble integrating the SDK, check our [troubleshooting documentation](https://doc.batch.com/developer/sdk/android/troubleshooting).

### What's next

*Congratulations on finishing your Batch integration!*

Here are a couple of extra steps you can take before releasing your app:

* **Small icon / Accent color**: Make sure the small icon you are using is **opaque white**. We also recommend you use an accent color. You will find more information [here](https://doc.batch.com/developer/sdk/advanced/customizing-notifications#small-icon).
* **Mobile Landings**: Make sure [Mobile Landings](https://doc.batch.com/developer/sdk/android/mobile-landings) are set up correctly.
* **Custom user identifier**: Add support for [custom user identifiers](https://doc.batch.com/developer/sdk/android/profile-data/custom-user-id) if you are planning to use the [Transactional](https://doc.batch.com/developer/api/mep/transactional) or the [Profile](https://doc.batch.com/developer/api/cep/profiles) APIs.
* **Analytics**: Add an [event dispatcher](https://doc.batch.com/developer/sdk/android/event-dispatchers) to automatically track your campaigns in your third-party analytics tool.
* **Token import**: [Import your existing tokens](https://doc.batch.com/getting-started/dashboard/customer-engagement-platform/21-cep-profiles/10-import-tokens) if you're coming from another push provider.
