Retain call service startup owners before IPC effects and isolate callback failures

This commit is contained in:
evgeny committed 2026-10-29 13:34:23 +01:00
1 parent 74e4bcfadb
commit dabb7d3b24
1 file changed
+112 -22
@@ -14,6 +14,8 @@ import android.content.pm.ServiceInfo
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.os.SystemClock
import androidx.core.app.NotificationCompat
@@ -22,6 +24,8 @@ import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import com.utun.chat.ChatApplication
import com.utun.chat.MainActivity
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Deferred
/**
* Владелец аудиодвижка и PARTIAL_WAKE_LOCK на время исходящего/принятого звонка.
@@ -35,11 +39,37 @@ class CallService : Service() {
private const val NOTIFICATION_ID = 1002
private const val EXTRA_ID = "call_id"
private const val ACTION_END = "com.utun.chat.action.END_CALL"
@Volatile private var pendingCleanup: CallService? = null // Сильная ссылка до подтверждённой очистки, включая onDestroy.
val pendingRelease: Deferred<Unit>? get() = pendingCleanup?.released
fun cleanupPending(): Boolean = pendingCleanup != null
/** На main повторить незавершённую очистку. Ошибка запрещает заменять владельца или останавливать ядро. */
fun requireReleased() {
checkMain()
val previous = pendingCleanup ?: return
check(previous.shutdown().isCompleted) {
val message = "Call service cleanup still pending id=${previous.callId}"
LogManager.addLog("ERROR", "CallService", message)
message
}
}
fun start(context: Context, callId: Long) {
checkMain()
requireReleased()
require(callId != 0L) {
LogManager.addLog("ERROR", "CallService", "service request rejected: zero call ID")
"Call ID must be nonzero"
}
ContextCompat.startForegroundService(context,
Intent(context, CallService::class.java).putExtra(EXTRA_ID, callId))
}
private fun checkMain() = check(Looper.myLooper() == Looper.getMainLooper()) {
val message = "CallService requires main thread: caller=${Thread.currentThread().name}"
LogManager.addLog("ERROR", "CallService", message)
message
}
}
val audio = CallAudioEngine()
@@ -49,19 +79,38 @@ class CallService : Service() {
private var callId = 0L
private var wakeLock: PowerManager.WakeLock? = null
private var powerEventsRegistered = false
private var audioOwned = false
private var foregroundOwned = false
private var channelReady = false
private var stopping = false
private var destroyed = false
private var stopRequested = false
private var lastStartId = 0
private var released = CompletableDeferred<Unit>()
private var openIntent: PendingIntent? = null
private var endIntent: PendingIntent? = null
private val main = Handler(Looper.getMainLooper())
private var retryDelayMs = 250L
private val retryCleanup = Runnable { shutdown() }
private val powerEvents = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
LogManager.addLog("INFO", "CallService",
"power event=${intent.action} id=$callId interactive=${pm.isInteractive} " +
if (stopping || destroyed || !powerEventsRegistered) return
try {
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
LogManager.addLog("INFO", "CallService", "power event=${intent.action} id=$callId interactive=${pm.isInteractive} " +
"idle=${pm.isDeviceIdleMode} save=${pm.isPowerSaveMode} lock=${wakeLock?.isHeld} ${audio.diagnostics}")
} catch (e: Exception) {
LogManager.addLog("ERROR", "CallService", "power diagnostics failed action=${intent.action} id=$callId: $e")
}
}
}
override fun onCreate() {
checkMain()
super.onCreate()
createChannel()
audio.onFailure = { id, detail -> CallController.audioFailed(id, detail) }
try { createChannel() } catch (e: Exception) {
LogManager.addLog("ERROR", "CallService", "channel creation failed; will retry at start: $e")
}
LogManager.addLog("INFO", "CallService", "created")
}
@@ -74,35 +123,60 @@ class CallService : Service() {
enableVibration(false)
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
})
val channel = manager.getNotificationChannel(CHANNEL)
LogManager.addLog("INFO", "CallService",
"notification channel=$CHANNEL enabled=${manager.areNotificationsEnabled()} " +
channelReady = true
try {
val channel = manager.getNotificationChannel(CHANNEL)
LogManager.addLog("INFO", "CallService", "notification channel=$CHANNEL enabled=${manager.areNotificationsEnabled()} " +
"importance=${channel?.importance} lockscreenVisibility=${channel?.lockscreenVisibility}")
} catch (e: Exception) {
LogManager.addLog("WARN", "CallService", "channel diagnostics unavailable channel=$CHANNEL: $e")
}
}
fun refreshLanguage() { createChannel(); updateNotification() }
fun refreshLanguage() {
checkMain()
if (stopping || destroyed) return
try { createChannel(); updateNotification() } catch (e: Exception) {
LogManager.addLog("ERROR", "CallService", "notification language refresh failed id=$callId: $e")
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
checkMain()
lastStartId = startId
val id = intent?.getLongExtra(EXTRA_ID, 0L) ?: 0L
if (intent?.action == ACTION_END) {
CallController.end(id)
if (id == 0L || id != callId || stopping || destroyed || !CallController.wantsService(id)) {
LogManager.addLog("WARN", "CallService", "stale END ignored id=$id owned=$callId stopping=$stopping")
if (callId == 0L) shutdown()
} else try { CallController.end(id) } catch (e: Exception) {
LogManager.addLog("ERROR", "CallService", "END callback failed id=$id: $e")
shutdown()
}
return START_NOT_STICKY
}
if (!CallController.wantsService(id)) {
if (destroyed || !CallController.wantsService(id)) {
LogManager.addLog("WARN", "CallService", "stale start id=$id owned=$callId")
if (callId == 0L) {
if (!destroyed && callId == 0L) {
// Даже отменённый startForegroundService должен завершить foreground-handshake.
try {
if (!channelReady) createChannel()
promote(false)
} catch (e: Exception) {
LogManager.addLog("ERROR", "CallService", "cancelled foreground handshake failed id=$id: ${e.message}")
} finally {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf(startId)
shutdown()
}
}
return START_NOT_STICKY
}
if (stopping && !released.isCompleted) {
LogManager.addLog("ERROR", "CallService", "start blocked by pending cleanup id=$id owned=$callId")
try { CallController.audioFailed(id, "previous service cleanup pending") } catch (e: Exception) {
LogManager.addLog("ERROR", "CallService", "cleanup refusal callback failed id=$id: $e")
}
return START_NOT_STICKY
}
if (callId == id) return START_NOT_STICKY
if (callId != 0L) {
LogManager.addLog("ERROR", "CallService", "start conflicts id=$id owned=$callId")
@@ -110,12 +184,23 @@ class CallService : Service() {
return START_NOT_STICKY
}
callId = id
try {
promote(true)
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "utun:ongoing_call").apply {
setReferenceCounted(false)
stopping = false; stopRequested = false
if (released.isCompleted) released = CompletableDeferred()
audio.onFailure = { failedId, detail ->
if (failedId == callId && !stopping && !destroyed) try { CallController.audioFailed(failedId, detail) } catch (e: Exception) {
LogManager.addLog("ERROR", "CallService", "audio failure callback failed id=$failedId: $e")
shutdown()
}
}
var operation = "channel"
try {
if (!channelReady) createChannel()
operation = "foreground"
promote(true)
operation = "wake lock"
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "utun:ongoing_call")
wakeLock!!.setReferenceCounted(false)
wakeLock!!.acquire()
LogManager.addLog("INFO", "CallService",
"foreground phoneCall|microphone; CPU lock acquired id=$id held=${wakeLock?.isHeld}")
@@ -125,13 +210,17 @@ class CallService : Service() {
addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
}
ContextCompat.registerReceiver(this, powerEvents, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
operation = "power receiver"
powerEventsRegistered = true
ContextCompat.registerReceiver(this, powerEvents, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
operation = "ready callback"
if (!CallController.serviceReady(id, this)) shutdown()
} catch (e: Exception) {
LogManager.addLog("ERROR", "CallService", "start failed id=$id: ${e.message}")
CallController.audioFailed(id, "foreground/wake lock failed: ${e.message}")
LogManager.addLog("ERROR", "CallService", "start failed operation=$operation id=$id: $e")
shutdown()
try { CallController.audioFailed(id, "$operation failed: $e") } catch (callback: Exception) {
LogManager.addLog("ERROR", "CallService", "startup failure callback failed id=$id: $callback")
}
}
return START_NOT_STICKY
}
@@ -143,6 +232,7 @@ class CallService : Service() {
ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL or micType or
(if (cameraForeground && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA else 0)
} else 0
foregroundOwned = true // startForeground может отказать после эффекта IPC.
ServiceCompat.startForeground(this, NOTIFICATION_ID, notification(), types)
LogManager.addLog("INFO", "CallService", "foreground notification id=$callId phase=${CallController.state.value?.phase}")
}