> ## Documentation Index
> Fetch the complete documentation index at: https://docs.castled.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Getting Started with Android SDK

> [!NOTE]
>
> **Prerequisites**
>
> * [Castled CEP account is already setup](https://docs.castled.io/account-management/user-signup.md)

The Castled Android SDK enables mobile applications running on Android devices to receive push, in-app and inbox notifications originating from the Castled Customer Engagement Platform.
The steps outlined below will assist your Android app developers in integrating the SDK with your mobile application

## SDK installation

**Gradle**

Applicable if your project uses **Gradle** for managing dependency. Add `castled-notifications` as a dependency in the `build.gradle` file of your Android application module.

```groovy build.gradle
    ...
    dependencies {
        ...
        implementation 'io.castled.android:castled-notifications:<sdk-latest-version>'
    }
```

Replace `latest-version` with the latest version number of the SDK found here. Sync the gradle file to pull the dependencies just added.

**Maven**

Applicable if your project uses **Maven** for managing dependency. Add the following snippet in your module `pom.xml` file as a child of `dependencies`

```xml pom.xml
    <dependency>
        <groupId>io.castled.android</groupId>
        <artifactId>castled-notifications</artifactId>
        <version>sdk-latest-version</version>
    </dependency>
```

Replace `sdk-latest-version` with the latest version of the sdk.

## SDK initialization

The next step is to initialize the SDK. Initialization is typically done in the `onCreate` method of your
`Application` class as follows.

```kotlin MyApplicationClass.kt
class MyApplicationClass : MultiDexApplication() {
    override fun onCreate() {
        super.onCreate()

        // SDK initialization
        CastledNotifications.initialize(
            this, CastledConfigs.Builder()
                .appId("<app-id>")
                .location(<location>)
                .build()
        )
        ...
    }
    ...
}
```

* `app-id` is a unique key associated with your Castled account. It can be found in the Castled dashboard at **Settings > Api Keys**.
* `location` is the region where you have your Castled account.

```kotlin CastledConfigs.kt
    enum class CastledLocation {
        US,   // United States
        IN,   // India
        AP    // Asia Pacific
    }
```

### User Identification

To identify the user associated with this app instance, use the following method. This is typically invoked immediately after user completes the
sign-in flow of your app. `user-id` is the id that you use internally within your organisation to identify a user.

```kotlin

// User identification
CastledNotifications.setUserId(context, "<user-id>")
```

> [!NOTE]
>
> It is recommended to pass an optional **user-token** as the third parameter to
> `setUserId` to mitigate any risk of user impersonation. In the absence of a
> **user-token**, no additional verifications will be done to enforce user
> authenticity. If your **user-id** is random id such as a UUID, **user-token**
> is probably not required. More info on **user-token** can be found in the next
> section.

### Secure User Identification

`user-token` is a unique token for each user generated by your app server. This token is usually issued by the app server after the user
completes the login flow within your app.

```kotlin

// Secure user identification
CastledNotifications.setUserId(this, "<user-id>", "<user-token>")
```

`user-token` is basically a Base64 encoded **Hash-based Message Authentication Code** (HMAC). Ensure the hash computation happens in your app server so that `api-key`
is not exposed. You can create an `api-key` in the **Setting > API Keys** page within your Castled account. Contact Castled support for help with integration.

Find sample server code snippets to generate **HMAC** for the `user-id`.

```java java
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;

    public static String calculateHMAC(String userId, String apiKey) throws Exception {
        // Get an instance of the HMAC using SHA-256 hashing algorithm
        Mac sha256Hmac = Mac.getInstance("HmacSHA256");

        // Create a SecretKeySpec using the provided key
        SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");

        // Initialize the Mac with the secret key
        sha256Hmac.init(secretKey);

        // Compute the HMAC of the given data
        byte[] rawHmac = sha256Hmac.doFinal(userId.getBytes(StandardCharsets.UTF_8));

        // Convert the HMAC bytes to a Base64 encoded string
        return Base64.getEncoder().encodeToString(rawHmac);
    }
```

```go go
    import (
        "crypto/hmac"
        "crypto/sha256"
        "encoding/base64"
        "fmt"
    )

    func calculateHMAC(message string, apiKey string) string {
        key := []byte(apiKey)
        h := hmac.New(sha256.New, key)
        h.Write([]byte(message))

        // Encoding the HMAC as a Base64 encoded string
        return base64.StdEncoding.EncodeToString(h.Sum(nil))
    }
```

#### FAQ

> **How do I rotate the Api Key?**
>
> At your server side you can keep the `Api Key` as some config that can be
> easily changed with minimal or no code change. So when you want to rotate
> the key, create a new key from Castled dashboard, update the new key at your
> server side. Ideally you shouldn't disable old token immediately as new user
> token is updated only when `setUserId()` is called. You should allow some grace
> period before disabling the old `Api Key` so that all users gets the updated user token.

### User Logout

To remove the user association with a particular app instance. Typically invoked as part of the user sign-out flow within the app. Once invoked, the app won't be able to
receive any messages or notifications sent from Castled until the user sign-in again to the app again.

```kotlin
// User logout
CastledNotifications.logout()
```

## SDK Configs

This section covers the basic configurations available in the SDK. Use these configs if you want to enable specific mobile communication channel or want to override default behavior.

| Config Name | Description | Default Value |
| - | - | - |
| enablePush | Enables push notification feature | false |
| enablePushBoost | Enhances push notification delivery rates on Android devices with the advanced push boost feature | false |
| enableInApp | Enables In App notification feature | false |
| enableAppInbox | Enables App Inbox notification feature | false |
| enableTracking | Enables tracking of User attributes or App events | false |
| enableSessionTracking | Enables tracking of User Sessions | true |
| location | Preferred server location | US |
| skipUrlHandling | Disables the click action handling by the SDK. Set when app handles the notification action itself | false |

Please find below a sample snippet to enable Push Notification and using Castled US server location.

```kotlin MyApplicationClass.kt
class MyApplicationClass : MultiDexApplication() {
    override fun onCreate() {
        super.onCreate()

        // SDK initialization
        CastledNotifications.initialize(
            this, CastledConfigs.Builder()
                .apiKey("<api-key>")
                .enablePush(true)
                .location(CastledLocation.US)
                .build()
        )
        ...
    }
    ...
}
```

## SDK Permissions

By default `AndroidManifest.xml` of the SDK includes the following permission requests. No developer action is required here.

```xml

<!-- Castled SDK needs this permission to sync user token and campaign events  -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Castled SDK will use this permission to decide when to make network calls -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.