Recover SIM observers without losing healthy subscription state

This commit is contained in:
evgeny committed 2026-10-27 21:49:15 +01:00
1 parent 30e132b729
commit 1ddb9fd272
2 files changed
+423 -60

No files matched your search

@@ -16,37 +16,50 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
/** Живое состояние SIM-звонков. Номера не читаются; отсутствие разрешения означает UNKNOWN.
/** Живое состояние SIM без чтения номеров: BUSY, если занята хотя бы одна SIM; IDLE — только когда все известны и свободны.
* Нет SIM/разрешения или ещё не пришёл начальный callback — UNKNOWN. Три младших бита policy включают наблюдение,
* запреты обычных/радиозвонков передаются независимо от READ_PHONE_STATE. init/refresh и состояния принадлежат main.
* У каждой SIM свой callback: TelephonyCallback с 31, PhoneStateListener на 26..30; начальное значение приходит тем же путём.
* refresh сохраняет здоровые регистрации; временные отказы повторяются через 1..30с, отключение отменяет повтор.
* При снятии наблюдения старые callbacks теряют право публикации даже при ошибке ОС.
* JNI принимает копию асинхронно; SERVICE_STARTED вызывает refresh и повторяет состояние для нового ядра. */
@Suppress("DEPRECATION")
object PhoneStateMonitor {
private val main = Handler(Looper.getMainLooper())
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private data class Watch(val manager: TelephonyManager, val callback: Any)
private val watches = mutableListOf<Watch>()
private val states = mutableMapOf<Int, Int>()
private class Watch(val id: Int, val manager: TelephonyManager) {
var state = -1 // UNKNOWN до первого callback; это не Android CALL_STATE_IDLE (0).
val modern = Build.VERSION.SDK_INT >= 31
val callback: Any = if (modern) object : TelephonyCallback(), TelephonyCallback.CallStateListener {
override fun onCallStateChanged(state: Int) = changed(this@Watch, state)
} else object : PhoneStateListener() {
override fun onCallStateChanged(state: Int, phoneNumber: String?) = changed(this@Watch, state)
}
}
private class Subscriptions(val manager: SubscriptionManager) {
val callback = object : SubscriptionManager.OnSubscriptionsChangedListener() {
override fun onSubscriptionsChanged() { main.post { if (subscriptions === this@Subscriptions) refresh() } }
}
}
private val watches = mutableMapOf<Int, Watch>()
private var activeIds = emptySet<Int>()
private var subscriptions: Subscriptions? = null
private var enabled = false
private var policy = 0
private var generation = 0
private var lastState = -1
private var started = false
private var listeningSubscriptions = false
private val subscriptions = object : SubscriptionManager.OnSubscriptionsChangedListener() {
override fun onSubscriptionsChanged() { main.post {
if (enabled && granted()) try {
val ids = ChatApplication.instance.getSystemService(SubscriptionManager::class.java)
?.activeSubscriptionInfoList.orEmpty().map { it.subscriptionId }.toSet()
if (ids != states.keys) refresh()
} catch (e: Exception) { LogManager.addLog("WARN", "PhoneState", "Cannot read changed SIM subscriptions: $e"); publish(0) }
} }
}
private var retryDelay = 1_000L
private val retry = Runnable { refresh() }
fun granted(): Boolean = ContextCompat.checkSelfPermission(ChatApplication.instance, Manifest.permission.READ_PHONE_STATE) ==
PackageManager.PERMISSION_GRANTED
/** Подписаться на пять настроек приложения; повторный init на main не создаёт второй collector. */
fun init() {
checkMain()
if (started) return
started = true
LogManager.addLog("INFO", "PhoneState", "SIM monitor initialized")
val app = ChatApplication.instance
scope.launch {
app.configProvider.incomingCallOptions.collect { options ->
@@ -57,71 +70,110 @@ object PhoneStateMonitor {
}
}
/** Вызывается также после старта ядра и возврата из системных настроек. */
/** Сверить SIM/разрешение и повторно опубликовать состояние; main, в том числе после старта ядра/возврата из настроек. */
fun refresh() {
check(Looper.myLooper() == Looper.getMainLooper())
val app = ChatApplication.instance
val subManager = app.getSystemService(SubscriptionManager::class.java)
generation++
for (watch in watches) try {
if (Build.VERSION.SDK_INT >= 31) watch.manager.unregisterTelephonyCallback(watch.callback as TelephonyCallback)
else watch.manager.listen(watch.callback as PhoneStateListener, PhoneStateListener.LISTEN_NONE)
} catch (e: Exception) { LogManager.addLog("WARN", "PhoneState", "Cannot unregister phone observer: $e") }
watches.clear(); states.clear()
checkMain()
main.removeCallbacks(retry)
if (!enabled || !granted()) {
if (listeningSubscriptions) subManager?.removeOnSubscriptionsChangedListener(subscriptions)
listeningSubscriptions = false
clearWatches(); clearSubscriptions(); retryDelay = 1_000L
publish(0); return
}
val app = ChatApplication.instance
val subManager = app.getSystemService(SubscriptionManager::class.java)
val telephony = app.getSystemService(TelephonyManager::class.java)
if (telephony == null || subManager == null) {
LogManager.addLog("WARN", "PhoneState", "Telephony unavailable"); publish(0); return
clearWatches(); clearSubscriptions()
LogManager.addLog("WARN", "PhoneState", "Telephony unavailable phone=${telephony != null} subscriptions=${subManager != null}")
publish(0); return
}
val currentGeneration = generation
try {
if (!listeningSubscriptions) {
subManager.addOnSubscriptionsChangedListener(subscriptions)
listeningSubscriptions = true
if (subscriptions?.manager !== subManager) {
clearWatches(); clearSubscriptions()
val next = Subscriptions(subManager)
subscriptions = next
try {
if (Build.VERSION.SDK_INT >= 30) subManager.addOnSubscriptionsChangedListener(ContextCompat.getMainExecutor(app), next.callback)
else subManager.addOnSubscriptionsChangedListener(next.callback)
} catch (e: Exception) {
LogManager.addLog("ERROR", "PhoneState", "Cannot register SIM listener: $e")
clearSubscriptions(); scheduleRetry(); publish(0); return
}
val ids = subManager.activeSubscriptionInfoList.orEmpty().map { it.subscriptionId }
if (ids.isEmpty()) { publish(0); return }
for (id in ids) states[id] = -1
for (id in ids) {
val manager = telephony.createForSubscriptionId(id)
val callback: Any = if (Build.VERSION.SDK_INT >= 31) {
object : TelephonyCallback(), TelephonyCallback.CallStateListener {
override fun onCallStateChanged(state: Int) = changed(currentGeneration, id, state)
}.also { manager.registerTelephonyCallback(ContextCompat.getMainExecutor(app), it) }
} else {
object : PhoneStateListener() {
override fun onCallStateChanged(state: Int, phoneNumber: String?) = changed(currentGeneration, id, state)
}.also { manager.listen(it, PhoneStateListener.LISTEN_CALL_STATE) }
}
watches.add(Watch(manager, callback))
states[id] = if (Build.VERSION.SDK_INT >= 31) manager.callStateForSubscription else manager.callState
}
publishAggregate()
LogManager.addLog("INFO", "PhoneState", "SIM listener registered")
}
val ids = try {
subManager.activeSubscriptionInfoList.orEmpty().map { it.subscriptionId }.toSet()
} catch (e: Exception) {
generation++ // Поздние callbacks частично зарегистрированного набора не публикуют ложную свободу.
LogManager.addLog("ERROR", "PhoneState", "Cannot observe phone state: $e")
publish(0)
LogManager.addLog("ERROR", "PhoneState", "Cannot read SIM subscriptions: $e")
clearWatches(); scheduleRetry(); publish(0); return
}
if (ids != activeIds) LogManager.addLog("INFO", "PhoneState", "SIM subscriptions $activeIds -> $ids")
activeIds = ids
for (id in watches.keys.toList()) if (id !in ids) watches.remove(id)?.let(::removeWatch)
var failed = false
for (id in ids) if (id !in watches) {
try {
val watch = Watch(id, telephony.createForSubscriptionId(id))
watches[id] = watch
if (watch.modern) watch.manager.registerTelephonyCallback(ContextCompat.getMainExecutor(app), watch.callback as TelephonyCallback)
else watch.manager.listen(watch.callback as PhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)
LogManager.addLog("INFO", "PhoneState", "Phone observer registered SIM=$id api=${Build.VERSION.SDK_INT}")
} catch (e: Exception) {
watches.remove(id)?.let(::removeWatch)
failed = true
LogManager.addLog("ERROR", "PhoneState", "Cannot register phone observer SIM=$id: $e")
}
}
if (failed) scheduleRetry() else retryDelay = 1_000L
publishAggregate()
}
private fun changed(token: Int, id: Int, state: Int) {
if (token != generation || !enabled || !states.containsKey(id)) return
private fun removeWatch(watch: Watch) {
try {
if (watch.modern) watch.manager.unregisterTelephonyCallback(watch.callback as TelephonyCallback)
else watch.manager.listen(watch.callback as PhoneStateListener, PhoneStateListener.LISTEN_NONE)
} catch (e: Exception) { LogManager.addLog("WARN", "PhoneState", "Phone observer removal failed SIM=${watch.id}: $e") }
LogManager.addLog("DEBUG", "PhoneState", "Phone observer invalidated SIM=${watch.id}")
}
private fun clearWatches() {
val previous = watches.values.toList()
watches.clear(); activeIds = emptySet()
previous.forEach(::removeWatch)
}
private fun clearSubscriptions() {
val previous = subscriptions ?: return
subscriptions = null
try { previous.manager.removeOnSubscriptionsChangedListener(previous.callback) }
catch (e: Exception) { LogManager.addLog("WARN", "PhoneState", "SIM listener removal failed: $e") }
LogManager.addLog("DEBUG", "PhoneState", "SIM listener invalidated")
}
private fun scheduleRetry() {
LogManager.addLog("DEBUG", "PhoneState", "SIM observation retry in ${retryDelay}ms")
main.postDelayed(retry, retryDelay)
retryDelay = (retryDelay * 2).coerceAtMost(30_000L)
}
private fun changed(watch: Watch, state: Int) {
checkMain()
if (!enabled || watches[watch.id] !== watch) return
if (!granted()) { refresh(); return }
states[id] = state
watch.state = when (state) {
TelephonyManager.CALL_STATE_IDLE, TelephonyManager.CALL_STATE_RINGING, TelephonyManager.CALL_STATE_OFFHOOK -> state
else -> { LogManager.addLog("WARN", "PhoneState", "Invalid phone state SIM=${watch.id} state=$state"); -1 }
}
LogManager.addLog("DEBUG", "PhoneState", "Phone callback SIM=${watch.id} state=${watch.state}")
publishAggregate()
}
private fun publishAggregate() {
val busy = states.values.any { it == TelephonyManager.CALL_STATE_OFFHOOK || it == TelephonyManager.CALL_STATE_RINGING }
publish(if (busy) 2 else if (states.isNotEmpty() && states.values.all { it == TelephonyManager.CALL_STATE_IDLE }) 1 else 0)
val busy = watches.values.any { it.state == TelephonyManager.CALL_STATE_OFFHOOK || it.state == TelephonyManager.CALL_STATE_RINGING }
val idle = activeIds.isNotEmpty() && activeIds.all { watches[it]?.state == TelephonyManager.CALL_STATE_IDLE }
publish(if (busy) 2 else if (idle) 1 else 0)
}
private fun publish(state: Int) {
if (lastState != state) LogManager.addLog("INFO", "PhoneState", "State=$state enabled=$enabled subscriptions=${states.size}")
if (lastState != state) LogManager.addLog("INFO", "PhoneState", "State=$state enabled=$enabled subscriptions=${activeIds.size}")
lastState = state // Только для диагностики: повторный publish всё равно отправляет актуальное состояние.
if (!NativeLib.isReady()) {
LogManager.addLog("DEBUG", "PhoneState", "State deferred state=$state policy=$policy: core is not ready")
@@ -130,4 +182,12 @@ object PhoneStateMonitor {
if (!NativeLib.setPhoneState(state, policy))
LogManager.addLog("WARN", "PhoneState", "State not queued state=$state policy=$policy; next update/refresh will retry")
}
private fun checkMain() {
check(Looper.myLooper() === Looper.getMainLooper()) {
val message = "PhoneStateMonitor requires main thread: caller=${Thread.currentThread().name}"
LogManager.addLog("ERROR", "PhoneState", message)
message
}
}
}
@@ -0,0 +1,303 @@
package com.utun.chat.data
import android.content.Context
import android.os.Build
import android.os.Looper
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import com.utun.chat.ChatApplication
import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/** Настоящий singleton, Flow настроек и callbacks обеих Android API; каждый тест моделирует отдельный процесс приложения. */
@OptIn(ExperimentalCoroutinesApi::class)
class PhoneStateMonitorLifecycleTest {
private lateinit var context: Context
private lateinit var subscriptions: SubscriptionManager
private lateinit var telephony: TelephonyManager
private val loop get() = Looper.getMainLooper()
@Before fun prepare() {
assertSame(loop, Looper.myLooper())
Dispatchers.setMain(UnconfinedTestDispatcher())
Build.VERSION.SDK_INT = 36
context = Context()
subscriptions = requireNotNull(context.subscriptionManager)
telephony = requireNotNull(context.telephonyManager)
ChatApplication.instance = context
NativeLib.ready = true; NativeLib.acceptPhoneRequest = true
PhoneStateMonitor.init()
loop.dispatchAll()
NativeLib.phoneRequests.clear(); LogManager.entries.clear(); LogManager.console = true
}
@After fun release() {
NativeLib.ready = false
context.permissionGranted = false
subscriptions.failRemove = false
telephony.subscriptions.values.forEach { it.failRemove = false }
PhoneStateMonitor.refresh()
loop.dispatchAll()
// В приложении scope живёт до завершения процесса; в JVM отменяем только его collector между тестами.
val scope = PhoneStateMonitor::class.java.getDeclaredField("scope").apply { isAccessible = true }.get(null) as CoroutineScope
scope.coroutineContext.cancelChildren()
PhoneStateMonitor::class.java.getDeclaredField("started").apply { isAccessible = true }.setBoolean(null, false)
Dispatchers.resetMain()
}
private fun options(mask: Int, dispatch: Boolean = true) {
context.configProvider.incomingCallOptions.value = List(5) { mask and (1 shl it) != 0 }
if (dispatch) loop.dispatchAll()
}
private fun phone(id: Int = 10) = telephony.createForSubscriptionId(id)
private fun state(expected: Int, policy: Int = 1) = assertEquals(expected to policy, NativeLib.phoneRequests.lastOrNull())
private fun deliver(id: Int, state: Int, index: Int = phone(id).history.lastIndex) {
phone(id).deliver(index, state); loop.dispatchAll()
}
@Test fun initialStateComesFromCallbackAndBusyWinsAcrossSims() {
subscriptions.ids = listOf(10, 20)
phone(10).automaticInitial = false; phone(20).automaticInitial = false
options(1)
state(0)
deliver(10, TelephonyManager.CALL_STATE_IDLE); state(0)
deliver(20, TelephonyManager.CALL_STATE_RINGING); state(2)
deliver(20, TelephonyManager.CALL_STATE_IDLE); state(1)
deliver(10, TelephonyManager.CALL_STATE_OFFHOOK); state(2)
}
@Test fun minimumAndroidUsesLegacyListenerAndReceivesUpdates() {
Build.VERSION.SDK_INT = 26
options(1); state(1)
deliver(10, TelephonyManager.CALL_STATE_RINGING); state(2)
deliver(10, TelephonyManager.CALL_STATE_IDLE); state(1)
options(0)
assertTrue(phone().active.isEmpty())
}
@Test fun failedSynchronousSnapshotCannotDisableLiveCallback() {
phone().initialState = TelephonyManager.CALL_STATE_OFFHOOK
phone().failQuery = true
options(1)
state(2)
deliver(10, TelephonyManager.CALL_STATE_IDLE); state(1)
}
@Test fun missingPermissionPublishesUnknownAndKeepsPolicyBits() {
context.permissionGranted = false
options(25)
state(0, 25)
assertTrue(subscriptions.active.isEmpty())
assertEquals(0, phone().registerAttempts)
context.permissionGranted = true
PhoneStateMonitor.refresh(); loop.dispatchAll()
state(1, 25)
}
@Test fun blockOnlyPoliciesDoNotRequestPhoneObservers() {
for (mask in listOf(8, 16, 24)) {
options(mask); state(0, mask)
assertTrue(subscriptions.active.isEmpty())
assertEquals(0, phone().registerAttempts)
}
}
@Test fun eachPhonePolicyEnablesObservationIndependently() {
for (mask in listOf(1, 2, 4)) {
options(mask); state(1, mask)
assertEquals(1, phone().active.size)
options(0)
assertTrue(phone().active.isEmpty())
}
}
@Test fun invalidCallbackDoesNotPublishIdleAndIsLogged() {
options(1); state(1)
deliver(10, 99); state(0)
assertTrue(LogManager.entries.any { it.level == "WARN" && it.message.contains("Invalid phone state") })
deliver(10, TelephonyManager.CALL_STATE_IDLE); state(1)
}
@Test fun policyChangesReuseLiveObserverAndPreserveBusy() {
phone().initialState = TelephonyManager.CALL_STATE_OFFHOOK
options(1)
NativeLib.phoneRequests.clear()
options(31)
state(2, 31)
assertFalse(NativeLib.phoneRequests.any { it.first == 0 })
assertEquals(1, phone().registerAttempts)
assertEquals(1, subscriptions.addAttempts)
}
@Test fun refreshReplaysStateWithoutReplacingHealthyWatch() {
phone().initialState = TelephonyManager.CALL_STATE_OFFHOOK
options(1)
NativeLib.phoneRequests.clear()
PhoneStateMonitor.refresh(); loop.dispatchAll()
state(2)
assertEquals(1, phone().registerAttempts)
assertEquals(0, phone().removeAttempts)
}
@Test fun simReplacementIgnoresPreviousRegistration() {
phone().initialState = TelephonyManager.CALL_STATE_OFFHOOK
options(1)
subscriptions.ids = listOf(20)
subscriptions.deliver(); loop.dispatchAll(); state(1)
assertTrue(phone(10).active.isEmpty())
val count = NativeLib.phoneRequests.size
deliver(10, TelephonyManager.CALL_STATE_OFFHOOK, 0)
assertEquals(count, NativeLib.phoneRequests.size)
}
@Test fun partialRegistrationFailureKeepsHealthySimAndRetriesMissingSim() {
subscriptions.ids = listOf(10, 20)
phone(20).failRegister = true
options(1); state(0)
deliver(10, TelephonyManager.CALL_STATE_RINGING); state(2)
phone(20).failRegister = false
loop.advanceBy(30_000); state(2)
assertEquals(1, phone(10).registerAttempts)
deliver(10, TelephonyManager.CALL_STATE_IDLE); state(1)
}
@Test fun registrationRecoversWithoutSubscriptionChangeOrActivityResume() {
phone().failRegister = true
options(1); state(0)
assertTrue(LogManager.entries.any { it.level == "ERROR" && it.category == "PhoneState" })
phone().failRegister = false
loop.advanceBy(30_000)
state(1)
assertEquals(1, phone().active.size)
}
@Test fun subscriptionListFailureRetriesWithoutExternalEvent() {
subscriptions.failQuery = true
options(1); state(0)
subscriptions.failQuery = false
loop.advanceBy(30_000)
state(1)
}
@Test fun subscriptionListenerFailureRetriesWithoutExternalEvent() {
subscriptions.failAdd = true
options(1); state(0)
subscriptions.failAdd = false
loop.advanceBy(30_000)
state(1)
assertEquals(1, subscriptions.active.size)
}
@Test fun subscriptionCallbackAfterPermissionRevocationStopsObservers() {
phone().initialState = TelephonyManager.CALL_STATE_OFFHOOK
options(1); state(2)
context.permissionGranted = false
subscriptions.deliver(); loop.dispatchAll()
state(0)
assertTrue(subscriptions.active.isEmpty() && phone().active.isEmpty())
}
@Test fun subscriptionRemovalFailureIsLoggedWithoutEscapingRefresh() {
options(1)
context.permissionGranted = false
subscriptions.failRemove = true
PhoneStateMonitor.refresh()
state(0)
assertTrue(LogManager.entries.any { it.level == "WARN" && it.message.contains("remov", ignoreCase = true) })
val count = NativeLib.phoneRequests.size
subscriptions.deliver(0); loop.dispatchAll()
assertEquals(count, NativeLib.phoneRequests.size)
}
@Test fun removalUsesManagerThatOwnsSubscriptionListener() {
options(1)
val replacement = SubscriptionManager()
context.subscriptionManager = replacement
context.permissionGranted = false
PhoneStateMonitor.refresh()
assertEquals(1, subscriptions.removeAttempts)
assertEquals(0, replacement.removeAttempts)
assertTrue(subscriptions.active.isEmpty())
}
@Test fun latePhoneCallbackAfterRemovalFailureCannotChangeNewState() {
options(1)
phone().failRemove = true
options(0)
phone().failRemove = false
options(1)
val count = NativeLib.phoneRequests.size
deliver(10, TelephonyManager.CALL_STATE_OFFHOOK, 0)
assertEquals(count, NativeLib.phoneRequests.size)
deliver(10, TelephonyManager.CALL_STATE_RINGING); state(2)
}
@Test fun listFailureInvalidatesOldPhoneCallbacksUntilRecovery() {
options(1)
subscriptions.failQuery = true
subscriptions.deliver(); loop.dispatchAll(); state(0)
val count = NativeLib.phoneRequests.size
deliver(10, TelephonyManager.CALL_STATE_IDLE, 0)
assertEquals(count, NativeLib.phoneRequests.size)
subscriptions.failQuery = false
loop.advanceBy(30_000); state(1)
}
@Test fun disablingPolicyCancelsRegistrationRetry() {
phone().failRegister = true
options(1)
options(24)
val attempts = phone().registerAttempts
phone().failRegister = false
loop.advanceBy(60_000)
state(0, 24)
assertEquals(attempts, phone().registerAttempts)
assertTrue(phone().active.isEmpty() && subscriptions.active.isEmpty())
}
@Test fun emptySimSetStaysUnknownAndNewSimIsObserved() {
subscriptions.ids = emptyList()
options(1); state(0)
assertEquals(1, subscriptions.active.size)
subscriptions.ids = listOf(10)
subscriptions.deliver(); loop.dispatchAll(); state(1)
}
@Test fun missingTelephonyServiceStaysUnknown() {
context.telephonyManager = null
options(1); state(0)
assertTrue(LogManager.entries.any { it.level == "WARN" && it.category == "PhoneState" })
assertTrue(subscriptions.active.isEmpty())
}
@Test fun rejectedNativeCommandIsRetriedByRefresh() {
NativeLib.acceptPhoneRequest = false
options(1)
assertTrue(LogManager.entries.any { it.level == "WARN" && it.message.contains("not queued") })
NativeLib.acceptPhoneRequest = true
NativeLib.phoneRequests.clear()
PhoneStateMonitor.refresh(); state(1)
}
@Test fun invalidThreadCannotInitOrRefreshAndIsLogged() {
for (action in listOf({ PhoneStateMonitor.init() }, { PhoneStateMonitor.refresh() })) {
val error = AtomicReference<Throwable?>()
val thread = Thread { try { action() } catch (failure: Throwable) { error.set(failure) } }
thread.start(); thread.join(2_000)
assertFalse(thread.isAlive)
assertTrue(error.get() is IllegalStateException)
}
assertEquals(0, subscriptions.addAttempts)
assertTrue(LogManager.entries.any { it.level == "ERROR" && it.message.contains("main thread") })
}
}