Kotlin

Initializing Session

1. Perform session initialisation

Request camera/mic permissions, then connect to the Vonage session:

private fun initializeSession(appId: String, sessionId: String, token: String) {
    session = Session.Builder(this, appId, sessionId).build().apply {
        setSessionListener(sessionListener)
        connect(token)
    }
}

2. On Session connected request screen capture

When connected, launch the system screen capture dialog:

private fun requestScreenCapturePermission() {
    mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
    mediaProjectionManager?.createScreenCaptureIntent()?.let { intent ->
        screenCaptureLauncher.launch(intent)
    }
}

3. When user grants permission, start capture

When the user shares screen via the dialog:

  1. Start the foreground service – Required before using MediaProjection.
  2. Get MediaProjection – From the result intent.
  3. Create the capturerScreenSharingCapturer(context, mediaProjection).
  4. Build the publisher – Use the capturer and set video type to PublisherKitVideoTypeScreen.
  5. Publishsession.publish(publisher).
private fun startScreenCapture(resultCode: Int, data: Intent) {
    screenSharingManager.startForeground()

    Handler(Looper.getMainLooper()).postDelayed({
        val projectionManager = mediaProjectionManager ?: return@postDelayed
        mediaProjection = projectionManager.getMediaProjection(resultCode, data)
        val capturer = ScreenSharingCapturer(this, mediaProjection!!)

        publisher = Publisher.Builder(this)
            .capturer(capturer)
            .build()
            .apply {
                setPublisherListener(publisherListener)
                setPublisherVideoType(PublisherKit.PublisherKitVideoType.PublisherKitVideoTypeScreen)
                setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL)
            }

        publisherView = publisher?.view
        session?.publish(publisher)
    }, 100)
}

PublisherKitVideoTypeScreen optimizes encoding for screen content (e.g., text and UI).

Step 5: Foreground Service

The ScreenSharingService shows a notification and calls startForeground() with ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION. This must happen before you call getMediaProjection().

ScreenSharingManager binds to this service and exposes startForeground(). Initialize it in onCreate and unbind in onDestroy.