ANDROID • KOTLIN • IN-APP CHAT
How to add in-app chat to an Android app (Kotlin)
Build real-time, room-based chat in a native Android app with the RTCExpress chat SDK from Maven Central. You will have two devices sending messages to each other instantly, with recent history loaded when the chat opens, and no chat server, database or WebSocket code to write yourself.
1. What you need
- Android Studio with JDK 17.
- Two Android devices, or one Android phone and an Android emulator, on Android 7.0 (API 24) or newer.
- A free RTCExpress project. Its App ID is in the customer console.
2. Create a project and add the SDK
In Android Studio choose New Project → Empty Views Activity, language Kotlin, minimum SDK API 24. Name it ChatDemo with the package com.example.chatdemo.
The SDK is on Maven Central as com.devsquarelabs:rtcexpress-android. Open app/build.gradle.kts, keep what the template generated, and make sure these lines are there:
android {
defaultConfig {
minSdk = 24
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
implementation("com.devsquarelabs:rtcexpress-android:0.1.6")
}Click Sync Now. Chat needs no runtime permissions, and the SDK's manifest already declares internet access.
3. Create two test tokens
Log in to your customer console → Token tools and create two short-lived tokens in the same project and room:
- User ID alice, room ID chat-test.
- User ID bob, room ID chat-test.
Create Config.kt next to MainActivity.kt and paste in your App ID and both tokens:
package com.example.chatdemo
// Test values from the console's Token tools.
// In a real app, fetch the token from your own backend. Never ship an App Secret.
const val SERVER_URL = "https://api.devsquarelabs.com"
const val APP_ID = "YOUR_APP_ID"
const val ROOM_ID = "chat-test"
val TOKENS = mapOf(
"alice" to "ALICE_TOKEN",
"bob" to "BOB_TOKEN",
)4. Write the chat screen
Replace MainActivity.kt with this. It is the whole app: pick a user, connect, join a room, load recent messages, and send and receive new ones. It builds its views in code, so you can leave the generated layout file alone.
package com.example.chatdemo
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.rtcexpress.sdk.RTCExpress
import com.rtcexpress.sdk.RTCInitOptions
import com.rtcexpress.sdk.RoomMessage
import java.util.concurrent.Executors
class MainActivity : AppCompatActivity(), RTCExpress.Listener {
// The SDK does network work, so call it from a background thread.
private val worker = Executors.newSingleThreadExecutor()
private lateinit var rtc: RTCExpress
private lateinit var status: TextView
private lateinit var pickRow: LinearLayout
private lateinit var scroll: ScrollView
private lateinit var messages: LinearLayout
private lateinit var input: EditText
private lateinit var sendButton: Button
private var me: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
rtc = RTCExpress(applicationContext)
rtc.setListener(this)
status = TextView(this).apply { text = "Pick a user"; textSize = 18f }
pickRow = LinearLayout(this).apply {
addView(Button(context).apply { text = "I am Alice"; setOnClickListener { connect("alice") } })
addView(Button(context).apply { text = "I am Bob"; setOnClickListener { connect("bob") } })
}
messages = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
scroll = ScrollView(this).apply { addView(messages) }
input = EditText(this).apply { hint = "Type a message"; isEnabled = false }
sendButton = Button(this).apply { text = "Send"; isEnabled = false; setOnClickListener { send() } }
val inputRow = LinearLayout(this).apply {
addView(input, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))
addView(sendButton)
}
setContentView(LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(32, 64, 32, 32)
addView(status)
addView(pickRow)
addView(scroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(inputRow)
})
}
private fun connect(user: String) {
me = user
pickRow.visibility = View.GONE
status.text = "Connecting..."
sdk {
rtc.init(RTCInitOptions(serverUrl = SERVER_URL, appId = APP_ID, userId = user, token = TOKENS.getValue(user)))
rtc.joinRoom(ROOM_ID)
}
}
private fun send() {
val text = input.text.toString().trim()
if (text.isEmpty()) return
input.text.clear()
sdk {
rtc.sendMessage(text)
// The server sends your message to everyone else in the room, so add it here yourself.
runOnUiThread { addMessage(me ?: "", text) }
}
}
// Adds a message at the bottom (index = -1) or at a given position.
private fun addMessage(from: String, text: String, index: Int = -1) {
val mine = from == me
val view = TextView(this).apply {
this.text = if (mine) text else "$from: $text"
textSize = 16f
setPadding(24, 12, 24, 12)
setBackgroundColor(if (mine) 0xFFC8EFE8.toInt() else 0xFFEEEEEE.toInt())
}
val params = LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply {
gravity = if (mine) Gravity.END else Gravity.START
setMargins(0, 8, 0, 8)
}
messages.addView(view, index, params)
if (index == -1) scroll.post { scroll.fullScroll(View.FOCUS_DOWN) }
}
// Runs an SDK call on the background thread and shows any error.
private fun sdk(block: () -> Unit) = worker.execute {
try {
block()
} catch (e: Exception) {
runOnUiThread { status.text = "Error: ${e.message}" }
}
}
// SDK events arrive on a background thread, so switch to the UI thread first.
override fun onRoomJoined(roomId: String, members: List<String>) {
runOnUiThread {
status.text = "Joined $roomId"
input.isEnabled = true
sendButton.isEnabled = true
}
// Load the last 50 messages. History is for room members, so read it after joining.
sdk {
val page = rtc.getMessageHistory(ROOM_ID)
runOnUiThread {
// Newest first from the server: inserting each at the top leaves the oldest first.
page.messages.forEach { addMessage(it.fromUserId, it.text, index = 0) }
}
}
}
// Messages from the other people in the room.
override fun onMessage(message: RoomMessage) = runOnUiThread {
addMessage(message.fromUserId, message.text)
}
override fun onError(message: String) = runOnUiThread {
status.text = "Error: $message"
}
override fun onDestroy() {
worker.execute { rtc.destroy() }
worker.shutdown()
super.onDestroy()
}
}How it works
- init connects with a short-lived user token, and joinRoom asks to join the room.
onRoomJoinedconfirms membership; only then can the user send or read history. - sendMessage sends text to the current room. The server stores it and delivers it to everyone else in the room, so the app adds your own message to the list itself.
- onMessage fires for each new message from someone else, with a
RoomMessageholdingfromUserId,textandsentAt. - getMessageHistory returns the latest 50 messages, newest first, and a
nextCursor. Pass it asbeforeto load older pages. It makes a network request, so it runs on the background executor. - Threads: SDK calls run on one background executor, and listener events switch to the UI thread with
runOnUiThread. destroy inonDestroycloses the connection.
5. Run it on two devices
Connect both devices and run the app on each from Android Studio, or build once and install on both:
./gradlew installDebug- On the first device press I am Alice, and on the second press I am Bob. Wait for Joined chat-test.
- Type a message on Alice's device and press Send. It appears on Bob's device straight away.
- Reply from Bob, then close and reopen the app on one device and pick the same user: the earlier messages load from history.
Troubleshooting
- Send button stays disabled: the app hasn't joined the room. Check the App ID and that the token is for room
chat-testand hasn't expired. - Messages don't arrive on the other device: both users must be in the same room, and the other app must be open and connected.
- "Error: Join the room first": history and sending only work after
onRoomJoined, as in the code above. - Gradle can't find rtcexpress-android: check that
mavenCentral()is in therepositoriesblock ofsettings.gradle.kts, then sync again. - Error that the message limit is reached: the project used its included messages. See pricing.
6. Before you ship
Replace Config.kt with a call to your own backend. Your server signs the user in, checks they may join the room (for example, a one-to-one chat between two users), and requests a short-lived token from POST https://api.devsquarelabs.com/v1/token with your App ID and App Secret. The App Secret stays on the server.
For a real chat screen, use a RecyclerView for long conversations, a stable room ID per conversation (for example dm_alice__bob), older pages with nextCursor, a "sending…" state while offline, and push notifications for messages that arrive while the app is closed (see the push notification setup guide).
Android chat questions
Do I need my own chat server or database?
No. RTCExpress hosts the real-time connection and stores message history. Your backend only issues tokens.
Can users call each other from the chat?
Yes. The same SDK makes voice and video calls in the same room: rtc.callUser("bob"). Follow the Android voice calling tutorial to add a call button.
Does it work with Jetpack Compose or Java?
Yes. The SDK has no UI of its own, so you can show messages in Compose or any view, and its classes can be called from Java.
How are messages counted?
Each message sent counts once, however many people are in the room. The Free trial includes 10,000 messages in total, Starter 100,000 a month and Pro 500,000 a month. See pricing.