Enable push notifications
Show TalkJS push notifications in your Android app.
This guide shows you how to set up and receive push notifications from TalkJS in your Android app. Android Components delivers them through Firebase Cloud Messaging (FCM), groups them into one notification per conversation, and tells your app when the user taps one.
If you haven't already, add Firebase to your Android project, including the google-services Gradle plugin and your google-services.json file.
Then add your Firebase service account private key on the Settings page in your TalkJS dashboard. For detailed steps, see Configure Firebase Cloud Messaging.
On Android 13 (API 33) and higher, your app needs the runtime permission POST_NOTIFICATIONS to display notifications. Android Components already declares it in its manifest, so you don't need to add it to yours.
To ask the user for it, call TalkJSNotifications.requestNotificationPermissions from an Activity:
TalkJSNotifications.requestNotificationPermissions(activity, requestCode = 1)You can do this at any point in your app's flow that makes sense for your users. On older Android versions, the call does nothing.
Call TalkJSNotifications.registerPushNotificationHandlers from Application.onCreate. You have to call it there because Android can start your app's process to deliver a notification without opening any activity. The callbacks you pass only exist after this call has run.
TalkJSNotifications.registerPushNotificationHandlers(
context = this,
userProvider = { session.currentUser },
settings = PushNotificationSettings(
channelId = "talkjs_messages",
channelName = "Messages",
),
)userProvider is a suspend function that returns a UserRef. Whenever the Firebase installation ID changes, the library calls it. The library then unregisters the old installation ID from the returned user and registers the new one.
Once registered, any message sent to this user in TalkJS triggers a push notification when the user is offline.
Android Components can open your app when the user taps a notification.
To choose the activity it opens, pass the activity class as activityToOpen to registerPushNotificationHandlers:
TalkJSNotifications.registerPushNotificationHandlers(
context = this,
activityToOpen = MainActivity::class.java,
settings = PushNotificationSettings(
channelId = "talkjs_messages",
channelName = "Messages",
),
)The intent that starts the activity has one extra for each of the constants on TalkJSNotifications: EXTRA_CONVERSATION_ID, EXTRA_IS_FOREGROUND_EVENT, EXTRA_TITLE, EXTRA_BODY, EXTRA_SENDER_ID, EXTRA_MESSAGE_ID, and EXTRA_TIMESTAMP.
If the notification has no message data, EXTRA_CONVERSATION_ID is an empty string, and the sender, message, and timestamp extras are missing.
If your activity is already open, it receives the tap in onNewIntent instead of being created again. Read the conversation ID in both onCreate and onNewIntent, then pass it to a Chatbox:
class MainActivity : ComponentActivity() {
private var conversationId by mutableStateOf<String?>(null)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
conversationId = intent.getStringExtra(TalkJSNotifications.EXTRA_CONVERSATION_ID)
setContent {
conversationId?.let {
Chatbox(appId = "<APP_ID>", userId = "<USER_ID>", conversationId = it)
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
conversationId = intent.getStringExtra(TalkJSNotifications.EXTRA_CONVERSATION_ID)
}
}To run your own code when the user taps a notification, pass an onNotificationPressed callback to registerPushNotificationHandlers.
It receives a NotificationPressedEvent, whose data.conversationId is the conversation the notification belongs to.
The library keeps the callback for as long as your process runs, so don't capture an Activity in it.
To run your own code whenever the Firebase installation ID changes, pass an onNewInstallationId callback to registerPushNotificationHandlers.
It receives the old installation ID and the new installation ID.
The old installation ID is null if the app has not received an installation ID before.
If you pass userProvider, the library automatically unregisters the old installation ID and registers the new installation ID with the TalkJS server. If you want to do this manually, omit userProvider and use onNewInstallationId:
TalkJSNotifications.registerPushNotificationHandlers(
context = this,
onNewInstallationId = { oldInstallationId, newInstallationId ->
CoroutineScope(Dispatchers.Default).launch {
oldInstallationId?.let { session.currentUser.deleteFields("pushTokens.fcm:$it") }
session.currentUser.set(pushTokens = mapOf("fcm:$newInstallationId" to true))
}
},
settings = PushNotificationSettings(
channelId = "talkjs_messages",
channelName = "Messages",
),
)In the Kotlin Data API, you store push tokens on the user's pushTokens property, which you set with UserRef.set. Each key combines the push provider and the token ID, separated by a colon, in the format provider:token_id. On Android, the provider is fcm, and the ID is the Firebase installation ID of the app on that device, so a key looks like fcm:abc123.
You can update or remove a push token at any time. Deleting a token's field unregisters that specific device. For example, to unregister a device when the user logs out:
session.currentUser.deleteFields("pushTokens.fcm:$installationId")To unregister all the devices previously registered for the user, delete the pushTokens field:
session.currentUser.deleteFields("pushTokens")By default, Android Components includes a Firebase service that receives and displays all TalkJS push notifications, so you don't need to write one. If your app also receives push notifications that don't come from TalkJS, you need your own FirebaseMessagingService, because Android delivers each message to only one such service. That service receives every message, and your app is responsible for forwarding the TalkJS ones to Android Components.
To turn off the library's service, set registerBackgroundHandler to false in the PushNotificationSettings that you pass to registerPushNotificationHandlers:
settings = PushNotificationSettings(
channelId = "talkjs_messages",
channelName = "Messages",
registerBackgroundHandler = false,
),Add the firebase-messaging dependency to your app's build.gradle.kts:
implementation("com.google.firebase:firebase-messaging")Then call TalkJSNotifications.handleRemoteMessage from your service's onMessageReceived. It returns true if the message came from TalkJS and the library handled it, and false otherwise:
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (TalkJSNotifications.handleRemoteMessage(this, remoteMessage)) {
// This was a TalkJS message, and it has been handled
return
}
// Process non-TalkJS push notification
}
}Since the library's service is turned off, Firebase also sends refreshed installation IDs to your service. Pass them to TalkJSNotifications.updateInstallationId from onRegistered. The library then handles the new installation ID with the userProvider and onNewInstallationId you passed to registerPushNotificationHandlers:
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onRegistered(installationId: String) {
TalkJSNotifications.updateInstallationId(this, installationId)
}
}Declare your service in your app's manifest as usual:
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>