Build

How to Add Chat to an Android Application with PubNub

14 min read Oliver Carson on Mar 23, 2022
Try PubNub Today

Free up to 1MM monthly messages. No credit card required.

Subscribe to our newsletter

By submitting this form, you are agreeing to our Terms and Conditions and Privacy Policy.

This tutorial illustrates how to take PubNub’s Chat Components for Android and integrate them into any Android application to add chat functionality. All the steps you need to use the components are i...

We're excited to announce the release of our Chat Components for Android. We've created ready-to-use components for Android developers that make it simple to add essential chat features to your app without the need of developing your own backend services, reducing your time to market. Sign up to learn more about our Chat Components for Android release using the form below. Then, read on to learn how you can use our new Android components in an existing open-source Android app.

Register for PubNub's Chat Community

Get the most recent updates about PubNub’s newest chat features.

By signing up, you’ll also receive:

  • Free PubNub swag
  • Exclusive Q&A sessions, workshops, and webinars with our engineers and product managers
  • The opportunity to have your voice heard by influencing our chat roadmap

PubNub’s Chat Components for Android are easy-to-use, prebuilt UI and chat building blocks to reduce app development resources in getting an application to market.

You can depend on PubNub’s infrastructure of real-time communication for user lists, channel lists, and messages in <100 ms worldwide latency and 99.999% SLA-backed reliability.

Best of all, let PubNub handle the backend services for you. PubNub powers all of the messaging features you would want in a chat app: message delivery in real-time, metadata, user presence, and other chat-related data to facilitate the actions within the chat UI components.

PubNub’s Chat Components for Android can be integrated into your application for a variety of use cases. Chat apps like live event messaging, telemedicine, multiplayer chat lobby, and service desk support can be built with minimal effort using our Android components with features such as:

  • User and Channel Metadata: Add additional information about the users, channels, and their memberships (and store it locally for offline use).

  • Subscriptions: Subscribe to user channels automatically.

  • Messages: Publish and display new and historical text messages.

  • Presence: Get currently active users, observe their state, and notify them about changes.

  • Typing Indicators: Display notifications that users are typing.

  • Persistent Data Storage: Store messages, channels, and users locally.

  • Paging: Pull new data only when you need it.

  • Jetpack Compose: Build native UI with a modern toolkit.

Our Chat Components for Android are modifiable to your requirements, so you’re free to create chat for various use cases all with different functionalities and customizable looks.

This tutorial illustrates how to take PubNub’s Chat Components for Android and integrate them into any Android application to add chat functionality. This post includes all the steps you need to use the chat components. 

You will add chat running on the PubNub Network to JetNews, which is an open-source news application built using Android Kotlin:

Android Chat App Example

This open-source mobile app was selected to add chat driven by PubNub’s Chat Components because it could benefit from chat as an additional feature. This Android project was chosen because it wasn't created by PubNub. We wanted to show you how easy adding Android Components in real apps like this one is easy.

The tutorial was built using Android Studio Bumblebee 2021.1.1 and PubNub Chat Components for Android. We recommend using the latest version of Android Studio available. It is recommended to review PubNub’s Chat Components for Android overview to learn more about chat components.

The complete application of this tutorial is available in the GitHub Repository, in the finished-application branch. The source code contains everything performed in this tutorial.

How does PubNub work with Android Chat Components?

Before using PubNub's Chat Components for Android, you should know why PubNub is the best choice for powering them. PubNub is used for real-time message delivery, metadata, user presence, and other chat-related data to facilitate the actions within the chat UI components.

PubNub is a fantastic backend API for all types of real-time chat applications because it offers a lot of functionality that you never have to build yourself. Some essential advantages of PubNub are:

  • PubNub delivers billions of messages every day and will effortlessly scale with your application as it grows.

  • User presence features are built-in. Easily create online and offline statuses and typing indicators.

  • Storage and Playback for message history. History is essential for a complete user experience.

  • Push notifications to deliver chat messages fast and reliably regardless of whether the application is in the foreground or background.

PubNub Android Chat Components have PubNub services fully incorporated and are ready to use in an existing Android App. It’s recommended that you’re familiar with Kotlin and Android development if you wish to modify the Android components for use in your application. However, you can still follow along, explore, and use these Android Chat Components without prior experience.

Available mobile chat components

The following chat components are included with PubNub's Chat Components for Android:

  • ChatProvider: Top-level component that sets up default chat configuration for themes, repositories, services, and utilities.

  • ChannelList: List of channels that represent chat rooms in the application.

  • MemberList: List of users with properties like names, titles, or avatars.

  • MessageList: Paginated list of messages with sender details.

  • MessageInput: Field to send messages and emojis in chat rooms.

For the purpose of this tutorial, you will be implementing the ChatProvider, MessageList, and MessageInput Chat Components. However, you can easily include the other components if they are necessary to your application.

Now that you have an understanding of the available components for Android, let’s get started by setting-up the required accounts and software.

Getting Started Building an Android Chat App 

To be able to utilize the power of the PubNub Network and receive/send messages in a chat room, you’ll need to sign-up at PubNub to create a free account and configure some required settings. The end result will be two API keys that you’ll use in your mobile chat application. A PubNub account and API keys are always free (perfect for startups).

You’ll first need to sign up for a free PubNub account.

  1. Sign in to your PubNub Dashboard. You are now in the Admin Portal.

  2. Go to Apps on the left hand side of the Portal.

  3. Click the Create New App button in the top-right of the Portal.

  4. Give your app a name.

  5. Click Create.

  6. Click your new app to open its settings.

  7. When you create a new app, the first set of keys are generated automatically. However, a single app can have as many keysets as you like. PubNub recommends that you create separate keysets for production and test environments.

  8. Click on the keyset generated.

  9. Enable the Presence feature for your keyset. This will be used to show how many users are active. Enter "ENABLE" in all caps to confirm your choice. Leave the default settings.

  10. Enable the Storage and Playback feature for your keyset. Leave the default settings.

  11. Click Save Changes on the bottom right of the portal to save your changes.

  12. Copy the Publish and Subscribe Keys to a text editor. You will need them later in this tutorial.

Download Android Studio

This tutorial was developed using Android Studio Bumblebee 2021.1.1. Download the latest stable version of Android Studio for your operating system. This download includes the IDE, Android SDK, and Android Emulator.

Android Application Setup & Configuration

Now that you have your PubNub API keys and software installed, you will set up and configure the open-source Android app.

Download the JetNews app from the GitHub Repository, in the base-application branch. This app is a news feed application and will be your starting point when you add chat features. There are three different ways to download the app:

  1. In a terminal, if you have installed Git or GitHub Desktop as mentioned earlier, navigate to an empty folder of your choosing. Enter the following command to clone the Repository.

    git clone https://github.com/PubNubDevelopers/android-kotlin-chat-tutorial.git
  2. Click on the Green Code button, and select "Open with GitHub Desktop” if you have downloaded the GitHub Desktop Application described in the prerequisites.

    Jetnews App GitHub Menu
  3. In the same menu options as the image above, click on the green "Code" button and click on the “Download ZIP” option to download a zip file containing the repository. Extract this file and place it in a desired location on your computer.

After downloading the app, open the 'JetNews' folder in Android Studio. Once the project has loaded, you will need to create an android virtual device via the Device Manager to emulate the application in a virtual environment. In this tutorial, Pixel 4 API 30 was used as the virtual device.

After creating a virtual Android device, switch to the Project View instead of Android View in the top left corner, as this tutorial describes locations of files in this Project View:

Project View Android Chat Tutorial

Note: The tutorial will be referencing this view frequently when adding files, and will refer to this window as the project file viewer. Please keep this side toolbar open when developing your project.

Add the publish and subscribe keys constants at the end of 'JetNews > gradle.properties' in the project file viewer. Replace the value of these strings with your PubNub Publish and Subscribe Keys taken from your PubNub Account.

# PubNub Publish and Subscribe Keys needed to connect to PubNub's realtime communication network.
PUBNUB_PUBLISH_KEY="publish_key_here"
PUBNUB_SUBSCRIBE_KEY="subscribe_key_here"

In the project file viewer, open 'JetNews > app > build.gradle'. Add the PubNub Dependencies for Kotlin SDK and Chat components for Android at the end of the dependencies block to include the chat sdks.

//PubNub Dependencies
implementation "com.pubnub:pubnub-kotlin:7.0.0"
implementation "com.pubnub.components:chat-android:0.2.0"

In the same 'build.gradle' file, include two buildConfigFields in the defaultConfig property in android that enable you to use the publish and subscribe keys throughout your app. The completed defaultConfig is as below.

defaultConfig {
   applicationId 'com.example.jetnews'
   minSdkVersion 21
   targetSdkVersion 31
   versionCode 1
   versionName '1.0'
   vectorDrawables.useSupportLibrary = true
   testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'

   buildConfigField("String", "PUBLISH_KEY", project.property("PUBNUB_PUBLISH_KEY") as String)
   buildConfigField("String", "SUBSCRIBE_KEY", project.property("PUBNUB_SUBSCRIBE_KEY") as String)
}

You will need to sync the Gradle files so the application can detect these new dependencies. Click on the "Sync now" button at the top of the file after saving or press the "Sync Project with Gradle Files" Button in the toolbar at the top of Android Studio.

Android Chat Sync Gradle Files

Open 'JetNews > app > src > main > AndroidManifest.xml' to view the manifest of the application. The PubNub Network API requires internet permissions, otherwise you cannot connect to the PubNub Network. Add the following line in the manifest element, before the application block.

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

In the project file viewer, in 'JetNews > app > src > main > java > com.examples.jetnews > ui', right click and create a new package called 'chat'. Then, right click on the newly created package 'chat' and perform 'New > Kotlin Class/File'. Create one Kotlin Class titled 'ChatActivity.kt' and one Kotlin File titled 'Chat.kt'. This class and file will be discussed and implemented at a later time.

To be able to use the PubNub Chat SDKs, you will need to import the necessary packages in each of the files using the PubNub API. These packages are provided when implementing the chat components in their respective files.

Integrating PubNub Android Chat Components

The chat functionality will be implemented as a separate screen when clicking on a chat icon when viewing an article. You will first need to setup the icon to open the chat room as a separate screen.

Initialize the Database

This application uses the PubNub network to obtain previous messages sent by users for the articles (chat channels) they chatted about. This application will also use the Android Room persistence library to save data in a local database.

In the project file viewer, import the package to use this database in 'JetNews > app > src > main > java > com.example.jetnews > JetnewsApplication.kt', the entry point for the application.

import com.pubnub.components.data.Database

Then proceed to initialize the database in the same 'JetnewsApplication.kt' file in the onCreate function. The onCreate function will then look as the following:

override fun onCreate() {
   super.onCreate()
   container = AppContainerImpl(this)
   Database.initialize(this)
}

Add the Chat Button

Ideally, a chat room would be available on a per article basis, where the ID of the article is used as the channel name in the PubNub Network. For this tutorial, the only chat room that will be created is titled “default-article”. This means that there is only one chat room (channel on the PubNub Network) in this tutorial. To get to the chat room, a chat button will be added to the bottom toolbar of each article.

In the project file viewer, add a new button to the bottom bar in the ArticleScreen function in 'JetNews > app > src > main > java > com.example.jetnews > ui > article > ArticleScreen.kt' by adding a new function parameter onOpenChat to the bottom bar initialization function BottomBar.

Note: Please comment out the modifier = Modifier.navigationBars... parameter in the BottomBar function call. There is a current commit that is causing build failure due to this line.

// Show the bottom bar if the screen is not expanded
bottomBarContent = if (!isExpandedScreen) {
   {
       BottomBar(
           onUnimplementedAction = { showUnimplementedActionDialog = true },
           isFavorite = isFavorite,
           onToggleFavorite = onToggleFavorite,
           onSharePost = { sharePost(post, context) },
           onOpenChat = { openChat(post,context)} //Add onOpenChat
           //modifier = Modifier.navigationBarsPadding(start = false, end = false)
           //Commenting out the modifier variable. Currently an issue from recent commits.
       )
   }
} else {
     { }
},

Update the initialization function BottomBar in the same 'ArticleScreen.kt' file with this new onOpenChat parameter by adding a function to style the chat button (handled in 'JetNewsIcons.kt') and to apply the click event handler.

/**
 * Bottom bar for Article screen
 *
 * @param onUnimplementedAction (event) called when the user performs an unimplemented action
 * @param isFavorite (state) if this post is currently a favorite
 * @param onToggleFavorite (event) request this post toggle it's favorite status
 * @param onSharePost (event) request this post to be shared
 * @param onOpenChat (event) open a chat room for the article.
 */
@Composable
private fun BottomBar(
   onUnimplementedAction: () -> Unit,
   isFavorite: Boolean,
   onToggleFavorite: () -> Unit,
   onSharePost: () -> Unit,
   onOpenChat: () -> Unit, //Add onOpenChat
   modifier: Modifier = Modifier
) {
   Surface(elevation = 8.dp, modifier = modifier) {
       Row(
           verticalAlignment = Alignment.CenterVertically,
           modifier = Modifier
               .height(56.dp)
               .fillMaxWidth()
       ) {
           FavoriteButton(onClick = onUnimplementedAction)
           BookmarkButton(isBookmarked = isFavorite, onClick = onToggleFavorite)
           ShareButton(onClick = onSharePost)
           ChatButton(onClick = onOpenChat) //Add ChatButton Function
           Spacer(modifier = Modifier.weight(1f))
           TextSettingsButton(onClick = onUnimplementedAction)
       }
   }
}

In the same 'ArticleScreen.kt' file, add the function openChat that handles the click event. This function will change the activity to now transition to the chat room. The error for the ChatActivity parameter in the Intent function will be resolved towards the end of the tutorial in the Add the Activity section.

/**
* Opens chat for the article
*
* @param post to grab id from
* @param context Android context to show the chat in
*/

fun openChat(post:Post, context: Context) {
   val intent = Intent(context, ChatActivity::class.java)
   context.startActivity(intent) //transition to chat activity
}

Add the packages to 'ArticleScreen.kt' to use the ChatButton function and 'ChatActivity.kt' class.

import com.example.jetnews.ui.utils.ChatButton
import com.example.jetnews.ui.chat.ChatActivity

In the project file viewer, navigate to 'JetnewsIcons.kt' in 'JetNews > app > src > main > java > com.example.jetnews > ui > util'. You will add a function ChatButton that handles the click event and styles the chat icon.

The image of the chat icon uses Icons.Filled.Chat in the material package. Replace the androidx.compose.material.icons.filled packages instead with androidx.compose.material.icons.filled.*. The file package imports should now look like the following:

package com.example.jetnews.ui.utils

import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.IconToggleButton
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.semantics
import com.example.jetnews.R

Add the function ChatButton to handle the click event and style the chat icon. The text will be added as a string resource as described below. This is for best practice and is already in place for this open-source application.

@Composable
fun ChatButton(onClick: () -> Unit) {
   IconButton(onClick) {
       Icon(
           imageVector = Icons.Filled.Chat, //icon included in material package
           contentDescription = stringResource(R.string.article_chat)
       )
   }
}

In the project file viewer, add the string for the chat icon as a string resource in the "Article Screen block by adding a new string element in 'JetNews > app > src > main > res > values > strings.xml'.

<string name="article_chat">Chat</string>

Incorporate PubNub Chat Components

Navigate in the project file viewer to 'JetNews > app > src > main > java > com.example.jetnews > ui > theme > Theme.kt'. Add two package imports to this file to begin using the PubNub API.

import com.pubnub.api.PubNub
import com.pubnub.components.chat.provider.ChatProvider

Add the new function ChatAppTheme below the JetNewsTheme function. ChatAppTheme defines the chat application’s theme and will call the ChatProvider Chat Component, which is a top-level component that sets up default chat configuration for themes, repositories, services, and utilities.

@Composable
fun ChatAppTheme(
   darkTheme: Boolean = isSystemInDarkTheme(),
   pubNub: PubNub,
   content: @Composable() () -> Unit
) {
   MaterialTheme(
       colors = if (darkTheme) DarkThemeColors else LightThemeColors,
       typography = JetnewsTypography,
       shapes = JetnewsShapes,
   ) {
       ChatProvider(pubNub) {
           content()
       }
   }
}

'ChatActivity.kt' and 'Chat.kt' will contain the logic of incorporating PubNub Chat Components into the open-source application. Both files are presented in its entirety below, but highlight the important functions to demonstrate how the chat components are constructed.

ChatActivity.kt

'ChatActivity.kt' contains the logic of initializing the PubNub objects, generating user IDs, creating the publish and subscribe memberships, and populating the database with these memberships.

The 'ChatActivity.kt' class is given below in its entirety. Copy this code in the project file viewer to 'JetNews > app > src > main > java > com.example.jetnews > ui > chat > ChatActivity.kt'.

package com.example.jetnews.ui.chat

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import com.example.jetnews.BuildConfig
import com.pubnub.api.PNConfiguration
import com.pubnub.api.PubNub
import com.pubnub.api.enums.PNLogVerbosity
import com.pubnub.components.chat.provider.LocalMemberRepository
import com.pubnub.components.chat.provider.LocalMembershipRepository
import com.pubnub.components.chat.ui.component.provider.LocalChannel
import com.pubnub.components.chat.viewmodel.message.MessageViewModel
import com.pubnub.components.data.member.DBMember
import com.pubnub.components.data.membership.DBMembership
import com.example.jetnews.ui.theme.ChatAppTheme
import com.pubnub.components.repository.member.DefaultMemberRepository
import com.pubnub.components.repository.membership.DefaultMembershipRepository
import com.pubnub.framework.data.ChannelId
import kotlinx.coroutines.launch

class ChatActivity : ComponentActivity() {

   private lateinit var pubNub: PubNub

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       initializePubNub()
       var channelId = "default-article"; //default channel name
       setContent {
           ChatAppTheme(pubNub = pubNub) {
               AddDummyData(channelId)
               Box(modifier = Modifier.fillMaxSize()) {
                   ChannelView(id = channelId)
               }
           }
       }
   }

   override fun onDestroy() {
       destroyPubNub()
       super.onDestroy()
   }

   private fun initializePubNub(){
       pubNub  = PubNub(
           PNConfiguration(uuid = getRandomString(6)).apply {
               publishKey = BuildConfig.PUBLISH_KEY
               subscribeKey = BuildConfig.SUBSCRIBE_KEY
               logVerbosity = PNLogVerbosity.NONE
           }
       )
   }

   //Generates random username based on length of integer. Taken from https://stackoverflow.com/questions/46943860/idiomatic-way-to-generate-a-random-alphanumeric-string-in-kotlin
   private fun getRandomString(length: Int) : String {
       val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
       return (1..length)
           .map { allowedChars.random() }
           .joinToString("")
   }

   private fun destroyPubNub(){
       pubNub.destroy()
   }

   // Channel view
   @Composable
   fun ChannelView(id: ChannelId) {
       // region Content data
       val messageViewModel: MessageViewModel = MessageViewModel.defaultWithMediator(id)
       val messages = remember { messageViewModel.getAll() }
       // endregion

       CompositionLocalProvider(LocalChannel provides id) {
           Chat.Content(
               messages = messages,
           )
       }
   }

   @Composable
   fun AddDummyData(vararg channelId: ChannelId) {

       // Creates a user object with uuid
       val memberRepository: DefaultMemberRepository = LocalMemberRepository.current
       val member: DBMember = DBMember(id = pubNub.configuration.uuid, name = pubNub.configuration.uuid, profileUrl = "https://picsum.photos/seed/${pubNub.configuration.uuid}/200")

       // Creates a membership so that the user could subscribe to channels
       val membershipRepository: DefaultMembershipRepository = LocalMembershipRepository.current
       val memberships: Array<DBMembership> = channelId.map { id -> DBMembership(channelId = id, memberId = member.id) }.toTypedArray()

       // Fills the database with member and memberships data
       val scope = rememberCoroutineScope()
       LaunchedEffect(null) {
           scope.launch {
               memberRepository.add(member)
               membershipRepository.add(*memberships)
           }
       }
   }
}

Let's dive into the key functions of the 'ChatActivity.kt' class.

onCreate
  • Initializes the chat room by calling the Chat Provider component in 'Theme.kt' and the other necessary functionality for the MessageList and MessageInput Chat Components.

  • For the purpose of this tutorial, it creates a static channel name that defines the chat room name of "default-article".

initializePubNub
  • Creates and sets the PubNub Object.

  • Houses the configuration containing a UUID, publish key, and subscribe key.

    • UUID is 6 randomly generated characters. Helper method getRandomString is called to perform this action.

  • Publish and subscribe keys are called from 'build.gradle' defined in the set-up. BuildConfig is generated when building the application.

ChannelView
  • Obtains the messages from the channel ID and displays the chat messages by calling on the Chat.Content function (more on this in the 'Chat.kt' section below).

AddDummyData
  • Creates the user object with UUID, and creates a membership so that users could subscribe to channels

  • Automatically handles subscribing to channels for you.

  • Fills the database with members (users) and membership data.

  • This will automatically create the connection for the user to be subscribed to this channel and be able to receive messages from other users.

Chat.kt

'Chat.kt' displays and sends messages by using the MessageList and MessageInput Chat Components. These UI components are displayed in column format for easy visual representation.

In the project file viewer in J'etNews > app > src > main > java > com.example.jetnews > ui > chat > Chat.kt':

package com.example.jetnews.ui.chat

import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.tooling.preview.Preview
import androidx.paging.PagingData
import com.pubnub.components.chat.ui.component.input.MessageInput
import com.pubnub.components.chat.ui.component.input.renderer.AnimatedTypingIndicatorRenderer
import com.pubnub.components.chat.ui.component.message.MessageList
import com.pubnub.components.chat.ui.component.message.MessageUi
import com.pubnub.components.chat.ui.component.presence.Presence
import com.pubnub.components.chat.ui.component.provider.LocalChannel
import com.pubnub.components.chat.viewmodel.message.MessageViewModel
import com.pubnub.framework.data.ChannelId
import com.pubnub.framework.data.UserId
import kotlinx.coroutines.flow.Flow

object Chat {

   @Composable
   internal fun Content(
       messages: Flow<PagingData<MessageUi>>,
       presence: Presence? = null,
       onMemberSelected: (UserId) -> Unit = {},
   ) {
       val localFocusManager = LocalFocusManager.current

       Column(
           modifier = Modifier.fillMaxSize()
               .pointerInput(Unit) {
                   detectTapGestures(onTap = {
                       localFocusManager.clearFocus()
                   })
               }
       ) {
           MessageList(
               messages = messages,
               presence = presence,
               onMemberSelected = onMemberSelected,
               modifier = Modifier
                   .fillMaxSize()
                   .weight(1f, true),
           )

           MessageInput(
               typingIndicator = true,
               typingIndicatorRenderer = AnimatedTypingIndicatorRenderer,
           )
       }
   }

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

       CompositionLocalProvider(
           LocalChannel provides channelId
       ) {

           Scaffold(
               content = {
                   Content(
                       messages = messages,
                   )
               }
           )
       }
   }
}

@Composable
@Preview
private fun ChatPreview() {
   Chat.View("default-article")
}

Let's break-down what the two components are doing:

MessageList
  • This component is responsible for displaying provided messages.

  • It can display all or a selective group of messages of the channel/application to users.

  • A particular parameter to focus on when using this component is the messages parameter.

    • This parameter is obtained by creating a MessageViewModel class to store and manage UI-related data.

    • It then calls a function to grab the required number of messages (in this case, getAll), which returns the paged list of required data based on the date.

MessageInput
  • This component is responsible for sending messages (publish) and showing the typing indicator.

Add the Activity

As described earlier, the chat functionality will be implemented as a separate screen when clicking on a chat icon when viewing an article. To do this, you will need to add a new activity element with the path to the 'ChatActivity.kt' Class created earlier.

Open the 'AndroidManifest.xml' file in 'JetNews > app > src > main'. There should currently be one activity listed: .ui.MainActivity. Below this activity block, add a new activity to the manifest for the chat room to be available as a separate screen:

<activity android:name=".ui.chat.ChatActivity" android:exported="false" />

Running Your Chat App

You are now ready to test and run your application. To run the application, you will be focusing on the top toolbar in Android Studio. Sync the files by clicking on the “Sync Project with Gradle Files” button in the upper right corner of Android studio:

Android Chat Sync Gradle Files

Select “app” as the Run/Debug Configuration, and choose the emulated device created earlier as the available device.

Android Chat Run Config

Click the green play button next to the available devices drop-down to run the application. The emulator will display and load the JetNews application on the virtual device.

Note: Depending on your machine/processes going on, a pop-up stating that the app is not responding may appear as the app is loading/in-use. Click on the “wait” option to allow the app to load.

Once the app is loaded, click an article to view. Click on the chat icon on the bottom toolbar to open the chat room.

Android Chat Application Chat Room Button

You can view previous messages sent in this chat room for the article and send chat messages by click in the Type Message field, typing a message, and pressing the send button.

Android Chat App Example

Verifying Your PubNub Connected Message App

You might be wondering how to determine if this chat app is actually running on the PubNub Network. To be able to verify that the application is connected to the PubNub Network, you will need at least two users registered in the database for the “default-article” channel. You will be connecting to the network from two separate sources and each source is required to connect using a user already registered in the database.

To do this, restart the application and repeat the same process of running the application above to register another user. The usernames are the UUIDs needed for communication in the network.

Go to the debug console in the browser while you are in the chat room in the application. In the debug console, enter in the publish and subscribe keys for the keyset that the application is using. You will also need to enter in the channel name of "default-article" in the channel field. Finally, enter the first UUID (username) generated from the application that already exists in the database.

Subscribe to this channel by clicking the slider on the right hand side in the debug console:

Android Chat Tutorial Debug Console Subscribe

You're now ready to test the publish/subscribe functionality essential to the PubNub Network for your chat app.

In the Android Application, begin typing. In the debug console, you can see a typing indicator in the debug console in the Messages section:

Android Chat Typing Indicator

Send your new message in the Android app. You should be able to see the received messages get logged in two places in the debug console.

  • In the Messages section:

Android Chat Publish Message
  • In the History section in the bottom right hand of the screen by clicking on the refresh icon in the same section:

Android Chat Publish Message History

Finally, you will send a message from the Debug Console to your Android App to test the subscribe functionality.

In the debug console, send a message by formatting a message in the Message section.

Format the message as a JSON object. Include the following three fields:

  1. text: The message the user wants to send.

  2. type: The type of the message - leave as default as shown below.

  3. id: The ID of the message in the PubNub Network. This must be a unique, random string. The example below shows the message with a generated id that is slightly altered from the id sent by the application.

Below is an example of a message to send to an Android application.

Android Chat Debug Console Example Message

Press the blue “Publish a Message Button” as shown in the above screenshot. You should be able to view this message from the admin user in the application chat room:

Android Chat Verify Subscribe

What’s Next with Android Chat Components

In this tutorial, you looked at how PubNub’s Chat Components for Android can be implemented into an existing application. You set-up a PubNub Account, configured and integrated PubNub chat components into an open-source Android Application, and successfully created a working chat app. The complete application of this tutorial is available in the GitHub Repository, in the finished-application branch. The source code contains everything performed in this tutorial, as well as cleaning up unnecessary files for this application.

PubNub’s Chat Components for Android provide a fantastic starting point to build chat into any Android application. Let PubNub handle creating and maintaining a reliable, stable, and fast real-time infrastructure so you can focus on customizing the components to fit your application’s needs.

Take a look at our Kotlin SDK and Android Chat Components documentation to further customize your application. Enhance this chat app by adding the ChannelList and MemberList Android Chat Components to list the different article chat rooms and list of users. You can even expand this chat app to be a group chat, as demonstrated in PubNub’s React sample chat app.

Need some assistance modifying or building with Android Chat Components? Get in touch with our sales team and we’ll help you get started.

More from PubNub

Top Trends to Engage Your App Users
InsightsSep 27, 20224 min read

Top Trends to Engage Your App Users

Take a look at the top trends that are the most effective in attracting customers and reducing churn, and how you can incorporate...

PubNub Staff

PubNub Staff

Comparing Game Engines: Unity vs Unreal vs the Rest
Real-Time Gaming BlogSep 21, 20225 min read

Comparing Game Engines: Unity vs Unreal vs the Rest

Comparing the major game engines: Unity vs Unreal Engine vs Corona SDK vs GameMaker Studio, including the benefits and cons of...

PubNub Staff

PubNub Staff

Python Socket Programming: Client, Server and Peer Libraries
BuildSep 21, 20226 min read

Python Socket Programming: Client, Server and Peer Libraries

Sockets (aka socket programming) enable programs to send and receive data, bi-directionally, at any given moment. This tutorial...

PubNub Staff

PubNub Staff