Skip to content

Push

Your app keeps its own push service, Firebase Cloud Messaging. PurrCRM sends pushes through your Firebase project once your team has added its key in the Firebase key card on Settings › your app › Delivery › Push (A push campaign). The SDK reads the pushes you hand it; it shows no notification itself.

What you draw: the permission prompt, the notification for a push that arrives while your app is open, your bell, and the inbox of notices.

1. Add Firebase, and ask for the permission

Section titled “1. Add Firebase, and ask for the permission”

Add Firebase to your app as Firebase’s own guide says (the google-services plugin and google-services.json), and the messaging library:

app/build.gradle.kts
dependencies {
implementation(platform("com.google.firebase:firebase-bom:<version>"))
implementation("com.google.firebase:firebase-messaging")
}

On Android 13 (API 33) and later, notifications need the user’s permission. Declare it:

app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

and ask for it at a moment that makes sense to the user, then tell the SDK the answer, which it records as an event:

HomeActivity.kt
private val askNotifications =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
crm.permissionChanged("push", granted)
}
private fun offerNotifications() {
if (Build.VERSION.SDK_INT >= 33) {
askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS)
} else {
crm.permissionChanged("push", NotificationManagerCompat.from(this).areNotificationsEnabled())
}
}

Below Android 13 notifications are on unless the user turned them off. Without the permission, the pushes still reach your app, but Android shows none of them.

On Android 8 (API 26) and later every notification belongs to a channel the app created, which the user can turn off on its own. PurrCRM names one in every push: the Android channel on Settings › your app › Messaging rules › Push limits › Advanced. Left empty it is messages, which the SDK has as CrmConfig.DEFAULT_PUSH_CHANNEL. The SDK creates no channel: create it as your app starts, before the first push can arrive, or Android files your pushes under a channel of Firebase’s own.

NorthwindApp.kt
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= 26) {
val channel = NotificationChannel(
CrmConfig.DEFAULT_PUSH_CHANNEL, // the Android channel in your app's push settings
"Messages", // what the user sees in the app's notification settings
NotificationManager.IMPORTANCE_HIGH,
).apply { description = "Replies from our team, and messages about your account." }
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
// ... then make and start the Crm.
}

Creating a channel that exists already changes nothing, so do it on every start. If your team names another channel, ship a build that creates it first, and keep creating the old one while builds that know only it are installed. List the channels you create in CrmConfig.pushChannels whenever yours is not messages: the setup check then looks for those, and no longer for messages.

Hand the SDK Firebase’s token on every start, and whenever Firebase makes a new one. registerPushToken is a suspend call; it answers whether PurrCRM has the token.

NorthwindApp.kt
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
// In onCreate, after crm.start():
FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
appScope.launch { crm.registerPushToken(token) }
}

The SDK keeps the token, and registers it for each user who signs in, so a phone that changes hands gets only the new user’s pushes. A token handed in while nobody is signed in is registered at the next sign-in. Before your own sign-out, while the user’s token still works, call crm.forgetPushToken() (Sign users in).

PurrCRM‘s pushes are Firebase notification messages with data: while your app is in the background, Android shows them itself, in the channel the push names. While your app is open, Firebase hands them to your service instead, and showing one is up to you. Hand every push to the SDK first:

NorthwindPushes.kt
class NorthwindPushes : FirebaseMessagingService() {
private val app get() = application as NorthwindApp
override fun onNewToken(token: String) {
app.appScope.launch { app.crm.registerPushToken(token) }
}
override fun onMessageReceived(message: RemoteMessage) {
val result = app.crm.handlePushArrival(message.data)
if (result.isCrm && !result.replyOnScreen && !result.silent) {
showNotification(message) // see below
}
// Not PurrCRM's (result.isCrm is false): yours to handle, as before.
}
}
app/src/main/AndroidManifest.xml
<service android:name=".NorthwindPushes" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

handlePushArrival is safe from any thread, and answers a CrmPushResult:

  • isCrm: one of PurrCRM‘s pushes, which the SDK has acted on. A reply reads the messenger again (the unread count moves), a message from your team makes the app check in, and either reads the inbox again.
  • replyOnScreen: a reply in a conversation the user has open on screen right now. It is already there and read, so show nothing.
  • silent: a nudge with nothing to show. PurrCRM sends one to an app left open, to check in for an in-app message; the SDK has done so. It is no notice, and you show nothing.
  • noticeId: the notice in the user’s inbox the push is, if any.

PurrCRM‘s pushes carry type (support_reply for a reply, crm_message for a message from your team), link (the page, such as /messages/<id>) and notice_id in their data; CrmPushKeys names them.

Show the notification in the channel the push names, and put the push’s data on the Intent it opens, so the tap can be handed over too:

NorthwindPushes.kt
private fun showNotification(message: RemoteMessage) {
val manager = NotificationManagerCompat.from(this)
if (!manager.areNotificationsEnabled()) return
val open = Intent(this, HomeActivity::class.java)
.putExtra(FROM_PUSH, true)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
message.data.forEach { (key, value) -> open.putExtra(key, value) }
val tap = PendingIntentCompat.getActivity(
this, message.messageId.hashCode(), open, PendingIntent.FLAG_UPDATE_CURRENT, false,
)
val notification = NotificationCompat.Builder(
this, message.notification?.channelId ?: CrmConfig.DEFAULT_PUSH_CHANNEL,
)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(message.notification?.title)
.setContentText(message.notification?.body)
.setContentIntent(tap)
.setAutoCancel(true)
.build()
manager.notify(message.messageId.hashCode(), notification)
}
companion object {
const val FROM_PUSH = "from_push"
}

A notification Android showed opens your launcher Activity with the push’s data as the Intent’s extras (beside Firebase’s own, such as google.message_id); the one you showed opens the Activity you named, with the same data. In that Activity, hand the data to the SDK:

HomeActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) handlePushTap(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handlePushTap(intent)
}
private fun handlePushTap(intent: Intent) {
val extras = intent.extras ?: return
// Only an Intent a notification opened (Android's, with Firebase's id, or yours).
if (!extras.containsKey("google.message_id") && !extras.getBoolean(NorthwindPushes.FROM_PUSH)) return
val data = extras.keySet().associateWith { extras.getString(it) }
if (!crm.handlePushTap(data)) {
// Not one of PurrCRM's pages: yours to follow.
}
}

Call handlePushTap only for an Intent a notification opened. It records push_opened when the data is a push: one of PurrCRM‘s (its type is one PurrCRM sends), or one Firebase delivered (it carries google.message_id, as the extras of a notification Android showed do). Anything else answers false and records nothing, so a notification you build yourself for a push of your own counts its opens only when you put message.messageId on its Intent as google.message_id. A PurrCRM push whose link is one of PurrCRM‘s pages answers true, and that page opens through your navigate hook once the user is signed in and you have called setReady(true). One that names a place in your app, or a push of your own, answers false: follow it yourself.

A marketing push goes only to people who agreed to offers by push. If your app asks them, tell PurrCRM:

val agreed: Boolean? = crm.offersByPush() // null when PurrCRM could not be asked
val now: Boolean? = crm.setOffersByPush(true) // PurrCRM's answer, or null

Topics refine this further: see Preferences.

Every push PurrCRM sends is also kept as a notice in the user’s inbox. What you draw: the inbox screen and a bell with its count.

  • crm.notices is a StateFlow<CrmNotices>: notices (read so far, newest first), unread (the whole inbox’s count, for your bell), loaded, loading, failure and hasMore.
  • Each CrmNotice has id, type, title, body, createdAt (epoch milliseconds), link, readAt and unread.
  • crm.refreshNotices() reads the first page again (a pull to refresh), and crm.moreNotices() the next, older page.
  • crm.openNotice(notice) marks it read and answers its link; follow it with crm.openLink(link), which opens one of PurrCRM‘s pages through navigate, a place in your app through followable and openInApp, or a web address.
  • crm.markNoticesRead(ids), or crm.markNoticesRead(emptyList(), all = true), marks notices read; it answers whether PurrCRM took it.

The SDK reads the inbox when a user signs in, when the app comes back to the front, and when a push arrives, and empties it on sign-out.

InboxScreen.kt
@Composable
fun InboxScreen(crm: Crm) {
val inbox by crm.notices.collectAsState()
val scope = rememberCoroutineScope()
LazyColumn {
items(inbox.notices, key = { it.id }) { notice ->
ListItem(
headlineContent = { Text(notice.title, fontWeight = if (notice.unread) FontWeight.Bold else null) },
supportingContent = { Text(notice.body) },
modifier = Modifier.clickable {
scope.launch { crm.openLink(crm.openNotice(notice)) }
},
)
}
if (inbox.hasMore) item { LaunchedEffect(Unit) { crm.moreNotices() } }
}
}
  • The setup check has a row each for the permission, the token, the channel and your handler, and a Test a push action.
  • Send a test push on Settings › your app › Delivery › Push (Push my phones) sends one to your own phones.
  • Under Testing › Preview on my phone, make your phone a test phone, then send a push from any message with Try it on my test phone.