Get started with PubNub Chat Components for Android

Android tutorial

See how to use these chat components to create a simple chat app.

See how you can get a 1:1 chat app quickly up and running.

You will download a sample Android app that uses two PubNub Chat Components for Android: MessageInput and MessageList. Then, you'll run the app and send your first message by typing it in the message input field. The messages will pile up on the screen as you send them.

Prerequisites

Tools used

This guide uses PubNub Kotlin SDK (>= 7.3.2) for chat components and Jetpack Compose as the UI Toolkit.

Steps

Follow the steps to get your PubNub keys, clone the sample Android project files with chat components, and run the app to send your first message.

Create a PubNub account

Before you start, you need to obtain Publish and Subscribe Keys for your chat app. You need them to initialize the PubNub object in your app to send and receive messages through the PubNub Network. To get both keys, sign in or create an account on the Admin Portal. The autogenerated Demo Keyset in My First App already contains the configuration required to complete this guide.

Clone a sample chat app with components

Clone a sample app from the chat-components-android-examples repository.

git clone git@github.com:pubnub/chat-components-android-examples.git

Configure PubNub keys

  1. Once you've cloned the repository, open it in Android Studio and wait until it loads.

  2. In the gradle.properties file, replace both PUBNUB_PUBLISH_KEY and PUBNUB_SUBSCRIBE_KEY with your Publish and Subscribe Keys from your PubNub account in the Admin Portal:

    PUBNUB_PUBLISH_KEY="myPublishKey"
    PUBNUB_SUBSCRIBE_KEY="mySubscribeKey"
  3. Click Sync Now or the Sync Project with Gradle Files icon in the top notification bar to update your Android project.

Sync Project with Gradle Files

The rest of the configuration is already provided:

  • Dependencies to the PubNub Chat Components for Android and the Kotlin SDK are defined in the Dependencies.kt file:

    object PubNub {
    private const val version = "X.X.X"
    const val bom = "com.pubnub:pubnub-kotlin-bom:$version"
    const val kotlin = "com.pubnub:pubnub-kotlin"
    const val memberships = "com.pubnub:pubnub-memberships"

    object Components {
    const val chat = "com.pubnub.components:chat-android:X.X.X"
    }
    }
  • The Settings file stores the base application settings:

    object Settings {
    const val channelId: ChannelId = "Default"
    const val userId: UserId = "myFirstUser"
    val members = arrayOf("myFirstUser", "mySecondUser")
    }
    userId

    For simplicity, the getting started app creates both the myFirstUser and mySecondUser members. To switch between these two users, change the userId value.

  • In the ChatActivity file, the app initializes the PubNub instance in the onCreate() method:

    override fun onCreate(savedInstanceState: Bundle?) {
    ...
    initializePubNub()
    ...
    }

    Similarly, the app will destroy the PubNub instance and clean up all related resources once the application is terminated:

    override fun onDestroy() {
    destroyPubNub()
    super.onDestroy()
    }
  • To associate a sender/current user with the PubNub messages, it's required to configure the userId parameter (also known as userId) to define the default value for the chat user. The app already sets userId in the ChatActivity file, under the initializePubNub() method. Both publishKey and subscribeKey are copied from the gradle.properties file to the BuildConfig file when the project is built.

    private fun initializePubNub(){
    pubNub = PubNub(
    PNConfiguration(UserId(Settings.userId)).apply {
    publishKey = BuildConfig.PUBLISH_KEY
    subscribeKey = BuildConfig.SUBSCRIBE_KEY
    ...
    }
    )
    }
userId

For simplicity, the getting started app sets a static userId. However, if you implement chat in your app, you should generate a userId per user, device, and server and reuse it for their lifetime. Using separate User IDs in real-life apps is particularly important as it impacts your overall billing and the way your app works.

  • The app calls ChatProvider which initializes all the data components. These components are responsible for providing data to UI, setting the default app theme, and communicating with the PubNub service. ChatProvider is initialized by modifying the application theme functionality, in the Theme.kt file. This file is used to facilitate the majority of the functionality provided by PubNub Chat Components for Android.

    @Composable
    fun AppTheme(
    pubNub: PubNub,
    database: DefaultDatabase = Database.initialize(LocalContext.current),
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable() () -> Unit,
    ) {
    val colors = if (darkTheme) DarkColorPalette
    else LightColorPalette

    MaterialTheme(
    colors = colors,
    typography = Typography,
    shapes = Shapes,
    ) {
    show all 21 lines
  • The setContent() method in the ChatActivity file calls the AppTheme() composable function responsible for setting the visual content of chat components' content on the screen:

        setContent {
    AppTheme(pubNub = pubNub, database = ChatApplication.database) {
    Box(modifier = Modifier.fillMaxSize()) {
    Chat.View(Settings.channelId)
    }
    }
    }
  • In the ChatApplication file, the app initializes the default Android Room persistence library to save data in a local database. This database is used to fill the data for all the chat components.

    class ChatApplication : Application() {

    companion object {
    lateinit var database: DefaultDatabase
    }

    override fun onCreate() {
    super.onCreate()
    database = Database.initialize(applicationContext) { it.prepopulate() }
    }
  • The Room database needs data to display in the sample app. This data is provided in the RoomDatabase method in the ChatApplication file. This method is called only once, when the database is created.

    @OptIn(DelicateCoroutinesApi::class)
    private fun prepopulateData(){

    GlobalScope.launch(Dispatchers.IO) {
    with(database) {
    val channelArray = arrayOf(Settings.channelId)

    // Creates user objects with userId
    val members = Settings.members.map { userId ->
    DBMember(
    id = userId,
    name = userId,
    profileUrl = "https://picsum.photos/seed/${userId}/200"
    )
    }.toTypedArray()
    show all 31 lines
            memberDao().insertOrUpdate(*members)
membershipDao().insertOrUpdate(*memberships)
channelDao().insertOrUpdate(*channels)
}
}
}
```
  • In the same Chat.kt file, the app invokes chat components by passing a channel-related ChannelId parameter to the composable function.

    @Composable
    fun View(
    channelId: ChannelId,
    ) {
    // region Content data
    val messageViewModel: MessageViewModel = MessageViewModel.defaultWithMediator()
    val messages = remember(channelId) { messageViewModel.getAll(channelId) }
    // endregion

    CompositionLocalProvider(
    LocalChannel provides channelId
    ) {
    Content(
    messages = messages,
    )
    show all 17 lines
  • The Content function in the Chat.kt file draws the MessageList and MessageInput components in a column.

    @Composable
    internal fun Content(
    messages: Flow<PagingData<MessageUi>>,
    presence: Presence? = null,
    onMessageSelected: (MessageUi.Data) -> Unit = {},
    ) {
    val localFocusManager = LocalFocusManager.current
    Column(
    modifier = Modifier
    .fillMaxSize()
    .background(MaterialTheme.colors.background)
    .pointerInput(Unit) {
    detectTapGestures(onTap = {
    localFocusManager.clearFocus()
    })
    show all 31 lines
  • To make sure the app works upon running, it needs internet permissions to connect to the PubNub Network. This is specified in the AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />
OkHttp version

The Kotlin SDK that PubNub Chat Components for Android are based on uses OkHttp client in version 4.9.3 to handle all HTTP requests. If your chat app uses a different version of the OkHttp client, make sure to override it in the NetworkImage.kt file as follows: val url = data.toHttpUrl().

Run the chat app

Choose an emulator and run the getting-started app.

Send your first message

When your application opens up, type and send your first message. The messages will pile up on the screen as you send them.

Getting Started app for Android

To verify that the app is connected to the PubNub Network, mock a real-live chat conversation with myFirstUser. Open the app in a new emulator, send a message from one emulator and reply to it from another.