RelayGrid logoRelayGrid

Android SDK Documentation

Turn your users' Android devices into push targets, and report when each push arrives and when it is opened.

No RelayGrid key in your app

Your app never holds an sk_ key. It asks your own backend for a short-lived channel token, and that token only lets the device register itself for the one user your backend vouched for. Your server keeps sending exactly as it does today, with notify() from the Node.js library or the Ruby gem; when the template has a Firebase push channel, the user's registered devices get the push.

Android and iOS push is in early access. Your account needs mobile push enabled, so contact support if the push channel's Platform menu only offers RelayGrid.

Requirements

  • Android 7.0 (API 24) or newer. The SDK is compiled against API 35.
  • Kotlin coroutines: identify() and logout() are suspend functions.
  • Firebase Cloud Messaging in your app: a Firebase project with your app registered, its google-services.json in your app module, and the com.google.gms.google-services Gradle plugin.
  • A RelayGrid push channel with the Firebase Cloud Messaging (Android) platform and a service-account key from the same Firebase project. An account admin sets it up with the Firebase setup guide, which also covers downloading google-services.json.

Installation

Kotlin
// app/build.gradle.kts
dependencies {
    implementation("dev.relaygrid:relaygrid-android:0.1.0")
}

The artifact is not on a public Maven repository yet. Until it is, build it from the SDK repository and add mavenLocal() to your repositories:

Shell
./gradlew :relaygrid:publishReleasePublicationToMavenLocal

The SDK brings firebase-messaging, androidx.core, OkHttp and kotlinx-coroutines with it. It adds the INTERNET, ACCESS_NETWORK_STATE and POST_NOTIFICATIONS permissions to your manifest, plus a private, non-exported activity that handles notification taps.

1. Give your backend a channel-token endpoint

This is the one piece of server work. Add an endpoint to your own API that asks RelayGrid for a channel token for the user signed in to your app, with your secret key, and returns it:

HTTP
POST https://relaygrid.dev/api/v1/channel_tokens
Authorization: Bearer sk_...
Content-Type: application/json

{ "external_user_id": "user-123" }
JSON
{ "token": "eyJf...", "expires_in": 3600 }

external_user_id is your own id for the user, the same one you pass to notify(). RelayGrid creates the recipient if it doesn't exist yet, so this works on a user's very first login. With the Node.js library:

TypeScript
app.post("/me/relaygrid-token", requireLogin, async (req, res) => {
  const { token, expiresIn } = await relaygrid.channelTokens.create({ userId: req.user.id });
  res.json({ token, expires_in: expiresIn });
});

Use a restricted key that holds only messages:send and recipients:token. Never let the client choose external_user_id: take it from your own session, or any signed-in user could register their phone for someone else. Tokens last one hour. The SDK caches the token, asks your endpoint again shortly before it expires, and asks again if RelayGrid ever answers 401.

2. Configure

Call configure once, from Application.onCreate:

Kotlin
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        RelayGrid.configure(this, RelayGridConfig(
            channelTokenProvider = {
                val response = myApi.relayGridToken()
                ChannelToken(response.token, response.expiresIn)
            },
        ))
    }
}

configure does no network work on your thread and never asks for the notification permission. In the background it sends tracking events that were queued while offline and retries a device registration that didn't go through last time. Bad settings throw ConfigurationError from the RelayGridConfig constructor, so a misconfigured build fails at startup.

OptionDefaultPurpose
channelTokenProvider—suspend () -> ChannelToken that calls your endpoint from step 1. Required.
baseUrlhttps://relaygrid.devAPI origin, for self-hosted RelayGrid. The SDK appends /api/v1.
timeoutMillis30000Milliseconds to wait for a whole request.
maxQueuedEvents500Tracking events kept on disk while offline. The oldest are evicted first.
retryBaseDelayMillis1000First retry step for queued events, doubled per failure.
retryMaxDelayMillis300000Ceiling for that backoff.
loggerLogcat, tag RelayGridA RelayGridLogger to route diagnostics elsewhere. Tokens are never logged.
notificationChannelIdrelaygridAndroid 8+ notification channel pushes are posted on. Created with high importance if it does not exist; an existing channel with that id is used as is.
notificationSmallIcon0Drawable for the status bar icon. 0 falls back to the manifest meta-data in step 5.

3. Identify after login

Kotlin
lifecycleScope.launch {
    try {
        RelayGrid.identify()
    } catch (e: RelayGridError) {
        // registration stays pending and is retried on the next launch
        // or when the network comes back
    }
}

identify() fetches a fresh channel token from your provider, gets the device's FCM token and registers the device. Call it after every login, including when a different user signs in on the same phone: the device moves to whoever registered it last.

4. Ask for the notification permission

On Android 13 and newer, notifications need the POST_NOTIFICATIONS runtime permission. The SDK never requests it, so ask at a moment that makes sense to your user, for example after they turn on order updates:

Kotlin
if (Build.VERSION.SDK_INT >= 33) {
    requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}

A device registers fine without the permission; pushes simply aren't shown until the user grants it.

5. Declare the messaging service

RelayGrid sends data-only FCM messages, which Android never draws by itself. Declare the SDK's service in your app's AndroidManifest.xml. It reports the delivery, shows the notification and keeps the FCM token current:

XML
<service
    android:name="dev.relaygrid.RelayGridMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

For every push it:

  • reports delivered, queued on disk first so it survives the process dying;
  • creates the notification channel on Android 8+, named by the string resource relaygrid_notification_channel_name, which you can override or translate in your own strings.xml;
  • posts the notification with the push's title and body, a tap target and up to three action buttons. A second push for the same delivery replaces the first instead of stacking.

Without the permission from step 4, or with notifications turned off for the app, the delivery is still reported and the notification is skipped with a log line.

Status bar icon

The icon must be a monochrome drawable. Set notificationSmallIcon in the config, or add this to the manifest:

XML
<meta-data
    android:name="dev.relaygrid.notification_icon"
    android:resource="@drawable/ic_notification" />

Without either, the SDK uses Firebase's default_notification_icon meta-data if you have it, and your app icon as a last resort.

Already have a FirebaseMessagingService?

An app gets FCM messages in exactly one service, so don't declare RelayGridMessagingService next to yours. Hand RelayGrid's messages to the SDK from your own instead:

Kotlin
class MyMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(message: RemoteMessage) {
        if (RelayGridMessagingService.handleMessage(this, message)) return
        handleMyOwnMessage(message)
    }

    override fun onNewToken(token: String) {
        RelayGrid.onNewToken(token)
        sendTokenToMyOwnBackend(token)
    }
}

handleMessage returns false for anything that isn't a RelayGrid push and leaves it alone. When a user is identified, RelayGrid.onNewToken registers the new token and unregisters the old one.

6. Log out

Kotlin
RelayGrid.logout()

Call it before you end your own session, so your token endpoint can still vouch for the user. It unregisters the device, then forgets the identity, the cached channel token and any queued tracking events. Local state is cleared even when the request fails, in which case logout() throws.

Taps, deep links and action buttons

A tap goes to a small activity inside the SDK, which reports opened, dismisses the notification and routes the tap:

  • Notification body: opens the push's deep link, or your launcher activity when there is none.
  • Action button: calls your actionHandler with the button's id. If there is no handler or it returns false, opens the button's deep link, or your launcher activity when there is none.

Your launcher activity starts the way the launcher icon starts it: a running app comes back on the screen the user left, and a cold start lands on its home screen. A link is opened by your deepLinkHandler if it returns true, then by an activity of your own app whose intent filter matches it, then by anything else on the device that handles it, such as the browser. If nothing can open it, the app opens instead. Links with javascript:, data:, file:, vbscript:, content: or intent: schemes are never opened.

The usual setup is an intent filter on the activity that should open:

XML
<activity android:name=".OrderActivity" android:exported="true" android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="myapp" android:host="orders" />
    </intent-filter>
</activity>

The activity is started as a new task, so with singleTop an open screen receives the link in onNewIntent. To route links or buttons in code, set handlers once, next to configure. They run on the main thread, and a handler that throws is logged and treated as false:

Kotlin
RelayGrid.deepLinkHandler = RelayGridDeepLinkHandler { context, link ->
    if (link.host != "orders") return@RelayGridDeepLinkHandler false
    context.startActivity(OrderActivity.intent(context, link.lastPathSegment))
    true
}

RelayGrid.actionHandler = RelayGridActionHandler { context, actionId, push ->
    when (actionId) {
        "snooze" -> { Reminders.snooze(context, push.deliveryId); true }
        else -> false
    }
}

Tracking deliveries and opens yourself

With RelayGridMessagingService you don't call these. If you draw notifications yourself, parse a push with RelayGridPush and report it:

Kotlin
override fun onMessageReceived(message: RemoteMessage) {
    val push = RelayGridPush.fromData(message.data) ?: return
    push.trackingToken?.let(RelayGrid::trackDelivered)
    showMyOwnNotification(push)
}

// when the user taps it
RelayGrid.trackOpen(trackingToken)

Both are fire-and-forget. Events go to a small queue on disk first, so an open tapped without signal is reported when the phone is back online. Failed sends back off exponentially; a rejected tracking token is dropped, never retried. RelayGridPush exposes title, body, deliveryId, trackingToken, deepLink and up to three actionButtons, and fromData returns null for a message that isn't a RelayGrid push.

Errors

Everything the SDK throws descends from RelayGridError, like the Node.js library. HTTP errors are ApiError subclasses carrying status, body and errorMessage. A 401 on a device call is retried once with a fresh token from your provider; only a second 401 reaches you.

ErrorWhen
ConfigurationErrorBad config, Firebase not set up, or configure() not called.
ConnectionErrorNo HTTP response. TimeoutError is a subclass.
ChannelTokenProviderErrorYour provider threw or returned a blank token.
AuthenticationError401 or 403.
LimitExceededError402.
NotFoundError404, including when mobile push is not enabled on the account.
ValidationError422.
ServerError5xx.

Sample app

The SDK repository has a sample/ app that configures the SDK, identifies a user, shows the registration status and opens deep links. Its Show a test notification button tries the rendering and tap routing on a device without Firebase or a server. The repository README explains how to point it at RelayGrid and receive real pushes.