# Hailbell on Android

The Kotlin and Jetpack Compose SDK mirrors the Swift one: the same API names, the same chat screen, the same server. This page takes an Android app to a live support chat with push replies.

Requirements: minSdk 26, compileSdk 36 or later, Java 17. The library brings OkHttp, Coil, Compose, `lifecycle-process` and Play's in-app review library. It has no Firebase dependency: the app passes FCM tokens and messages in. Its manifest adds `INTERNET`, `POST_NOTIFICATIONS` and the chat activity, and Gradle merges them.

## 1. The app in Hailbell, and the person's dashboard steps

1. **Sign up** (the person) at `https://app.hailbell.com/?signup=1` with **Continue with Google** (or an emailed sign-in link), if they haven't, and connect you over MCP.
2. **Make the Android platform** (you): `list_apps` first. If the app isn't there, `create_app` with `platform: "android"` and `packageName` set to the app's `applicationId`. If it's there without Android, `add_platform` with its `productId` (and `packageName`). Use the returned App ID (`app_...`) in code. The package name is saved as the platform's **Play Store package name** for review cards and the store icon. The person can also do this in the dashboard (**Settings › New app**, or **Add Android** on the app's page).
3. **Upload the Firebase key** (the person) in **Settings › Push keys**. In the Firebase console, open the app's project, **Project settings › Service accounts**, and press **Generate new private key**. That downloads a service account JSON file; upload it in Hailbell. One file per Firebase project. Hailbell checks it with Google before saving it and never shows it again. The person does this; never ask for the JSON in the chat or open it yourself.
4. **Firebase project ID** (you): call `update_setup` with `firebaseProject` set to `project_info.project_id` from the app's `google-services.json` (the person can instead enter it in **Push › Setup**, Android card). Hailbell sends replies through FCM with that project's key and checks Firebase ID tokens against it. `get_setup` shows `ready.fcm` true (and the dashboard card **Ready**) once the account has a key for that project; if it stays false, check the project ID and that the key in **Settings › Push keys** is from the same project.
5. Under **Chat design** (the person), use the same accent, title and team photo as the iOS app so both chats look the same.
6. **Reviews** on the Android platform row: the **Play Store package name**, already filled in if you passed `packageName`. Review cards open the Play rating sheet.

## 2. Add the library

The library is published through JitPack. Add the repository in `settings.gradle.kts`:

```kotlin
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://jitpack.io") }
    }
}
```

Projects that still declare repositories in the root `build.gradle.kts` (`allprojects { repositories { ... } }`) add the same `maven { url = uri("https://jitpack.io") }` line there.

Then the dependency in the app's `build.gradle.kts`:

```kotlin
implementation("com.github.vidursaini:hailbell-android:1.2.0")
```

The source is at https://github.com/vidursaini/hailbell-android. The package is `com.hailbell` (`com.hailbell.Hailbell`, `com.hailbell.HailbellPush`).

## 3. Wrap every call in one object

Emptying one string turns the chat off. Drop the Superwall parts if the app doesn't use it.

```kotlin
object HailbellSupport {
    private const val APP_ID = "app_XXXXXXXX"   // "" turns the chat off and hides its entry points
    val isEnabled get() = APP_ID.isNotEmpty()

    fun configure(context: Context) {
        if (!isEnabled) return
        Hailbell.configure(context, APP_ID)
        Hailbell.teamPhoto = BitmapFactory.decodeResource(context.resources, R.drawable.support_photo)
        Hailbell.setPaywallPlacements(listOf("winback", "support_offer"))
        Hailbell.onPaywall = { placement, purchased ->
            val handler = PaywallPresentationHandler().apply {
                onDismiss { _, result -> if (result is PaywallResult.Purchased) purchased() }
            }
            Superwall.instance.register(placement, mapOf("entry_point" to "hailbell_chat"), handler)
        }
        FirebaseMessaging.getInstance().token.addOnSuccessListener { Hailbell.setPushToken(it) }
    }

    fun open(activity: Activity, source: String) {
        Hailbell.track("chat_opened", mapOf("source" to source))
        Hailbell.open(activity)
    }
}
```

Call `configure` from `Application.onCreate()`. Send `appVersion`, `plan` and `superwallUserId` (or `revenueCatUserId` from `Purchases.sharedInstance.appUserID`). With Superwall, also send `superwallAliasId` from `Superwall.instance.userAttributes["aliasId"]`, so purchases made before you identified the user (an onboarding paywall) match too with `Hailbell.setMetadata(map)` whenever the plan changes. Values are strings. `appVersion`, `os` and `locale` are sent automatically.

The team photo works well as a small WebP in `res/drawable-nodpi`, so the header shows it at once and offline. `Hailbell.darkMode` (default null, follows the phone) can be set to true for an always-dark app.

## 4. Entry points

1. A **"Chat with us"** row in Profile or Settings, with the `Forum` icon.
2. A **header button**: a 40 dp circle with the `HeadsetMic` icon in the brand accent, and a red dot while `Hailbell.unreadCount` (a `StateFlow<Int>`) is above zero.
3. An **app shortcut** "Chat with us": a static shortcut in `res/xml/shortcuts.xml` with its own action, handled in the main activity by opening the chat.
4. Optional: a **"Need help?" bar** above the tab bar for free users some time after they closed a paywall.

`Hailbell.open(activity)` starts the chat as its own translucent activity: a full-height sheet with rounded top corners and a grabber, dismissed by dragging down or with back.

## 5. Signed-in users (optional)

With a backend: sign an HS256 JWT with the identity secret (`sub` = user id) and pass `Hailbell.identify(identityToken = jwt)`.

Firebase Auth apps pass the ID token whenever a non-anonymous user signs in, and the chat follows the Firebase uid to new phones:

```kotlin
Hailbell.identify(name = name, email = email) {
    suspendCancellableCoroutine { cont ->
        FirebaseAuth.getInstance().currentUser?.getIdToken(false)
            ?.addOnSuccessListener { cont.resume(it.token) }
            ?.addOnFailureListener { cont.resume(null) } ?: cont.resume(null)
    }
}
```

When a Google or Apple account was linked to an anonymous Firebase user, `displayName` and `email` can be empty on the user while `user.providerData` still has them. Fall back to that.

Call `Hailbell.reset()` on sign-out. In the delete-account flow, call `Hailbell.deleteData()` first and stop if it throws, so a retry deletes both. Google Play requires in-app account deletion to remove this data too.

## 6. Push for replies

1. Add `firebase-messaging` to the app and a `FirebaseMessagingService`:

   ```kotlin
   class SupportPushService : FirebaseMessagingService() {
       override fun onNewToken(token: String) = Hailbell.setPushToken(token)
       override fun onMessageReceived(message: RemoteMessage) {
           val handled = HailbellPush.handleMessage(this, message.data, message.notification?.title, message.notification?.body)
           if (!handled) {
               // the app's own pushes
           }
       }
   }
   ```

2. Register it in the manifest with the `com.google.firebase.MESSAGING_EVENT` intent filter. If the app already has a messaging service, add the two Hailbell calls to it instead.

How pushes behave:

- Replies are notification messages on channel `hailbell_replies` ("<App> Support"), with `click_action` `HAILBELL_OPEN_CHAT`. Tapping opens the chat. In the background Android shows them without calling the service; in the foreground `handleMessage` shows them unless the chat is on screen. The SDK creates the channel on `configure`.
- Campaign pushes are data-only, on a second channel "Offers and updates" (`hailbell_offers`). `handleMessage` draws them itself in the foreground and background, so delivery is counted. The service must pass **every** message to it.
- When the team opens a chat, Hailbell sends a silent data message (`hb_check`) to learn whether the customer deleted the app. `handleMessage` returns false and shows nothing. Don't show a notification for data messages the app doesn't recognise, or customers see a blank one.
- On Android 13 and later, after the first message the chat offers to turn on notifications. Set `Hailbell.asksForNotifications = false` if the app asks itself.

### Marketing opt-in

On Android the system notification category is the switch. Read it at launch and on every resume:

```kotlin
override fun onResume() {
    super.onResume()
    val nm = NotificationManagerCompat.from(this)
    val channel = nm.getNotificationChannel(OFFERS_CHANNEL_ID)
    HailbellPush.setMarketing(nm.areNotificationsEnabled() &&
        (channel == null || channel.importance != NotificationManager.IMPORTANCE_NONE))
}
```

Calling it before `Hailbell.configure` is safe; the SDK keeps the value for the next subscribe.

If the app already has an offers channel people know, keep its ID (rename it "Offers and updates" if you like, but never delete it and make a new one: Android hides a category that never posted). Set `HailbellPush.offersChannel = "<its id>"` before `Hailbell.configure`, and have the person enter the same ID as **Offers channel ID** in **Push › Setup** (or call `update_setup` with `androidOffersChannel`). The SDK then leaves channel creation to the app.

**A push that opens a paywall:** send any deep link the app doesn't handle to Superwall once Superwall is ready (on a cold start, retry for a couple of seconds). Add a `deepLink_open` campaign in the Android Superwall app (host `offer`, source `support`, no active entitlement) and use `<scheme>://offer?source=support` as the push URL.

## 7. What comes with the library

Text and up to 4 photos (system photo picker, no storage permission, JPEG under 1.4 MB), ticks, typing, the online dot, an offline cache of 100 messages, review and offer cards, the AI notice and "AI" label, and the chat's own words in 14 languages. Colours follow the dashboard's Chat design.

## Bug reports (optional)

```kotlin
Hailbell.shakeToReport = true                     // off by default
Hailbell.trackScreen("Settings")                  // last 10 screens go with a report
Hailbell.reportBug(activity)                      // from a "Report a problem" button
Hailbell.log("Restore tapped")                    // SDK 1.2.0: last 50 lines, kept in memory
OkHttpClient.Builder().addInterceptor(Hailbell.networkInterceptor).build()   // records failed requests by itself
Hailbell.logRequest("POST", url, 422)             // or by hand, for other HTTP clients
```

A report carries a screenshot the customer can mark up or remove, their description, app version and build, device, Android version, language and the screens. From SDK 1.2.0 it also carries the log lines and the last 10 failed requests (status 400 or more, or no answer): method, address, status and time, never bodies or headers. Query strings are dropped and secret-looking parts of addresses (emails, tokens, keys, long ids, JWTs, phone numbers) become `:redacted`; passwords, tokens, API keys and Bearer values in log lines become `[redacted]`, on the phone and again on the server. Nothing leaves the phone until the customer taps Send. Never put personal data in `log` lines anyway. The team can ask for a report with a button (dashboard, `!bugreport`, Slack), and the AI attaches one when a customer on SDK 1.2.0 or later describes a bug.

## 8. Google Play submission

Data safety form, in addition to what the app already declares:

| Data type | Collected for |
| --- | --- |
| Personal info › Name, Email address | App functionality, only if passed to `identify` |
| Messages › Other in-app messages | App functionality (support chat) |
| Photos and videos › Photos | App functionality, only those the user attaches |
| App info and performance › Diagnostics | App version, Android version, device model, language and time zone |
| App activity › App interactions | `track` signals, push delivery and open counts |
| Device or other IDs | The chat's install id and the FCM token |

Data is encrypted in transit and can be deleted through the in-app account deletion. Keep user-facing release notes short and general.

## Checklist

- [ ] App created with the Android platform, Firebase project ID set in Push › Setup
- [ ] Firebase service account uploaded by the person in Settings › Push keys; the Android card says Ready
- [ ] JitPack repository and `com.github.vidursaini:hailbell-android` added
- [ ] `HailbellSupport.kt` with the App ID, `configure` in `Application.onCreate()`
- [ ] Metadata: `appVersion`, `plan`, `superwallUserId` or `revenueCatUserId`
- [ ] At least one entry point
- [ ] `FirebaseMessagingService` passes tokens and every message to Hailbell
- [ ] `reset()` on sign-out, `deleteData()` in account deletion
- [ ] Marketing synced from the system category in `onResume`
- [ ] Tested on an emulator with Google Play or a phone: message, reply push with the chat closed, deletion then a cold launch
- [ ] Data safety answers drafted for the person
