LiveKit Android SDK

repository·main·Indexed 43 days ago

https://github.com/livekit/client-sdk-android

An Android Kotlin SDK (v2.28.2) for integrating real-time video, audio, and data features. It enables developers to build video calls, live streaming, and multi-modal AI applications by connecting to LiveKit Cloud or self-hosted servers. Includes support for CameraX for advanced camera controls, track processors for virtual backgrounds, and SurfaceViewRenderer for video playback.

Tokens
12.7K
Snippets
31
Records
61
Agent score
55%

What's inside LiveKit

  1. Overview of Sample-app-basic

    main

    The sample-app-basic is a quickstart application designed to demonstrate the fundamental capabilities of the LiveKit Android SDK. It serves as a minimal implementation for the following core tasks:

    1. Connecting to a room: Establishing a connection to a LiveKit server room.
    2. Publishing media: Sending your device's local audio and video tracks to the room.
    3. Subscribing to video: Displaying the video track of a single remote participant.

    Note: This specific sample is intentionally limited to handling the video of only one remote participant. For production-grade video conferencing features, refer to the more comprehensive sample applications within the repository.

  2. Manage LiveKit Room connections with io.livekit.android.room

    main
    The io.livekit.android.room package contains the Room class, which is the primary controller for managing a LiveKit connection. The Room class manages the lifecycle of the connection and exposes listeners that allow you to react to room events (such as participant joining/leaving or track publishing).
  3. Observe properties using @FlowObservable

    main

    Properties marked with @FlowObservable can be observed as Kotlin Flows. This allows you to react to state changes (like active speakers) in a coroutine scope.

    coroutineScope.launch {
        room::activeSpeakers.flow.collectLatest { speakersList ->
            /* Handle changes to active speakers */
        }
    }
  4. Configure TokenSource for connecting to a room

    main

    To connect to a LiveKit room, you need a server URL and a participant token. The TokenSource factory methods provide different ways to obtain these credentials:

    1. Literal: Use pregenerated credentials (e.g., from LiveKit CLI or Cloud).
    2. Development Token Server: Use a token server ID for prototyping (insecure, do not use in production).
    3. Endpoint: Point to a production token endpoint URL with optional authentication headers.
    4. Custom: Provide a custom fetch function for fully controlled logic.

    You can wrap any TokenSource with .cached() to avoid refetching valid credentials.

    // 1. Literal
    val source = TokenSource.fromLiteral("wss://your.livekit.host", "your_token")
    
    // 2. Development Token Server
    val source = TokenSource.fromDevelopmentTokenServer("your token server id")
    
    // 3. Endpoint
    val source = TokenSource.fromEndpoint(
        url = "https://your.token-server/api/token",
        headers = mapOf("Authorization" to "Bearer <auth>"),
    )
    
    // 4. Custom
    val source = TokenSource.fromCustom { options ->
        Result.success(TokenSourceResponse(serverUrl = "...", participantToken = "..."))
    }
    
    // Caching a source
    val cachedSource = source.cached()
    
    // Fetching and connecting
    val response = cachedSource.fetch(
        TokenRequestOptions(roomName = "room", participantName = "participant"),
    ).getOrThrow()
    
    room.connect(response.serverUrl, response.participantToken)
  5. Understand SDK size and distribution

    main

    The SDK includes native WebRTC libraries for multiple architectures (arm64-v8a, armeabi-v7a, x86, x86_64). While the total AAR/APK size may appear large, using Android App Bundles for Google Play distribution ensures that users only download the native libraries specific to their device architecture, significantly reducing the download size.

    To verify the size for a specific architecture:

    1. Use bundletool to generate device-specific APKs from an App Bundle.
    2. Use the Android Studio APK Analyzer to inspect the /lib/<arch>/ folders.
  6. Install the CameraX support library

    main

    To use CameraX features (like custom zoom, torch control, and high-quality picture taking) with the LiveKit Android SDK, add the livekit-android-camerax dependency to your build.gradle file. Replace <current livekit sdk release> with the latest version from the releases page.

    // build.gradle
    ...
    dependencies {
      implementation "io.livekit:livekit-android-camerax:<current livekit sdk release>"
    }
  7. Render subscribed video tracks

    main

    LiveKit uses SurfaceViewRenderer to render video tracks. To display a remote video track, you must listen for RoomEvent.TrackSubscribed events, check if the track is a VideoTrack, and then call addRenderer on that track.

    // Setup the renderer in onCreate
    room.initVideoRenderer(findViewById<SurfaceViewRenderer>(R.id.renderer))
    
    // Listen for subscribed tracks
    launch {
        room.events.collect { event ->
            when (event) {
                is RoomEvent.TrackSubscribed -> onTrackSubscribed(event)
                else -> {}
            }
        }
    }
    
    // Attach the track to the renderer
    private fun onTrackSubscribed(event: RoomEvent.TrackSubscribed) {
        val track = event.track
        if (track is VideoTrack) {
            track.addRenderer(findViewById<SurfaceViewRenderer>(R.id.renderer))
        }
    }
  8. Install the LiveKit Android SDK

    main

    LiveKit for Android is available via Maven Central. You must add JitPack to your repository list in settings.gradle to resolve dependencies.

    Note: This is v2 of the SDK. If you are migrating from v1.x, refer to the official migration guide at https://docs.livekit.io/recipes/migrate-from-v1/.

    dependencyResolutionManagement {
        repositories {
            google()
            mavenCentral()
            //...
            maven { url 'https://jitpack.io' }
        }
    }
    // ...
    dependencies {
      def livekit_version = "2.28.2"
    
      // Core SDK
      implementation "io.livekit:livekit-android:$livekit_version"
    
      // CameraX support (pinch to zoom, torch control, etc.)
      implementation "io.livekit:livekit-android-camerax:$livekit_version"
    
      // Track processors (e.g., virtual background)
      implementation "io.livekit:livekit-android-track-processors:$livekit_version"
    }