---
url: https://talkjs.com/docs/UI_Components/Android/Push_Notifications_Guide/
title: "Enable push notifications | Android | TalkJS Docs"
---

For AI agents: Find a documentation index at https://talkjs.com/llms.txt (full content at https://talkjs.com/llms-full.txt). Get a markdown version of any page by appending .md to its URL path.

# 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.

## Set up Firebase

If you haven't already, [add Firebase to your Android project](https://firebase.google.com/docs/android/setup), 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](https://talkjs.com/dashboard/). For detailed steps, see [Configure Firebase Cloud Messaging](https://talkjs.com/docs/Guides/Mobile/Configure_FCM/).

## Request the notification permission

On Android 13 (API 33) and higher, your app needs the runtime permission [POST\_NOTIFICATIONS](https://developer.android.com/develop/ui/views/notifications/notification-permission) 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](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#TalkJSNotifications__requestNotificationPermissions) from an `Activity`:

```kotlin
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.

## Register the push notification handlers

Call [TalkJSNotifications.registerPushNotificationHandlers](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#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.

```kotlin
TalkJSNotifications.registerPushNotificationHandlers(
    context = this,
    userProvider = { session.currentUser },
    settings = PushNotificationSettings(
        channelId = "talkjs_messages",
        channelName = "Messages",
    ),
)
```

`userProvider` is a suspend function that returns a [UserRef](https://talkjs.com/docs/Data_APIs/Kotlin/Users/#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.

## Open your app when the user taps a notification

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](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#TalkJSNotifications__registerPushNotificationHandlers):

```kotlin
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](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#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`:

```kotlin
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)
    }
}
```

## Handle notification taps

To run your own code when the user taps a notification, pass an `onNotificationPressed` callback to [registerPushNotificationHandlers](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#TalkJSNotifications__registerPushNotificationHandlers). It receives a [NotificationPressedEvent](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#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.

## Handle new installation IDs

To run your own code whenever the Firebase installation ID changes, pass an `onNewInstallationId` callback to [registerPushNotificationHandlers](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#TalkJSNotifications__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`:

```kotlin
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](https://talkjs.com/docs/Data_APIs/Kotlin/Users/#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`.

### Remove push tokens

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:

```kotlin
session.currentUser.deleteFields("pushTokens.fcm:$installationId")
```

To unregister all the devices previously registered for the user, delete the `pushTokens` field:

```kotlin
session.currentUser.deleteFields("pushTokens")
```

## Using your own Firebase service (optional)

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](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#TalkJSNotifications__registerPushNotificationHandlers):

```kotlin
settings = PushNotificationSettings(
    channelId = "talkjs_messages",
    channelName = "Messages",
    registerBackgroundHandler = false,
),
```

Add the `firebase-messaging` dependency to your app's `build.gradle.kts`:

```kotlin
implementation("com.google.firebase:firebase-messaging")
```

Then call [TalkJSNotifications.handleRemoteMessage](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#TalkJSNotifications__handleRemoteMessage) from your service's `onMessageReceived`. It returns `true` if the message came from TalkJS and the library handled it, and `false` otherwise:

```kotlin
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](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#TalkJSNotifications__updateInstallationId) from `onRegistered`. The library then handles the new installation ID with the `userProvider` and `onNewInstallationId` you passed to [registerPushNotificationHandlers](https://talkjs.com/docs/UI_Components/Android/Push_Notifications/#TalkJSNotifications__registerPushNotificationHandlers):

```kotlin
class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onRegistered(installationId: String) {
        TalkJSNotifications.updateInstallationId(this, installationId)
    }
}
```

Declare your service in your app's manifest as usual:

```xml
<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
```
