ANDROID • KOTLIN • VIDEO CALLING
How to add video calling to an Android app (Kotlin)
Build a one-to-one video call in a native Android app with the RTCExpress video calling SDK from Maven Central. You will have two Android phones on a video call with full-screen remote video, a small self-view, mute, camera on/off, camera flip and hang up, and no WebRTC, TURN or media servers to run yourself.
plan_feature_denied; build the Android voice calling tutorial first, which works on Free. See pricing.1. What you need
- Android Studio with JDK 17.
- Two Android phones with cameras, Android 7.0 (API 24) or newer. Emulators work, but their virtual cameras show a test pattern.
- An RTCExpress project on the Pro plan. 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 VideoCallDemo with the package com.example.videocalldemo.
The SDK is on Maven Central as com.devsquarelabs:rtcexpress-android. New projects already list mavenCentral() in settings.gradle.kts. 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. The SDK's manifest already declares the internet, camera and microphone permissions, so you don't edit AndroidManifest.xml. Your app only asks the user at runtime, which the code below does.
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 video-test.
- User ID bob, room ID video-test.
Create Config.kt next to MainActivity.kt and paste in your App ID and both tokens:
package com.example.videocalldemo
// 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 = "video-test"
val TOKENS = mapOf(
"alice" to "ALICE_TOKEN",
"bob" to "BOB_TOKEN",
)4. Write the video call screen
Replace MainActivity.kt with this. It is the whole app: pick a user, connect, join a room, place or answer a video call, and see both cameras. It builds its views in code, so you can leave the generated layout file alone.
package com.example.videocalldemo
import android.Manifest
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.rtcexpress.sdk.CallInvite
import com.rtcexpress.sdk.CallStateUpdate
import com.rtcexpress.sdk.CallVideoView
import com.rtcexpress.sdk.RTCExpress
import com.rtcexpress.sdk.RTCInitOptions
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 buttons: LinearLayout
private var me: String? = null
private var pendingUser: String? = null
private var joined = false
private var incoming = false
private var inCall = false
private var muted = false
private var cameraOff = false
private val peer get() = if (me == "alice") "bob" else "alice"
private val askForCameraAndMic =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
val user = pendingUser ?: return@registerForActivityResult
if (result.values.all { it }) connect(user)
else status.text = "Allow camera and microphone access to make video calls"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
rtc = RTCExpress(applicationContext)
rtc.setListener(this)
status = TextView(this).apply { text = "Pick a user"; textSize = 18f }
buttons = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
// The other person fills the area; your own camera sits in the top corner.
val remoteVideo = CallVideoView(this)
val localVideo = CallVideoView(this).apply { local = true } // mirrored, drawn on top
val videoArea = FrameLayout(this).apply {
setBackgroundColor(0xFF111111.toInt())
addView(remoteVideo, FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT))
addView(localVideo, FrameLayout.LayoutParams(dp(110), dp(150), Gravity.TOP or Gravity.END).apply {
setMargins(dp(12), dp(12), dp(12), dp(12))
})
}
setContentView(LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(16), dp(32), dp(16), dp(16))
addView(status)
addView(videoArea, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(buttons)
})
render()
}
private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
private fun pickUser(user: String) {
pendingUser = user
askForCameraAndMic.launch(arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO))
}
private fun connect(user: String) {
me = user
status.text = "Connecting..."
render()
sdk {
rtc.init(
RTCInitOptions(
serverUrl = SERVER_URL,
appId = APP_ID,
userId = user,
token = TOKENS.getValue(user),
mediaMode = "p2p", // 1:1 video goes directly between the two phones
)
)
rtc.joinRoom(ROOM_ID)
}
}
// 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}" }
}
}
private fun render() {
buttons.removeAllViews()
fun button(label: String, onClick: () -> Unit) =
buttons.addView(Button(this).apply { text = label; setOnClickListener { onClick() } })
when {
me == null -> {
button("I am Alice") { pickUser("alice") }
button("I am Bob") { pickUser("bob") }
}
incoming -> {
button("Accept") { sdk { rtc.acceptCall() } }
button("Reject") { sdk { rtc.rejectCall() } }
}
inCall -> {
button(if (muted) "Unmute" else "Mute") {
muted = !muted
sdk { rtc.muteMicrophone(muted) }
render()
}
button(if (cameraOff) "Camera on" else "Camera off") {
cameraOff = !cameraOff
sdk { rtc.muteCamera(cameraOff) }
render()
}
button("Flip camera") { sdk { rtc.switchCamera() } }
button("End call") { sdk { rtc.endCall() } }
}
joined -> button("Video call $peer") { sdk { rtc.callUser(peer, video = true) } }
}
}
// SDK events arrive on a background thread, so switch to the UI thread first.
override fun onRoomJoined(roomId: String, members: List<String>) = runOnUiThread {
joined = true
status.text = "Joined $roomId"
render()
}
override fun onCallInvite(invite: CallInvite) = runOnUiThread {
incoming = true
status.text = "Incoming ${invite.callType} call from ${invite.fromUserId}"
render()
}
override fun onCallState(update: CallStateUpdate) = runOnUiThread {
status.text = "Call ${update.state}"
inCall = update.state in setOf("ringing", "connecting", "connected")
if (update.state != "ringing") incoming = false
if (!inCall) {
muted = false
cameraOff = false
}
render()
}
override fun onError(message: String) = runOnUiThread {
status.text = "Error: $message"
}
override fun onDestroy() {
worker.execute { rtc.destroy() }
worker.shutdown()
super.onDestroy()
}
}How it works
- CallVideoView is the SDK's video view. A plain
CallVideoViewshows the other person; withlocal = trueit shows your own camera, mirrored and drawn on top. The views can stay on screen all the time: the SDK attaches the cameras when the call connects and clears them when it ends. - init connects with a short-lived user token.
mediaMode = "p2p"sends video directly between the two phones, through a hosted TURN relay when a direct path isn't possible. - joinRoom asks to join. Membership is confirmed by
onRoomJoined, so the call button only appears after it fires. - callUser(peer, video = true) rings the other user with a video call. On their phone,
onCallInvitefires withcallTypevideo, and they can acceptCall or rejectCall. - muteCamera, switchCamera, muteMicrophone and endCall drive the in-call buttons.
- Threads: SDK calls run on one background executor, and listener events switch to the UI thread with
runOnUiThread. destroy inonDestroyends any call and closes the connection.
5. Run it on two phones
Connect both phones and run the app on each from Android Studio, or build once and install on both:
./gradlew installDebug- On the first phone press I am Alice, and on the second press I am Bob. Allow camera and microphone access and wait for Joined video-test.
- On Alice's phone, press Video call bob.
- On Bob's phone, press Accept.
- When the status shows Call connected, each phone shows the other person and its own camera in the corner. Try Camera off, Flip camera, Mute and End call.
Two phones next to each other will echo; use headphones, or move apart.
Troubleshooting
- Error
plan_feature_deniedwhen calling: video needs the Pro plan on this project. Check Billing in the console. - Gradle can't find rtcexpress-android: check that
mavenCentral()is in therepositoriesblock ofsettings.gradle.kts, then sync again. - Build fails with a Java or JVM target error: set Java 17 in
compileOptionsandjvmTarget = "17"as in step 2. - Call connects but the video area is black: check that camera permission was allowed in Android settings and that no other app is using the camera.
- Call button never appears: both tokens must be for the same room,
video-test, and must not be expired. - No incoming call: the user IDs in the tokens must be exactly
aliceandbob, and both phones must be connected.
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, 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.
Then test across Wi-Fi and mobile data, with denied permissions, a rejected call, an expired token, a rotated phone and an app in the background. During a call the SDK shows an "Ongoing call" notification so the call keeps working while the user is in another app. Ringing a phone while the app is closed needs push notifications; see setIncomingCallNotifier in the Android SDK guide and the push notification setup guide.
Android video calling questions
Do I need my own WebRTC, TURN or media server?
No. RTCExpress hosts signaling, STUN, TURN relays and media servers. The Android SDK connects to them with the token your backend issues.
Does it work with Jetpack Compose?
Yes. CallVideoView is a regular Android view, so you can place it in Compose with AndroidView { CallVideoView(it) }. This tutorial uses classic views to keep the code in one file.
How are video minutes counted?
In participant minutes: a two-person video call lasting ten minutes uses twenty. Pro includes 10,000 video minutes and 50,000 voice minutes a month. See pricing.
Can I do group video calls?
Yes. joinVideoRoom() joins group video in the current room, and setting userId on a CallVideoView shows one person's camera per tile. See the Android SDK guide.