Android SDK
Register Endpoints and complete Login with the Android SDK.
Native Android SDK for push Subscriptions, remote notification display, delivery ACKs, and local timers. Maven coordinate: com.comraid:comraid.
Package namespace com.comraid.android. Vocabulary: Endpoint / Subscription, external_user_id, Identity verification JWT (login(..., jwt)), Contact Attributes, Subscription Properties. Canonical package README: comraid-android.
Use a publishable App ID (cr_app_…) in the mobile SDK. Keep secret API keys (cr_sk_…) on your backend only — never ship them in the Android app.
Automatic Properties and sessions
On register and eligible app foregrounds the SDK sends app/SDK version, OS, model,
locale, language, IANA timezone and country, and POSTs
/session (debounced ~30 minutes
since last background). There is no public session method — use
setDeviceProperties only to override auto-collected fields.
Server-side Notification sends (Single send, Broadcast, Multi-send) use Message / Campaign
HTTP resources (/messages, /campaigns). Delivery outcomes are
sent, delivered, opened, failed, and skipped; Message statuses include
scheduled, preparing, processing, completed, failed, and cancelled.
See Notifications and API Reference.
Install
Add com.comraid:comraid from Maven Central and Firebase Messaging (the host app owns the Firebase project).
dependencies {
implementation("com.comraid:comraid:<version>")
implementation("com.google.firebase:firebase-messaging")
}Declare com.comraid.android.internal.ComraidMessagingService (or a subclass) in the host
manifest for FCM token rotation (onPushTokenRefresh), remote display, and durable
delivered/opened ACKs. ComRaid never sends an FCM notification block on Android: every
alert Notification is a data message, and this service presents it (title, body, image,
actions, Category channel, sound, badge, grouping) and enqueues a delivered ACK — including
when the app is in the background or was swiped closed (as long as the OS delivers FCM).
Data-only Notifications are never shown. React Native on Android uses the same native
service. Configure FCM credentials under Push → Push settings → Platforms → Android — FCM.
Related: Push providers, Notifications,
Acknowledgements.
Getting started
Configure early in Application.onCreate with a publishable App ID (cr_app_…). The default
channel is created here before permission / token acquisition (Android 13+), and category
channels sync in the background. Then request
permission (or call the non-blocking register when already granted) and login to bind
the Subscription to a Contact.
ComRaid.configure(
applicationContext,
ComRaidConfiguration(
appId = "cr_app_your_id",
// apiBaseUrl = "http://10.0.2.2:8080", // optional; default https://api.comraid.io
smallIconResourceId = R.drawable.ic_notification,
// accentColor = 0xFF5474B4.toInt(), // optional tint for SDK-drawn notifications
),
)
val caps = ComRaid.capabilities(applicationContext)
// caps.notificationsEnabled, caps.exactAlarmsAvailable
ComRaid.requestPermission(activity) { granted ->
if (granted) {
ComRaid.login("user_123", jwt = jwtFromYourBackend)
}
}
// or when permission is already granted:
ComRaid.register { result ->
result.onSuccess {
ComRaid.login("user_123", jwt = jwtFromYourBackend)
}
}Method reference
Hand-written Depth B reference for the public ComRaid surface. Grouped by lifecycle.
Examples are clustered per group (not every method).
Configure
configure(context: Context, configuration: ComRaidConfiguration)
Stores App ID / API base URL, creates the default channel, starts a background sync of
category channels, and prepares the runtime. Call once from Application.onCreate before
permission, register, schedule, or ACKs. No network I/O runs on the calling thread.
| Parameter | Type | Description |
|---|---|---|
context | Context | Any context; the SDK keeps applicationContext. |
configuration | ComRaidConfiguration | appId (cr_app_…), optional apiBaseUrl, channel defaults, smallIconResourceId, optional accentColor. |
Returns: Unit. Throws if appId is blank.
capabilities(context: Context): ComRaidCapabilities
Local capability probe (no network): whether notifications are enabled and whether exact alarms are available on this device / OS version.
| Parameter | Type | Description |
|---|---|---|
context | Context | Used for AlarmManager and notification permission / settings. |
Returns: ComRaidCapabilities(notificationsEnabled, exactAlarmsAvailable).
ComRaid.configure(
applicationContext,
ComRaidConfiguration(
appId = "cr_app_your_id",
smallIconResourceId = R.drawable.ic_notification,
),
)
val caps = ComRaid.capabilities(applicationContext)
// caps.notificationsEnabled, caps.exactAlarmsAvailableIdentity
requestPermission(activity: Activity, onResult: (granted: Boolean) -> Unit)
Requests POST_NOTIFICATIONS when needed (Android 13+), then registers a Subscription if
granted. Configure only stores settings; token fetch + register run on the SDK executor.
onResult is always delivered on the main thread after register completes when permission
is granted (true on success, false if register fails) so hosts never hang.
| Parameter | Type | Description |
|---|---|---|
activity | Activity | Host activity for the system permission dialog. |
onResult | (Boolean) -> Unit | Invoked on the main thread with whether permission was granted and register succeeded. |
Returns: Unit. Requires prior configure.
onRequestPermissionsResult(requestCode: Int, grantResults: IntArray)
Forward Activity.onRequestPermissionsResult for requestPermission. On grant, register
runs on the SDK executor; the permission callback runs on the main thread after register
completes.
| Parameter | Type | Description |
|---|---|---|
requestCode | Int | Must match the SDK’s permission request. |
grantResults | IntArray | System grant results. |
Returns: Unit.
register(onComplete: (Result<Unit>) -> Unit)
Fetches the FCM token and registers (or refreshes) a Subscription on the SDK executor.
Returns immediately; onComplete is delivered on the main thread. Call after notification
permission is granted, or use requestPermission. When a Subscription credential is already
persisted (encrypted SharedPreferences), it is sent as subscription_credential so a repeat
register keeps the same Subscription and Contact.
| Parameter | Type | Description |
|---|---|---|
onComplete | (Result<Unit>) -> Unit | Success or ComRaidException / other failure. |
Returns: Unit. Requires prior configure.
suspend register()
Coroutine variant of register. Suspends until registration completes; work still runs
on the SDK executor.
Returns: Unit. Throws ComRaidException.NotConfigured / ApiError.
registerBlocking()
Worker-thread-only blocking register. Throws IllegalStateException if called on the main
thread. Prefer the callback or suspend register APIs.
Returns: Unit. Throws ComRaidException.NotConfigured / ApiError / IllegalStateException.
onPushTokenRefresh()
Handles FCM token rotation. Prefer replace-token when a Subscription credential exists;
otherwise register. Prefer letting ComraidMessagingService call this; invoke manually
only if you own the messaging service.
Returns: Unit. Requires prior configure.
getToken(): String
Returns the Provider push token (FCM). Not a ComRaid Endpoint / Subscription id.
Returns: FCM registration token. Requires prior configure.
getInitialNotification(): RemoteMessageEvent?
Returns the notification tap that cold-started the app, if any. Cleared after the first read.
Returns: RemoteMessageEvent?.
consumeLaunchIntent(intent: Intent?, coldStart: Boolean = false): RemoteMessageEvent?
Reads cr_* extras from a system-tray / launcher launch intent, records opened, and
surfaces open listeners / initial notification.
| Parameter | Type | Description |
|---|---|---|
intent | Intent? | Host Activity launch intent. |
coldStart | Boolean | When true, stash for getInitialNotification. |
Returns: Parsed event, or null when no ComRaid payload is present.
presentNotification(event: RemoteMessageEvent) / presentNotification(data: Map<String, String>)
Posts a local tray item from title/body/actions (optional Data-only promotion). Body/action
taps auto-ACK opened (with actionId for actions). Data-only Notifications are never
auto-drawn on receive — call this when the app wants shade UI. Presentation fields travel
on the event (see Receive event fields); either overload rebuilds
the payload map and uses the same display path. Requires a non-blank title.
| Field | Applied on present? |
|---|---|
imageUrl | Yes — expanded picture / large icon |
subtitle | No — exposed on the event for in-app UI; Android trays never draw it |
sound | Android 7 and older only; on 8+ the Category channel decides (ADR 0012) |
badge | Yes — notification count |
threadId | Yes — notification tag (newer push in the same thread replaces the older) |
androidChannelId | Yes — posts on that channel when known; otherwise default after one Category sync |
priority | Android 7 and older only; on 8+ the Category channel importance decides |
Returns: Unit. Requires prior configure (or persisted SdkConfigStore).
ComRaidConfiguration.displayForegroundNotifications (default true) controls whether
non–data-only alerts are shown by the SDK in the foreground; set false to handle alerts
only via receive listeners.
login(externalUserId: String, jwt: String? = null)
Binds the current Subscription to a known Contact (external_user_id). Optional Identity
verification JWT from your backend. Persists the External user ID with the Subscription id
and credential so setAttributes works after an app restart.
| Parameter | Type | Description |
|---|---|---|
externalUserId | String | Non-blank External user ID. |
jwt | String? | Optional Identity verification JWT (jwt field). |
Returns: Unit. Throws NotConfigured, NotReady, or ApiError.
logout()
Makes the Subscription Inactive and clears its server credential. Clears the persisted
Subscription id, credential, and External user ID, then immediately registers a fresh
Subscription on a new Anonymous contact. Mobile routes refuse the old row with
401 unauthorized (missing/mismatched credential) or 409 subscription_inactive.
Returns: Unit.
optOut()
Opt the Subscription out of the push Channel (channel: push).
Returns: Unit. Requires a registered Subscription.
optIn()
Opt the Subscription back into the push Channel (channel: push).
Returns: Unit. Requires a registered Subscription.
ComRaid.requestPermission(activity) { granted -> /* … */ }
// or when permission is already granted:
ComRaid.register { result -> result.getOrThrow() }
// suspend { ComRaid.register() }
ComRaid.login("user_123")
ComRaid.login("user_123", jwt = jwtFromYourBackend)
ComRaid.logout()
ComRaid.optOut()
ComRaid.optIn()Properties and Attributes
Automatically collected Properties
| Field | Source |
|---|---|
app_version | Host app versionName |
sdk_version | ComRaid Android library version |
device.os / device.os_version / device.model | Android OS + Build.MODEL |
locale / language / country | Device locale / region |
timezone | IANA id from the device timezone |
Sent on register, token refresh, and each debounced foreground /session.
setDeviceProperties(properties: DeviceProperties)
Optional overrides for automatically collected Properties on the next register / token / session call. Null fields keep the auto-collected value.
| Parameter | Type | Description |
|---|---|---|
properties | DeviceProperties | Optional overrides (appVersion, sdkVersion, model, os, osVersion, locale, timezone, language, country, extras). |
Returns: Unit.
setAttributes(attributes: Map<String, Any?>)
Upsert Contact Attributes for the logged-in Contact
(PUT /mobile/subscriptions/{id}/attributes).
| Parameter | Type | Description |
|---|---|---|
attributes | Map<String, Any?> | Attribute map (e.g. plan → premium). Empty map is a successful empty update. A null value removes that Attribute. |
Returns: Unit. Throws NotReady if not logged in.
ComRaid.setDeviceProperties(
DeviceProperties(appVersion = "1.2.0", model = "Pixel 8"),
)
// overrides hitchhike on the next register / token / session
ComRaid.login("user_123")
ComRaid.setAttributes(mapOf("plan" to "premium"))Delivery ACKs
Remote messages enqueue durable delivered/opened ACKs (persisted SharedPreferences queue
with Retry-After / backoff). Flush works from the messaging service without a foreground
ComRaid singleton as long as configure has run at least once on the device. Flushes run
on the SDK's background thread, so taps, actions and the methods below are safe from the
main thread. Auth remains
the per-delivery attribution token — see Acknowledgements.
acknowledgeDelivered(deliveryId: String, attributionToken: String): Boolean
Enqueue a delivered ACK and flush it on the SDK's background thread (safe from any thread).
| Parameter | Type | Description |
|---|---|---|
deliveryId | String | Delivery id from the push payload. |
attributionToken | String | Attribution token from the push payload. |
Returns: false when either id is blank; otherwise true once the ACK is queued.
acknowledgeOpened(deliveryId: String, attributionToken: String, actionId: String? = null): Boolean
Enqueue an opened ACK (optional action button id) and flush it on the SDK's background thread.
| Parameter | Type | Description |
|---|---|---|
deliveryId | String | Delivery id from the push payload. |
attributionToken | String | Attribution token from the push payload. |
actionId | String? | Optional action button id. |
Returns: false when either id is blank; otherwise true once the ACK is queued.
flushAcks()
Flush any durable ACK backlog on the SDK's background thread (safe to call from
Application.onCreate).
Returns: Unit. No-op if not configured.
ComRaid.acknowledgeDelivered(deliveryId, attributionToken)
ComRaid.acknowledgeOpened(deliveryId, attributionToken, actionId = "accept")
ComRaid.flushAcks()Local schedule and timers
Exact alarms are opt-in: the host must declare the applicable exact-alarm permission,
satisfy store policy, and obtain system access. ComRaid defaults to inexact alarms and never
adds an exact-alarm permission to the library manifest. Boot restoration needs
ComRaid.configure from Application.onCreate before the boot receiver can restore
schedules.
schedule(request: ComRaidScheduleRequest): ComRaidScheduleResult
Schedule a local notification at an absolute trigger time.
| Parameter | Type | Description |
|---|---|---|
request | ComRaidScheduleRequest | notification, triggerAtMillis (must be in the future), precision, fallbackPolicy. |
Returns: ComRaidScheduleResult (id, requested/applied precision, trigger, optional
fallbackReason). Throws NotConfigured, InvalidSchedule, or ExactAlarmUnavailable.
startTimer(notification: ComRaidNotification, durationMillis: Long, precision: SchedulePrecision = INEXACT, fallbackPolicy: FallbackPolicy = FAIL): ComRaidScheduleResult
Starts a countdown timer that fires a Local notification when complete. Persists timer
state so pauseTimer / resumeTimer / timers and reboot restore match iOS semantics.
| Parameter | Type | Description |
|---|---|---|
notification | ComRaidNotification | Local tray content (id, title, body, …). |
durationMillis | Long | Must be positive. |
precision | SchedulePrecision | INEXACT (default) or EXACT. |
fallbackPolicy | FallbackPolicy | FAIL (default) or USE_INEXACT when exact is unavailable. |
Returns: ComRaidScheduleResult. Throws InvalidSchedule if duration ≤ 0.
pauseTimer(id: String): ComRaidTimer
Pauses a running timer, clears its pending system alarm, and stores remaining duration.
| Parameter | Type | Description |
|---|---|---|
id | String | Timer / notification id. |
Returns: ComRaidTimer (PAUSED). Throws TimerNotFound / TimerNotPaused.
resumeTimer(id: String): ComRaidTimer
Resumes a paused timer from remaining duration (re-arms the alarm).
| Parameter | Type | Description |
|---|---|---|
id | String | Timer / notification id. |
Returns: ComRaidTimer (RUNNING). Throws TimerNotFound / TimerNotPaused.
cancelTimer(id: String)
Cancels a timer and removes its pending schedule.
| Parameter | Type | Description |
|---|---|---|
id | String | Timer / notification id. |
Returns: Unit.
timers(): List<ComRaidTimer>
Lists persisted timers (RUNNING, PAUSED, CANCELLED, COMPLETED).
Returns: List<ComRaidTimer>. Throws NotConfigured if timer store is unavailable.
cancel(id: String)
Cancel a pending local schedule by notification id and remove it from the durable store.
If a matching timer exists, marks it CANCELLED.
| Parameter | Type | Description |
|---|---|---|
id | String | ComRaidNotification.id / schedule id. |
Returns: Unit.
pendingSchedules(): List<ComRaidScheduleRequest>
List durable pending local schedules.
Returns: List<ComRaidScheduleRequest>. Throws NotConfigured if schedule store is
unavailable.
val result = ComRaid.startTimer(
notification = ComRaidNotification(
id = "focus-1",
title = "Focus complete",
body = "Your timer has finished.",
),
durationMillis = 25 * 60 * 1000L,
)
ComRaid.pauseTimer("focus-1")
ComRaid.resumeTimer("focus-1")
val allTimers = ComRaid.timers()
ComRaid.cancelTimer("focus-1")
ComRaid.schedule(
ComRaidScheduleRequest(
notification = ComRaidNotification(id = "promo-1", title = "Reminder", body = "Tonight"),
triggerAtMillis = System.currentTimeMillis() + 3_600_000L,
),
)
ComRaid.cancel("promo-1")
val pending = ComRaid.pendingSchedules()Receive event fields
RemoteMessageEvent (from receive listeners, getInitialNotification, and
consumeLaunchIntent) carries presentation fields outside sender data. Optional fields
are absent (null) when not set — never empty strings. priority is always "high" or
"normal" on received events (default "high" per ADR 0012).
| Field | Type | Source | Platform notes |
|---|---|---|---|
imageUrl | String? | cr_image_url | Downloaded when the SDK draws the tray item (≤ 5 MB, 10 s). |
subtitle | String? | cr_subtitle | Exposed for parity / in-app UI; never drawn on Android trays. |
sound | String? | cr_sound | Raw name as sent (chime.wav, default). Used on Android 7 and older only; on 8+ the Category channel decides (ADR 0012). |
badge | Int? (≥ 0) | cr_badge | Notification count when the SDK draws. |
threadId | String? | cr_thread_id | Notification tag when the SDK draws. |
androidChannelId | String? | cr_android_channel_id | Category channel for SDK-drawn items; unknown ids fall back to the default after one sync. |
priority | String ("high" | "normal") | cr_priority (else default "high") | Always present on received events. Tray importance on Android 8+ still follows the channel. |
data stays sender keys only — reserved cr_* keys (including cr_subtitle) are stripped.
presentNotification(event) uses these fields; see the method above.
Deep links and rich fields
API content.push.deep_link arrives in FCM data as cr_deep_link. On notification open,
the SDK brings your launch activity forward and surfaces deepLink on the opened listener /
getInitialNotification. The SDK does not fire ACTION_VIEW or route for you — navigate
in the host (same model as iOS).
- When FCM includes a system
notificationblock, Android applies sound / tag / notification count from the provider; readRemoteMessageEvent.deepLink(orcr_deep_linkon the payload) on open for in-app navigation. - When the SDK builds the tray notification (data-first payloads or action buttons), the
trampoline still opens your app and delivers the same
deepLinkon the opened event.
When the SDK draws the notification (action buttons, foreground display, or
presentNotification) it also applies:
| Field | Android behaviour |
|---|---|
image_url / imageUrl | Downloaded (≤ 5 MB, 10 s timeout) and shown as an expanded picture and large icon. |
body | Expandable long text when there is no image. |
actions[].icon | Name of a drawable in your app (res/drawable); unknown names give a text-only button. |
thread_id / threadId | Notification tag: a newer push in the same thread replaces the older one. |
badge | Notification count. |
sound | Name of a sound in your app's res/raw (chime or chime.wav). Android 7 and older only. |
priority | Android 7 and older only; on 8+ the category's importance decides. |
ComRaidConfiguration.accentColor | Tint for the small icon and action buttons. |
subtitle is never drawn on Android (iOS-only display).
Sounds on Android 8+
From Android 8 the notification channel decides the sound, not the individual push, whoever
draws the notification. Set the sound on the category (android_sound, a res/raw
name) and send the push in that category. Android fixes a channel's sound when the channel
is first created on the device, so changing a category's sound later needs a new category.
If a push names a category channel the device hasn't created yet, the SDK syncs categories once more and otherwise posts on the default channel, so the notification is never dropped.
Models
| Type | Role |
|---|---|
ComRaidConfiguration | App ID, API base URL, default channel, small icon, accent colour. |
RemoteMessageEvent / RemoteMessageAction | Receive / open event (presentation fields in Receive event fields); actions are id, text, optional icon. |
ComRaidNotification | Local schedule content (id, title, body, optional channelId / data). |
ComRaidScheduleRequest / ComRaidScheduleResult | Local schedule input / outcome. |
ComRaidTimer / TimerState | Local countdown timer state (RUNNING / PAUSED / …). |
SchedulePrecision / FallbackPolicy | Exact vs inexact; fail vs fall back. |
ComRaidCapabilities | notificationsEnabled, exactAlarmsAvailable. |
DeviceProperties | Overrides for auto-collected Properties on register / token / session. |
Errors
ComRaidException (sealed, extends IllegalStateException):
| Type | When |
|---|---|
NotConfigured | Public API called before configure (or schedule/timer store unavailable). |
NotReady | No Subscription credential, or Attributes without Login. |
InvalidSchedule | Bad trigger / duration. |
ExactAlarmUnavailable | Exact precision requested with FallbackPolicy.FAIL and no exact-alarm access. |
TimerNotFound | Unknown timer id. |
TimerNotPaused | Pause/resume state mismatch. |
ApiError | Mobile HTTP / FCM token failure. |
Mobile HTTP error codes (inside ApiError when the API returns them):
| Code | HTTP | When |
|---|---|---|
unauthorized | 401 | Missing or mismatched Subscription credential, or credential-less Endpoint. |
subscription_inactive | 409 | Login, opt-out/in, token, Attributes, or session on an Inactive Subscription. |
Notes
- Wire field is
external_user_id(never the legacy OneSignal CSV header name). - Subscription id, credential, and External user ID persist in encrypted SharedPreferences
across launches;
register()sends the stored credential on refresh. - After Logout the SDK clears that store and registers a fresh Subscription; do not reuse the old id/credential.
- Package namespace is
com.comraid.android; nevercom.comraide. - Guides: Acknowledgements, Notifications, API Reference. Sister SDKs: iOS, React Native.
Node SDK
Send Notifications from your server with @comraid/node.
iOS SDK
Integrate ComRaid push on iOS with the Swift Package ComRaid — Subscription register, Login, Logout, Contact opt-in/out, remote display helpers, Notification Service Extension images, durable delivery ACKs, and local schedules/timers.