fix(calls): Bildschirmübertragung ohne Absturz, Lautsprecher, Mikrofon im Hintergrund, zurück in den Anruf

Bernds Anruftest Handy↔PC (2026-10-07):
- Teilen am Handy: App "verkleinerte sich", Anruf danach weg. Ursache:
  Android 14+ verlangt vor MediaProjection einen Vordergrunddienst vom Typ
  mediaProjection; flutter_webrtc startet keinen, der Manifest-Eintrag
  verwies auf eine nicht mehr existierende Klasse. Neu: CallService
  (microphone|mediaProjection) + CallForeground: Zustimmung → Dienst
  (wartet auf echten startForeground) → Mitschnitt. Emulator-Test (Android
  16): mit Fix 1080x2400@30 läuft; Gegenprobe ohne Dienst wirft genau
  'Media projections require a foreground service ...'.
- Dienst läuft während jedes Anrufs: Mikrofon bleibt im Hintergrund aktiv,
  Benachrichtigung "Anruf läuft" führt zurück. Mikrofon-Typ nur mit
  Berechtigung, sonst schmalere Variante statt Dienst-Abbruch.
- Handy hörte nichts: SDK schaltet Sprachanrufe auf die Hörmuschel. Jetzt
  Lautsprecher als Standard (wie Discord) + Umschalter in der Anrufleiste.
- LiveKit-Teilen am Handy öffnete den PC-Quellen-Auswähler → System-Dialog.
- Im offenen Chat (Handy) Leiste "Anruf läuft · Zurück".
- Einstellungen → Sprache & Video: Mikrofontest mit Pegel (PC-Diagnose:
  das Standardgerät lieferte nur Stille – Voicemeeter/virtuelle Geräte).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Bernd Steckmeister
2026-10-08 00:01:29 +02:00
co-authored by Claude Opus 5.5
parent c817de924a
commit 441cc6ef54
18 changed files with 750 additions and 3 deletions
+7 -2
View File
@@ -9,6 +9,7 @@
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
@@ -26,11 +27,15 @@
android:allowBackup="false"
android:fullBackupContent="false"
android:dataExtractionRules="@xml/data_extraction_rules">
<!-- Laufender Anruf: hält das Mikrofon im Hintergrund am Leben und
ist Pflicht für Bildschirmübertragung ab Android 14 (CallService.kt).
Der frühere Eintrag com.cloudwebrtc...FlutterForegroundService
verwies auf eine Klasse, die flutter_webrtc 1.x nicht mehr hat. -->
<service
android:name="com.cloudwebrtc.webrtc.FlutterForegroundService"
android:name=".CallService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="mediaProjection" />
android:foregroundServiceType="microphone|mediaProjection" />
<activity
android:name=".MainActivity"
android:exported="true"
@@ -0,0 +1,143 @@
package chat.pyramid.pyramid
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.Manifest
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
/**
* Vordergrunddienst für laufende Anrufe (1:1 und Sprachkanäle).
*
* Warum: Android schaltet das Mikrofon einer App im Hintergrund stumm, und
* seit Android 14 stürzt jede Bildschirmübertragung ab, wenn vorher kein
* Dienst vom Typ „mediaProjection“ läuft (flutter_webrtc startet keinen).
* Genau das war Bernds Fehlerbild 2026-10-07: Teilen gestartet → App weg →
* beim Öffnen kein Anruf mehr.
*
* Typen: immer „microphone“ (ab Android 11), bei laufender Übertragung
* zusätzlich „mediaProjection“. Der Dienst darf mit mediaProjection erst
* NACH der Zustimmung des Nutzers gestartet werden – das stellt die
* Dart-Seite sicher (lib/core/call_foreground.dart).
*/
class CallService : Service() {
companion object {
private const val TAG = "PYRAMID-CALL"
private const val CHANNEL_ID = "pyramid_call"
private const val NOTIF_ID = 7301
private const val EXTRA_TITLE = "title"
private const val EXTRA_SCREEN = "screen"
// Wer auf den tatsächlichen startForeground wartet (Hauptthread).
// Die Bildschirmübertragung darf erst danach beginnen.
private val waiters = mutableListOf<(Boolean) -> Unit>()
fun whenStarted(callback: (Boolean) -> Unit) {
waiters.add(callback)
}
private fun notifyWaiters(ok: Boolean) {
val list = waiters.toList()
waiters.clear()
list.forEach { it(ok) }
}
fun start(ctx: Context, title: String, screen: Boolean) {
val intent = Intent(ctx, CallService::class.java)
.putExtra(EXTRA_TITLE, title)
.putExtra(EXTRA_SCREEN, screen)
ContextCompat.startForegroundService(ctx, intent)
}
fun stop(ctx: Context) {
ctx.stopService(Intent(ctx, CallService::class.java))
}
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val title = intent?.getStringExtra(EXTRA_TITLE) ?: "Pyramid"
val screen = intent?.getBooleanExtra(EXTRA_SCREEN, false) ?: false
ensureChannel()
val launch = packageManager.getLaunchIntentForPackage(packageName)?.apply {
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
}
val open = launch?.let {
PendingIntent.getActivity(
this, 0, it,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
}
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(if (screen) "Bildschirm wird übertragen" else "Anruf läuft")
.setContentText("$title – tippen, um zurückzukehren")
.setOngoing(true)
.setOnlyAlertOnce(true)
.setSilent(true)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setContentIntent(open)
.build()
// Typ „microphone“ nur mit Mikrofon-Berechtigung (sonst verweigert
// Android den GANZEN Dienst – auch den für die Übertragung).
val micAllowed = ContextCompat.checkSelfPermission(
this, Manifest.permission.RECORD_AUDIO
) == PackageManager.PERMISSION_GRANTED
val candidates = mutableListOf<Int>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val mic = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
val proj = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
if (screen) {
if (micAllowed) candidates.add(mic or proj)
candidates.add(proj)
} else if (micAllowed) {
candidates.add(mic)
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
candidates.add(if (screen) ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION else 0)
} else {
candidates.add(-1) // ohne Typ
}
var ok = false
for (type in candidates) {
try {
if (type == -1) startForeground(NOTIF_ID, notification)
else startForeground(NOTIF_ID, notification, type)
ok = true
break
} catch (e: Exception) {
// Nächste, schmalere Variante versuchen – lieber ohne Dienst
// weiter als die App abstürzen zu lassen.
Log.e(TAG, "startForeground fehlgeschlagen (screen=$screen, type=$type): ${e.message}")
}
}
if (!ok) stopSelf()
notifyWaiters(ok)
return START_NOT_STICKY
}
private fun ensureChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val nm = getSystemService(NotificationManager::class.java)
if (nm.getNotificationChannel(CHANNEL_ID) != null) return
nm.createNotificationChannel(
NotificationChannel(CHANNEL_ID, "Laufende Anrufe", NotificationManager.IMPORTANCE_LOW).apply {
description = "Zeigt an, dass ein Anruf oder eine Bildschirmübertragung läuft."
setShowBadge(false)
}
)
}
}
@@ -97,6 +97,39 @@ class MainActivity : FlutterActivity() {
super.configureFlutterEngine(flutterEngine)
// Cache so ReplyReceiver can call back into Dart without starting a new engine.
FlutterEngineCache.getInstance().put("main", flutterEngine)
// Anruf-Vordergrunddienst (lib/core/call_foreground.dart ↔ CallService.kt).
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "chat.pyramid.pyramid/call")
.setMethodCallHandler { call, result ->
when (call.method) {
"start" -> {
// Erst antworten, wenn der Dienst wirklich im Vordergrund
// läuft (oder nach 3 s aufgeben) – eine Übertragung vor
// dem startForeground würde die App abstürzen lassen.
val done = java.util.concurrent.atomic.AtomicBoolean(false)
val reply = { ok: Boolean ->
if (done.compareAndSet(false, true)) result.success(ok)
}
try {
CallService.whenStarted(reply)
CallService.start(
this,
call.argument<String>("title") ?: "Pyramid",
call.argument<Boolean>("screen") ?: false,
)
android.os.Handler(mainLooper).postDelayed({ reply(false) }, 3000)
} catch (e: Exception) {
// z. B. Start aus dem Hintergrund verboten (Android 12+).
Log.e("PYRAMID-CALL", "CallService-Start abgelehnt: ${e.message}")
reply(false)
}
}
"stop" -> {
CallService.stop(this)
result.success(true)
}
else -> result.notImplemented()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel)
.setMethodCallHandler { call, result ->
when (call.method) {