In recent years, in-app chat has become an essential feature to provide for mobile app users. Whether you're creating a telehealth application or enhancing user engagement for your marketplace app, providing a seamless in-app chat experience is key.
This tutorial explains how to use CometChat's Android UI Kit to develop a comprehensive in-app messaging system that can be tailored to fit your specific workflows. The tutorial will use the Kotlin language for building the Android application.
The diagram below illustrates the architecture of the app that you'll build. It includes the welcome and auth screens that you'll make from scratch. For all other screens, you'll use the CometChat UI Kit's prebuilt components.
Prerequisites
Before getting started, you’ll need a few things to complete the tutorial. You should have an Android development environment set up on your system and an Android device (physical or emulated) for testing the app.
If you don’t have one already, you’ll need to set up a trial CometChat account . Once you have an account, generate a new app from the CometChat dashboard and get your App ID, Region, and Auth Key from the app’s Credentials page. You'll need these values while configuring the CometChat SDK in your application.
You also need to add Firebase support to your Android app, as the tutorial uses Firebase to handle notifications in the app.
Developing the Chat App
In this tutorial, you'll integrate CometChat's Android UI Kit into your Android application for chat functionality and use its prebuilt chat screens.
Add real-time chat with minimal effort using CometChat
Installing the App Dependencies
The CometChat UI Kit is hosted in a custom Maven repository, and you need to add its URL to your app's repository settings so you can pull from it. Include the Maven repository URL for CometChat in the settings.gradle
file using the following code snippet:
Note: For older apps, you might need to include the Maven URL in the project-level build.gradle
file instead of settings.gradle
.
You need to include Maven dependency for the CometChat UI Kit in your Android application. Add the following to the app/build.gradle
file under the dependencies
section:
The Android toolchain allows you to customize the Android manifest by specifying dynamic details through variable declarations, known as Android manifest placeholders. You need to add a file_provider
for CometChat's file attachments to work. Add manifestPlaceholders
under android > defaultConfig
and set its value to your app's package name:
Make sure that compileOptions
under android
is set to the following:
Finally, enable Jetifier by adding the following property to the gradle.properties
file:
Configuring the AndroidManifest File
The tutorial defines login, sign-up, and conversation activities in later sections. These activities need to be registered in AndroidManifest.xml
before you can run the application. Also, the android:theme
property needs to be set at the application level for activities to inherit from it. Update the application
tag in the project's AndroidManifest.xml
file to:
Note the changes made to the AndroidManifest.xml
file:
- You set the android:theme
to @style/Theme.MaterialComponents
at the application level, which will apply the theme to all activities.
- You add LoginActivity
, SignupActivity
, and ConversationsActivity
to the manifest. Android Studio might complain that these files don't exist, but you'll create the XML and Kotlin files for these activities in later sections.
- You set the `android:exported` property to false
for all activities except MainActivity
, since you don't need to directly launch these activities from other applications.
Configuring the CometChat SDK Credentials
Create a Constants.kt
file in your Android project and add the app ID, region, and auth key that you obtained when creating the CometChat
app:
Setting Up CometChat's Android UI Kit
You need to initialize the CometChat UI Kit for Android SDK before using its prebuilt components. The CometChatUIKit.init
method takes the following inputs:
- Activity context
- UIKitSettings
, which lets you customize the CometChat UI Kit. You also need to pass the app credentials (region, app ID, and auth key) to it.
You'll initialize it in the onCreate
callback of MainActivity
. Create the initCometChatUiKit
method in MainActivity.kt
:
Next, call this method at the end of your activity's onCreate
method:
Creating the Login and Sign-Up Pages
CometChat doesn't handle user management for applications, and you can continue using your preferred authentication backend in your application. Once the user authenticates with your system, you can add them with the CometChat application using a unique ID (`uid`). Your application backend needs to generate a uid
to map a user in your system with CometChat. You could also use an existing unique identifier as an uid
. CometChat's user functionality is designed to make it easy for you to quickly get and add users to your CometChat experience. You need to call the SDK's createUser
and login
methods after the user has signed up or has logged in to your application.
If you are embedding chat into an existing application that has existing users, you can use CometChat's migration APIs to import them and create users in the CometChat system.
For this example, you'll skip backend authentication and directly call CometChat's login
and createUser
methods.
Sign-Up Page
You can build and customize the sign-up page as per your app's needs, but this example limits it to two fields: userId
and username
.
First, create an activity_signup.xml
file in the layout
directory and add the code from this file hosted on GitHub.
Next, create SignupActivity.kt
in the app's package directory and replace the code with the following:
Let's go over the code for the activity class:
- Clicking the "sign up" button calls the createUser
method. This method, in turn, uses the CometChat.createUser
method to pass the User
request object as an argument. You can set the uid
(unique ID) and name
properties with the User
object.
- The onSuccess
callback in the createUser
method invokes the CometChat.login
method, passing the uid
to it.
- Upon successful login, the user is redirected to ConversationsActivity
, which you'll build in later sections.
The screenshot below shows how the sign-up form would render for the user:
Login Page
For the login page, you need to create a form with a text field for userId
. Create an activity_login.xml
file in the layout
directory and add the code from this file hosted on GitHub.
Next, create LoginActivity.kt
in the app's package directory and replace the code with the following:
The code for the activity class does the following:
- The login
method is called when the "login" button is clicked. login
calls the CometChat.login
method, passing uid
to it.
- Upon successful login, the user is redirected to ConversationsActivity
.
The screenshot below shows how the login form would render to the user:
Updating MainActivity
You need to update MainActivity
to set up UI buttons and navigation to the login and sign-up activities that you just defined. Update the activity_main.xml
file in the layout
directory with code from this file hosted on GitHub. The layout file defines login and sign-up buttons.
Next, create a function in the MainActivity.kt
file to set click event handlers for the login and sign-up buttons:
Update the activity's onCreate
method to call the initEventHandlers
method:
Next, add a method that checks if the user is already logged in and redirects them to the conversations page:
Update the activity's onCreate
method to call the checkLoginStatus
method:
Setting Up the Conversations Screen
You're now going to build the conversations screen that displays users' one-to-one and group conversations. You can utilize the CometChat UI Kit's CometChatConversationsWithMessages
component for this screen. The look and feel of the UI can be customized to match your brand and app identity.
The component provides the following features:
- Displays a list with a user's one-to-one and group chats. Clicking a one-to-one chat opens the `CometChatUsersWithMessages` component, and clicking a group chat opens the `CometChatGroupsWithMessages` component.
- Contains a button in the header to initiate a new chat. It opens up the `CometChatContacts` widget, allowing the user to select either a contact or a group.
Create a ConversationsActivity.kt
file in the app's package directory with the following code:
The screenshot below compares the conversation list screen and the one-to-one conversation screen:
Adding Advanced Chat Features
You'll now look at some advanced chat customization capabilities of the CometChat UI Kit for Android. Specifically, you'll learn how to enhance the chat experience by customizing elements such as the user's presence indicator, typing status, and read receipts. You'll also learn how to add custom file attachments and notification support to the application using the CometChat UI Kit.
Check out the `setConversationsConfig` method on GitHub, which applies the configuration for all the advanced features discussed in the next few sections.
Presence Indicator
The presence indicator helps users understand whether a contact is online or not. You'll add this using the UI Kit's `ConversationsConfiguration` config object, which you could also use to modify a component's properties such as title, styling, icons, back button behavior, etc. You can set disableUsersPresence
in ConversationsConfiguration
to control the presence indicator in the conversations list view:
Typing Status
Typing status indicates to the recipient whether the sender is typing or not. It contributes to real-time interaction awareness, reduced ambiguity, and improved user engagement. Typing status indicators adds a layer of richness to digital conversations.
You use the UI Kit to control the typing indicator. In the conversations list, you can set the disableTyping
property of ConversationsConfiguration
to indicate if a participant in a conversation is typing:
In the conversation view, you can set the setDisableTyping
property of MessagesConfiguration
to indicate if the sender is typing:
Read Receipts
A read receipt informs the sender whether or not the recipient has read the message. It enhances the overall communication experience by offering transparency, improving engagement, and providing valuable information on the status of messages within a chat application. The flexibility to control these receipts adds an extra layer of customization to cater to diverse user preferences.
With the UI Kit, you can control read receipts by setting the disableReceipt
property of ConversationsConfiguration
to enable or disable read receipts, which are shown in the subtitle of the conversation item:
File Attachments
The UI kit has built-in support for sending media messages, including photos and videos from the gallery, photos clicked from the camera, files and documents, and audio files.
While the UI Kit offers built-in support for attaching common media formats, there could be scenarios where you need to use the CometChat SDK to incorporate custom attachment support into your app. Consider instances where users may want to share other file formats, such as TIFF or DICOM, often used to store X-ray or Radiology images in the medical field.
Notifications
Push notifications keep users informed and engaged with real-time updates. In the context of a chat application, the goal is to provide users with timely alerts for new messages, ensuring they stay connected and promptly respond to incoming communication.
You can integrate push notifications for chat messages in your application using CometChat's push extension for Android. In this section, you'll learn how to enable push notifications for chat messages using Firebase Cloud Messaging (FCM). To integrate notifications into your app, follow these steps:
- Create a new Firebase project and enable cloud messaging for it. You can follow the setup instructions in this guide.
- Enable and configure the push notification extension for your CometChat application using the dashboard by following this guide.
Next, you'll set up push notifications in the Android app. Add the Firebase Cloud Messaging library dependency in the app/build.gradle
file:
Create MyFirebaseMessagingService.kt
in the app package and add the following code snippet to it:
In this code snippet:
- The onMessageReceived
method handles all incoming push notifications
- CometChatHelper.processMessage
parses the CometChat push notification payload
- Finally, the showNotifcation
method constructs a NotificationCompat
object with the parsed message to be displayed on the user's device
Next, create a registerPushToken
method in LoginActivity.kt
to register the device's push notification token with the CometChat server:
Call the registerPushToken
method in the login success callback:
Finally, update the AndroidManifest.xml
file to add MyFirebaseMessagingService
, which you defined earlier:
More Chat Customization Options
This section briefly explores some additional CometChat Android SDK features tailored for specific use cases.
Moderation
Chat moderation involves monitoring and managing online conversations to ensure compliance with community guidelines, prevent inappropriate content, and maintain a safe and respectful environment. Application admins can opt to use moderation features to maintain a safe and controlled environment within their app.
The SDK offers multiple extensions for moderating chats, including slow mode , user and message reporting, a profanity filter, image moderation, and virus and malware scans. CometChat also offers manual chat moderation tools through its web dashboard, enabling admins to take action on inappropriate content.
Canned Conversation Starters
Conversation starter is an AI-powered feature that allows you to fetch a starting message in a new conversation. The feature uses AI to analyze a user's recent messages to suggest a set of conversation starter messages. It returns a set of starting messages that can help direct the flow of the conversation. For example, based on recent messages from other chats, it could return "Good morning, how may I help you?" as one of the starting messages. Chat applications with communities or bots might opt for this feature to suggest messages in a new conversation. You can use the CometChat.getConversationStarter
method to fetch starter messages for a new conversation. The method also accepts a configuration object that can be used to customize the results.
Video and Audio Calling
Video Calling SDK allows you to integrate audio and video calling into your application with minimal configuration. For example, social media or business applications could use this feature to make the chat more engaging. If your application uses the CometChat UI Kit, integrating calling support is even easier. You can enable outgoing call support by simply adding the Calls SDK library dependency. Integrating incoming call support requires a few additional steps, for which you can follow this guide.
Conclusion
This tutorial provided an overview of how to use CometChat SDKs and UI kits to create a comprehensive messaging system that rivals popular apps like WhatsApp but also meets the specific needs of businesses. The CometChat Android SDK and UI Kit for Android offer a versatile and customizable solution for any in-app chat application. Regardless of whether you are a single developer or a business team, CometChat gives you the ability to create an interactive and engaging chat experience for your users.
Vivek Kumar Maskara