Push notifications
Android SDK v1.4.0 — Push notifications
The SDK has no Firebase dependency of its own — it never registers for
FCM, never receives a push, and doesn't render a notification for you. What
it does provide is the two hooks that connect your FCM integration to
Optima: registering the device's token so campaigns can target it, and
recording that a delivered push was opened. You still write your own
FirebaseMessagingService.
FCM setup recipe
Add Firebase Cloud Messaging to your app the normal way
(com.google.firebase:firebase-messaging, google-services.json, the
Google Services Gradle plugin) — none of that is part of this SDK. Then wire
the two callbacks:
import android.app.PendingIntent
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.optima.sdk.Optima
import com.optima.sdk.push.OptimaPush
class MyFirebaseService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
Optima.instance.push.setToken(token)
}
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
val push = Optima.instance.push.parse(message.data) ?: return // not an Optima-sent push
// Resolve title/body here, while `message` is in scope — a notification-block message
// carries them under message.notification; a data-only message carries them as plain
// data keys instead.
val title = message.notification?.title ?: message.data["title"]
val body = message.notification?.body ?: message.data["body"]
showNotification(push, title, body, message.data)
}
/** [data] is the RAW payload (message.data), not push.data — push.data has optima_open/
* deep_link/buttons/image_url filtered OUT, and those reserved keys are exactly what
* push.trackOpen(intent.extras) needs to find on the launched Activity's intent later. */
private fun showNotification(push: OptimaPush, title: String?, body: String?, data: Map<String, String>) {
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
data.forEach { (k, v) -> putExtra(k, v) } // carries optima_open (plus deep_link/buttons/image_url/your own keys) onto the launch intent
}
val requestCode = push.openToken?.hashCode() ?: (title ?: "optima").hashCode()
val pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
push.buttons.forEachIndexed { i, button ->
val actionIntent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
data.forEach { (k, v) -> putExtra(k, v) } // same optima_open carried on every action's own intent
button.deepLink?.let { putExtra("deep_link", it) } // a button's own deep link overrides the notification-level one
}
val actionPendingIntent = PendingIntent.getActivity(this, requestCode + i + 1, actionIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
builder.addAction(0, button.label, actionPendingIntent)
}
NotificationManagerCompat.from(this).notify(requestCode, builder.build())
}
companion object { const val CHANNEL_ID = "optima_campaigns" }
}MainActivity and R.drawable.ic_notification/the CHANNEL_ID notification
channel are your own app's — create the channel once (e.g. in
Application.onCreate) and use an icon from your own resources; neither is
part of this SDK. push.openToken is nullable (OptimaPush.openToken: String?) because a push with open tracking off has none — the request-code
fallback above avoids calling hashCode() on a null.
push.setToken(token) stores the token (_optima_push_token) and — unless
Edge has already acknowledged this exact token for this device
(_optima_push_synced) — calls identify({push_token_fcm: token}) to attach
it to the device's current profile. Call it from onNewToken
every time; it's a no-op once Edge has acknowledged that token for this
device, and a registration that failed (offline on first launch, say) is
retried on the next launch and on every foreground, so there's no
harm in calling it unconditionally on every app start too (e.g. by fetching
the current token via FirebaseMessaging.getInstance().token in
Application.onCreate and feeding it through, in case onNewToken was
missed while the app was killed).
Reading the payload with push.parse
push.parse(extras) (there's a Map<String, String> overload and a
Bundle overload — pass message.data directly to either, since
RemoteMessage.data is already a Map<String, String>) reads the reserved
data keys the deliverer sends — deep_link, buttons (a JSON array,
already parsed into List<PushButton>), optima_open — and returns
OptimaPush(deepLink, buttons, data, openToken), where data is every
other key (your own custom payload data, with the reserved keys filtered
out). It returns null if none of the reserved keys are present at all — a
signal that this message wasn't built by Optima's delivery pipeline, so you
can fall through to whatever else handles your other push sources.
iOS/Android note that also applies here: buttons on Android come from
whatever NotificationCompat.Actions you add yourself (as in the recipe
above) — there's no OS-level "notification category" registration step like
APNs uses; push.parse's buttons list is just data for you to turn into
actions, not something the OS renders automatically.
push.trackOpen
Call it from the launched Activity, in both onCreate (a cold start from a
notification tap) and onNewIntent (the app was already running):
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
intent?.extras?.let { Optima.instance.push.trackOpen(it) }
setContent { /* ... */ }
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
intent.extras?.let { Optima.instance.push.trackOpen(it) }
}
}The data keys ride the launch Intent's extras because that's exactly what
the recipe above put there when it built the notification's (and each
button's) PendingIntent. trackOpen looks for optima_open; if present
and non-blank, it fires GET /edge/v1/o/{token} fire-and-forget (a 5-attempt
backoff ladder, failures logged at debug only — a missed open record never
surfaces as an app-visible error) and returns true. If optima_open is
absent, it does nothing and returns false — safe to call unconditionally
on every launch, including a normal (non-push) app open, since a launch
Intent with no such extra is simply ignored.
What the backend needs
Three prerequisites, all covered in the operator-facing sections of
FEATURES.md/TASK.md in the main optima repo:
EMAIL_TRACK_KEYmust be configured — the same key the email open pixel uses. Push opens are sealed with the identicalinternal/emailtrackmechanism, just taggedchannel: "push"instead of the email pixel's implicit channel.- Open tracking must be turned on for the push template (or the instance-
wide
email_open_trackingdefault, if the template doesn't override it) — the same switch email templates use, not a separate mobile-specific one. If it's off, the send simply never mints anoptima_openkey,push.parsereturnsopenToken = null, andtrackOpencorrectly does nothing — there is no error state here, just "nothing to track." push_token_fcmmust be an allowlisted identifier in the tenant'sidentify_allowed_keys— otherwisepush.setToken'sidentify(...)call succeeds but the server drops the key (visible in theIdentifyevent'sdroppedlist, and, more importantly, in a campaign never actually reaching the device because the token was never attached).
optima_open is a reserved data key — pushReservedDataKeys in the backend
rejects any attempt by a template author to set it themselves, so it's
always the delivery pipeline's own minted token, never something a
campaign's custom data payload could spoof or collide with.
reset() and the push token
reset() deliberately preserves _optima_push_token and, as one of its
final steps, re-sends it via identify({push_token_fcm: token}) under the
new device id — because the physical device (and its FCM registration)
hasn't changed, only the person using the app has, and pushes should keep
reaching this device under whatever profile it resolves to next.
If the outgoing user should not keep receiving pushes meant for this
device once a new person logs in — the common case for a genuinely
shared/kiosk device, less so for "my personal phone, I logged out of one
account and into another" — call push.setToken(null) before calling
reset(). setToken(null) forgets the token locally without notifying the
server, so reset()'s re-attach step finds nothing to re-send:
fun logout() {
Optima.instance.push.setToken(null)
Optima.instance.reset()
// Once a fresh token arrives via onNewToken (FCM issues a new one on request,
// or on the next app start), call setToken(token) again to re-attach it.
}