ComRaidComRaid Docs

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.

ParameterTypeDescription
contextContextAny context; the SDK keeps applicationContext.
configurationComRaidConfigurationappId (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.

ParameterTypeDescription
contextContextUsed 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.exactAlarmsAvailable

Identity

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.

ParameterTypeDescription
activityActivityHost activity for the system permission dialog.
onResult(Boolean) -> UnitInvoked 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.

ParameterTypeDescription
requestCodeIntMust match the SDK’s permission request.
grantResultsIntArraySystem 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.

ParameterTypeDescription
onComplete(Result<Unit>) -> UnitSuccess 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.

ParameterTypeDescription
intentIntent?Host Activity launch intent.
coldStartBooleanWhen 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.

FieldApplied on present?
imageUrlYes — expanded picture / large icon
subtitleNo — exposed on the event for in-app UI; Android trays never draw it
soundAndroid 7 and older only; on 8+ the Category channel decides (ADR 0012)
badgeYes — notification count
threadIdYes — notification tag (newer push in the same thread replaces the older)
androidChannelIdYes — posts on that channel when known; otherwise default after one Category sync
priorityAndroid 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.

ParameterTypeDescription
externalUserIdStringNon-blank External user ID.
jwtString?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

FieldSource
app_versionHost app versionName
sdk_versionComRaid Android library version
device.os / device.os_version / device.modelAndroid OS + Build.MODEL
locale / language / countryDevice locale / region
timezoneIANA 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.

ParameterTypeDescription
propertiesDevicePropertiesOptional 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).

ParameterTypeDescription
attributesMap<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).

ParameterTypeDescription
deliveryIdStringDelivery id from the push payload.
attributionTokenStringAttribution 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.

ParameterTypeDescription
deliveryIdStringDelivery id from the push payload.
attributionTokenStringAttribution token from the push payload.
actionIdString?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.

ParameterTypeDescription
requestComRaidScheduleRequestnotification, 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.

ParameterTypeDescription
notificationComRaidNotificationLocal tray content (id, title, body, …).
durationMillisLongMust be positive.
precisionSchedulePrecisionINEXACT (default) or EXACT.
fallbackPolicyFallbackPolicyFAIL (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.

ParameterTypeDescription
idStringTimer / notification id.

Returns: ComRaidTimer (PAUSED). Throws TimerNotFound / TimerNotPaused.

resumeTimer(id: String): ComRaidTimer

Resumes a paused timer from remaining duration (re-arms the alarm).

ParameterTypeDescription
idStringTimer / notification id.

Returns: ComRaidTimer (RUNNING). Throws TimerNotFound / TimerNotPaused.

cancelTimer(id: String)

Cancels a timer and removes its pending schedule.

ParameterTypeDescription
idStringTimer / 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.

ParameterTypeDescription
idStringComRaidNotification.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).

FieldTypeSourcePlatform notes
imageUrlString?cr_image_urlDownloaded when the SDK draws the tray item (≤ 5 MB, 10 s).
subtitleString?cr_subtitleExposed for parity / in-app UI; never drawn on Android trays.
soundString?cr_soundRaw name as sent (chime.wav, default). Used on Android 7 and older only; on 8+ the Category channel decides (ADR 0012).
badgeInt? (≥ 0)cr_badgeNotification count when the SDK draws.
threadIdString?cr_thread_idNotification tag when the SDK draws.
androidChannelIdString?cr_android_channel_idCategory channel for SDK-drawn items; unknown ids fall back to the default after one sync.
priorityString ("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.

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 notification block, Android applies sound / tag / notification count from the provider; read RemoteMessageEvent.deepLink (or cr_deep_link on 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 deepLink on the opened event.

When the SDK draws the notification (action buttons, foreground display, or presentNotification) it also applies:

FieldAndroid behaviour
image_url / imageUrlDownloaded (≤ 5 MB, 10 s timeout) and shown as an expanded picture and large icon.
bodyExpandable long text when there is no image.
actions[].iconName of a drawable in your app (res/drawable); unknown names give a text-only button.
thread_id / threadIdNotification tag: a newer push in the same thread replaces the older one.
badgeNotification count.
soundName of a sound in your app's res/raw (chime or chime.wav). Android 7 and older only.
priorityAndroid 7 and older only; on 8+ the category's importance decides.
ComRaidConfiguration.accentColorTint 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

TypeRole
ComRaidConfigurationApp ID, API base URL, default channel, small icon, accent colour.
RemoteMessageEvent / RemoteMessageActionReceive / open event (presentation fields in Receive event fields); actions are id, text, optional icon.
ComRaidNotificationLocal schedule content (id, title, body, optional channelId / data).
ComRaidScheduleRequest / ComRaidScheduleResultLocal schedule input / outcome.
ComRaidTimer / TimerStateLocal countdown timer state (RUNNING / PAUSED / …).
SchedulePrecision / FallbackPolicyExact vs inexact; fail vs fall back.
ComRaidCapabilitiesnotificationsEnabled, exactAlarmsAvailable.
DevicePropertiesOverrides for auto-collected Properties on register / token / session.

Errors

ComRaidException (sealed, extends IllegalStateException):

TypeWhen
NotConfiguredPublic API called before configure (or schedule/timer store unavailable).
NotReadyNo Subscription credential, or Attributes without Login.
InvalidScheduleBad trigger / duration.
ExactAlarmUnavailableExact precision requested with FallbackPolicy.FAIL and no exact-alarm access.
TimerNotFoundUnknown timer id.
TimerNotPausedPause/resume state mismatch.
ApiErrorMobile HTTP / FCM token failure.

Mobile HTTP error codes (inside ApiError when the API returns them):

CodeHTTPWhen
unauthorized401Missing or mismatched Subscription credential, or credential-less Endpoint.
subscription_inactive409Login, 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; never com.comraide.
  • Guides: Acknowledgements, Notifications, API Reference. Sister SDKs: iOS, React Native.

On this page

InstallGetting startedMethod referenceConfigureconfigure(context: Context, configuration: ComRaidConfiguration)capabilities(context: Context): ComRaidCapabilitiesIdentityrequestPermission(activity: Activity, onResult: (granted: Boolean) -> Unit)onRequestPermissionsResult(requestCode: Int, grantResults: IntArray)register(onComplete: (Result<Unit>) -> Unit)suspend register()registerBlocking()onPushTokenRefresh()getToken(): StringgetInitialNotification(): RemoteMessageEvent?consumeLaunchIntent(intent: Intent?, coldStart: Boolean = false): RemoteMessageEvent?presentNotification(event: RemoteMessageEvent) / presentNotification(data: Map<String, String>)login(externalUserId: String, jwt: String? = null)logout()optOut()optIn()Properties and AttributesAutomatically collected PropertiessetDeviceProperties(properties: DeviceProperties)setAttributes(attributes: Map<String, Any?>)Delivery ACKsacknowledgeDelivered(deliveryId: String, attributionToken: String): BooleanacknowledgeOpened(deliveryId: String, attributionToken: String, actionId: String? = null): BooleanflushAcks()Local schedule and timersschedule(request: ComRaidScheduleRequest): ComRaidScheduleResultstartTimer(notification: ComRaidNotification, durationMillis: Long, precision: SchedulePrecision = INEXACT, fallbackPolicy: FallbackPolicy = FAIL): ComRaidScheduleResultpauseTimer(id: String): ComRaidTimerresumeTimer(id: String): ComRaidTimercancelTimer(id: String)timers(): List<ComRaidTimer>cancel(id: String)pendingSchedules(): List<ComRaidScheduleRequest>Receive event fieldsDeep links and rich fieldsModelsErrorsNotes