Kotlin

Initialisation de la session

1. Initialisation de la session

Demandez les autorisations pour la caméra et le microphone, puis connectez-vous à la session Vonage :

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

2. Lors de la session connectée, demander une capture d'écran

Une fois la connexion établie, la boîte de dialogue de capture d'écran du système s'ouvre :

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

3. Lorsque l'utilisateur en donne l'autorisation, démarrer la capture

Lorsque l'utilisateur partage l'écran via le dialogue :

  1. Démarrer le service d'avant-plan - Obligation avant l'utilisation MediaProjection.
  2. Obtenir MediaProjection - A partir de l'intention de résultat.
  3. Créer le capteur - ScreenSharingCapturer(context, mediaProjection).
  4. Créer l'éditeur - Utilisez le capteur et réglez le type de vidéo sur PublisherKitVideoTypeScreen.
  5. Publier - session.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 optimise l'encodage pour le contenu de l'écran (par exemple, le texte et l'interface utilisateur).

Étape 5 : Service d'action extérieure

Les ScreenSharingService affiche une notification et appelle startForeground() avec ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION. Cela doit se faire avant vous appelez getMediaProjection().

ScreenSharingManager se lie à ce service et expose startForeground(). L'initialiser dans onCreate et le délier dans onDestroy.