diff --git a/app/src/androidTest/java/com/wangzan101/mika/ui/CallStandbyNotificationRouteTest.kt b/app/src/androidTest/java/com/wangzan101/mika/ui/CallStandbyNotificationRouteTest.kt new file mode 100644 index 0000000000..0cee7ac8f8 --- /dev/null +++ b/app/src/androidTest/java/com/wangzan101/mika/ui/CallStandbyNotificationRouteTest.kt @@ -0,0 +1,37 @@ +package com.wangzan101.mika.ui + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.wangzan101.mika.R +import com.wangzan101.mika.calls.CallStandbyService +import org.junit.Assert.assertNotEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +/** Exercises the notification's local navigation without starting the phone service or making calls. */ +@RunWith(AndroidJUnit4::class) +class CallStandbyNotificationRouteTest { + @get:Rule val compose = createAndroidComposeRule() + + @Test fun blockedStandbyNotificationReopensTheExpandedSettings() { + val activity = compose.activity + val general = CallStandbyService.notificationContentIntent(activity, opensSettings = false) + val repair = CallStandbyService.notificationContentIntent(activity, opensSettings = true) + assertNotEquals(general, repair) + val background = compose.onNodeWithTag("call-settings-background") + val details = compose.onNodeWithText(activity.getString(R.string.calls_background_lock_screen_note)) + repair.send() + background.performScrollTo().assertIsDisplayed() + details.performScrollTo().assertIsDisplayed() + background.performScrollTo().performClick() + details.assertDoesNotExist() + repair.send() + details.performScrollTo().assertIsDisplayed() + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7598025cfe..b13317f065 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -282,6 +282,11 @@ android:value="Keeps the user-enabled incoming call assistant available while the screen is locked and carries one user-confirmed outgoing call across screen lock, with a visible ongoing notification and no idle audio capture" /> + + diff --git a/app/src/main/java/com/wangzan101/mika/calls/CallRuntime.kt b/app/src/main/java/com/wangzan101/mika/calls/CallRuntime.kt index ee223f532a..b164615282 100644 --- a/app/src/main/java/com/wangzan101/mika/calls/CallRuntime.kt +++ b/app/src/main/java/com/wangzan101/mika/calls/CallRuntime.kt @@ -22,6 +22,9 @@ import android.telecom.VideoProfile import android.telephony.SubscriptionManager import android.telephony.TelephonyManager import android.util.Log +import androidx.annotation.MainThread +import com.wangzan101.mika.i18n.tr +import com.wangzan101.mika.settings.FeatureFlags import android.view.accessibility.AccessibilityEvent import com.wangzan101.mika.cap.phone.a11y.ScreenAccessibility import com.wangzan101.mika.BuildConfig @@ -206,7 +209,9 @@ class CallRuntime(private val app: MikaApp) { lockedDial?.takeIf { !config.enabled || !config.credentialsConfigured || config.audioMode != it.config.audioMode || config.activeVoiceProfileId != it.config.activeVoiceProfileId } ?.let { finishLockedDial(it, "电话设置已变更,未执行锁屏拨出") } - if (!hasAuthorizedIncomingStandby()) standbyService?.revokeIncomingAuthorization() + val authorized = hasAuthorizedIncomingStandby() + if (!authorized) standbyService?.revokeIncomingAuthorization() + CallStandbyRecoveryJob.reconcile(app, authorized) stopBackgroundStandbyIfUnneeded() val active = work if (active != null && (!config.enabled || !config.credentialsConfigured || @@ -284,7 +289,7 @@ class CallRuntime(private val app: MikaApp) { // The app can reopen before the on-device audio helper finishes reconnecting. // Reevaluate when readiness changes; Android only permits this start while visible. combine(app.foreground.visible, state) { visible, _ -> visible }.collect { visible -> - val eligible = visible && !standbyStarting && standbyService?.stickyAutoAnswer != true && + val eligible = visible && !configuring && !standbyStarting && standbyService?.stickyAutoAnswer != true && work == null && lockedDial == null && !unobservedManagedCall && liveCalls().isEmpty() && hasAuthorizedIncomingStandby() && interactiveForeground() && autoAnswerBlocker(settings.state.value) == null && @@ -309,6 +314,23 @@ class CallRuntime(private val app: MikaApp) { if (isIncomingStandbyRunning()) ok("后台待命已启动") else fail(standbyStartError ?: "后台待命未启动") } + @MainThread + internal fun refreshStandbyRecovery() { + CallStandbyRecoveryJob.reconcile(app, hasAuthorizedIncomingStandby()) + } + + /** A periodic check never restores outgoing work or overrides an explicit stop. */ + @MainThread + internal fun restoreAuthorizedStandbyFromSystem(requireBatteryExemption: Boolean) { + refreshStandbyRecovery() + if (!hasAuthorizedIncomingStandby() || + (requireBatteryExemption && !CallStandbyRecoveryJob.allowsScheduledForegroundStart(app)) || + !CallStandbyRecoveryJob.allowsBackgroundRecovery(app) || + configuring || standbyStarting || isIncomingStandbyRunning() || hasOutgoingForegroundWork() || + !CallStandbyService.notificationsAvailable(app, create = true)) return + requestCallForegroundService(incoming = true) + } + private fun requestCallForegroundService(incoming: Boolean): Boolean { if (standbyStarting) return !incoming || standbyIncomingRequested standbyIncomingRequested = incoming @@ -337,7 +359,7 @@ class CallRuntime(private val app: MikaApp) { private fun isStandbyOptedIn(): Boolean = CallStandbyPolicy.optedIn(settings.state.value, userUnlocked()) - internal fun hasAuthorizedIncomingStandby(): Boolean = isStandbyOptedIn() && settings.state.value.backgroundStandbyAuthorized + internal fun hasAuthorizedIncomingStandby(): Boolean = isStandbyOptedIn() && settings.state.value.backgroundStandbyAuthorized && !FeatureFlags.get(app).quitRequested() private fun isIncomingStandbyRunning(): Boolean = standbyService?.stickyAutoAnswer == true && hasAuthorizedIncomingStandby() @@ -1927,6 +1949,7 @@ class CallRuntime(private val app: MikaApp) { app.getString(R.string.calls_pick_types) else "自动接听名单为空" config.incomingScope == IncomingScope.TYPES && ScreenAccessibility.instance.value == null -> app.getString(R.string.calls_type_accessibility) + config.enabled && shell == null && !configuring -> tr(R.string.calls_setup_shell) else -> prerequisite(ignoreWork = true, notificationReady = notificationReady) ?: if (!audioReady) audioDetail ?: "设备通话音频尚未准备好" else null } diff --git a/app/src/main/java/com/wangzan101/mika/calls/CallSettings.kt b/app/src/main/java/com/wangzan101/mika/calls/CallSettings.kt index a04e2b8b37..c19e9b441b 100644 --- a/app/src/main/java/com/wangzan101/mika/calls/CallSettings.kt +++ b/app/src/main/java/com/wangzan101/mika/calls/CallSettings.kt @@ -199,6 +199,10 @@ class CallSettings( private const val CREDENTIALS = "volc_credentials_v1" internal const val BACKGROUND_AUTHORIZED = "background_standby_authorized" + internal fun hasStoredStandbyAuthorization(context: Context): Boolean = + context.getSharedPreferences("mika_call_settings", Context.MODE_PRIVATE) + .getBoolean(BACKGROUND_AUTHORIZED, false) + fun create(context: Context): CallSettings = CallSettings(context.getSharedPreferences("mika_call_settings", Context.MODE_PRIVATE)) } diff --git a/app/src/main/java/com/wangzan101/mika/calls/CallStandbyRecoveryJob.kt b/app/src/main/java/com/wangzan101/mika/calls/CallStandbyRecoveryJob.kt new file mode 100644 index 0000000000..308255c4f5 --- /dev/null +++ b/app/src/main/java/com/wangzan101/mika/calls/CallStandbyRecoveryJob.kt @@ -0,0 +1,85 @@ +package com.wangzan101.mika.calls + +import android.app.ActivityManager +import android.app.ApplicationExitInfo +import android.app.job.JobInfo +import android.app.job.JobParameters +import android.app.job.JobScheduler +import android.app.job.JobService +import android.content.ComponentName +import android.content.Context +import android.os.Build +import android.os.PowerManager +import android.util.Log +import com.wangzan101.mika.MikaApp + +/** Periodic backup for devices that drop the normal sticky foreground-service restart. */ +class CallStandbyRecoveryJob : JobService() { + override fun onStartJob(params: JobParameters): Boolean { + // JobService and the runtime share the main thread. Keep this callback alive until + // Android has been asked to start the service or the runtime has declined the request. + (application as MikaApp).calls.restoreAuthorizedStandbyFromSystem(requireBatteryExemption = true) + return false + } + + // The callback queues no job-owned work, and later checks use the normal periodic schedule. + override fun onStopJob(params: JobParameters): Boolean = false + + companion object { + private const val JOB_ID = 0x43414C52 + private const val INTERVAL_MS = 15 * 60 * 1_000L + private const val PREFS = "call_standby_recovery" + private const val LAST_OPENED = "last_opened" + private const val USER_STOPPED = "user_stopped" + + /** Keep the existing interval across app/service restarts. The OS can defer periodic work. */ + internal fun reconcile(context: Context, authorized: Boolean) { + runCatching { + val scheduler = context.getSystemService(JobScheduler::class.java) ?: return + if (!authorized || !allowsScheduledForegroundStart(context) || !allowsBackgroundRecovery(context)) { + scheduler.cancel(JOB_ID) + } else if (scheduler.getPendingJob(JOB_ID) == null) { + val info = JobInfo.Builder(JOB_ID, ComponentName(context, CallStandbyRecoveryJob::class.java)) + .setPeriodic(INTERVAL_MS) + .setPersisted(true) + .build() + check(scheduler.schedule(info) == JobScheduler.RESULT_SUCCESS) + } + }.onFailure { Log.w("CallStandby", "Could not configure the Android standby recovery job", it) } + } + + internal fun acknowledgeUserOpen(context: Context) { + prefs(context).edit().putLong(LAST_OPENED, System.currentTimeMillis()).remove(USER_STOPPED).apply() + } + + internal fun allowsScheduledForegroundStart(context: Context): Boolean = runCatching { + Build.VERSION.SDK_INT >= 30 && + context.getSystemService(ActivityManager::class.java)?.isBackgroundRestricted == false && + context.getSystemService(PowerManager::class.java)?.isIgnoringBatteryOptimizations(context.packageName) == true + }.getOrDefault(false) + + internal fun allowsBackgroundRecovery(context: Context): Boolean { + val state = prefs(context) + if (Build.VERSION.SDK_INT < 30 || state.getBoolean(USER_STOPPED, false)) return false + val lastOpened = state.getLong(LAST_OPENED, 0L) + val userStopped = runCatching { + val manager = checkNotNull(context.getSystemService(ActivityManager::class.java)) + // Before the first recorded opening, only the newest exit is reliable for + // deciding whether the existing install was stopped by the owner. + val maxRecords = if (lastOpened > 0L) 0 else 1 + manager.getHistoricalProcessExitReasons(context.packageName, 0, maxRecords).any { + explicitStopSinceOpen(it.reason, it.timestamp, lastOpened) + } + }.getOrElse { return false } + if (!userStopped) return true + // Task Manager can leave jobs scheduled. Remember the stop after exit history rotates. + state.edit().putBoolean(USER_STOPPED, true).apply() + return false + } + + internal fun explicitStopSinceOpen(reason: Int, exitedAt: Long, lastOpened: Long): Boolean = + reason == ApplicationExitInfo.REASON_USER_REQUESTED && exitedAt >= lastOpened + + private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + } +} diff --git a/app/src/main/java/com/wangzan101/mika/calls/CallStandbyService.kt b/app/src/main/java/com/wangzan101/mika/calls/CallStandbyService.kt index fe2ff5c691..b043d1f94a 100644 --- a/app/src/main/java/com/wangzan101/mika/calls/CallStandbyService.kt +++ b/app/src/main/java/com/wangzan101/mika/calls/CallStandbyService.kt @@ -65,7 +65,10 @@ class CallStandbyService : Service() { if (calls?.hasOutgoingForegroundWork() != true || statusJob == null) requestStop(startId) return START_NOT_STICKY } - val incoming = calls.hasAuthorizedIncomingStandby() && (intent == null || calls.isIncomingStandbyStartRequested() || stickyAutoAnswer) + val incoming = calls.hasAuthorizedIncomingStandby() && ( + if (intent == null) Build.VERSION.SDK_INT < 30 || CallStandbyRecoveryJob.allowsBackgroundRecovery(this) + else calls.isIncomingStandbyStartRequested() || stickyAutoAnswer + ) if (!notificationAllowed || !CallStandbyPolicy.acceptsStart(incoming, explicit, calls.hasOutgoingForegroundWork())) { calls.onStandbyStartFailed(getString( if (notificationAllowed) R.string.calls_standby_not_ready else R.string.calls_standby_notifications_required, @@ -92,7 +95,8 @@ class CallStandbyService : Service() { state.backgroundStandbyBlockedReason != null -> getString(R.string.calls_standby_unavailable) state.aiActive -> getString(R.string.calls_standby_ai_active) else -> getString(R.string.calls_standby_running) - }, state.lockedDialRequestId) + }, state.lockedDialRequestId, opensSettings = state.phase == CallPhase.IDLE && + !lockedDial && state.autoAnswerStage != CallAutoAnswerStage.PAUSED && state.backgroundStandbyBlockedReason != null) }.distinctUntilChanged().collect { notice -> if (notice == null) requestStop() else if (runCatching { @@ -101,7 +105,7 @@ class CallStandbyService : Service() { } } // A null Intent is only accepted when Android restarts this already opted-in service. - // Our other recovery path runs only with the unlocked app visible and an existing grant. + // Periodic recovery reuses an existing incoming-only grant. return if (incoming) START_STICKY else START_NOT_STICKY } @@ -120,12 +124,10 @@ class CallStandbyService : Service() { super.onDestroy() } - private data class Notice(val summary: String, val requestId: String?) + private data class Notice(val summary: String, val requestId: String?, val opensSettings: Boolean = false) private fun notification(notice: Notice): Notification { - val open = PendingIntent.getActivity(this, NOTIFICATION_ID, Intent(this, MainActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - .putExtra(MainActivity.EXTRA_OPEN_CALLS, true), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val open = notificationContentIntent(this, notice.opensSettings) return Notification.Builder(this, CHANNEL) .setSmallIcon(android.R.drawable.sym_action_call) .setContentTitle(getString(R.string.app_name)) @@ -153,6 +155,16 @@ class CallStandbyService : Service() { private const val ACTION_START = "com.wangzan101.mika.calls.START_STANDBY" private const val EXTRA_REQUEST_ID = "standby_start_id" private const val NOTIFICATION_ID = 90_118 + private const val STANDBY_SETTINGS_REQUEST_CODE = 90_120 + + internal fun notificationContentIntent(context: Context, opensSettings: Boolean): PendingIntent { + val requestCode = if (opensSettings) STANDBY_SETTINGS_REQUEST_CODE else NOTIFICATION_ID + val intent = Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + .putExtra(MainActivity.EXTRA_OPEN_CALLS, true) + .putExtra(MainActivity.EXTRA_OPEN_STANDBY_SETTINGS, opensSettings) + return PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + } internal fun startIntent(context: Context, requestId: String? = null): Intent = Intent(context, CallStandbyService::class.java).setAction(ACTION_START).putExtra(EXTRA_REQUEST_ID, requestId) diff --git a/app/src/main/java/com/wangzan101/mika/quit/MikaQuit.kt b/app/src/main/java/com/wangzan101/mika/quit/MikaQuit.kt index 047864cecd..b7a786c287 100644 --- a/app/src/main/java/com/wangzan101/mika/quit/MikaQuit.kt +++ b/app/src/main/java/com/wangzan101/mika/quit/MikaQuit.kt @@ -40,6 +40,7 @@ object MikaQuit { runCatching { app.capsule.stopNow() } // 先撤掉系统闹钟和进程内的长任务,再停前台服务;服务被系统重交启动请求时也会按退出标记拒绝工作 runCatching { TriggerRuntime.suspendAlarms(app) } + com.wangzan101.mika.calls.CallStandbyRecoveryJob.reconcile(app, authorized = false) runCatching { RuntimePreparer.stop(app) } runCatching { app.wechat.stop() } // 主动能力开着时不再读通知:请系统解绑监听,免得系统为了它把进程又拉起来 diff --git a/app/src/main/java/com/wangzan101/mika/ui/CallSettingsScreen.kt b/app/src/main/java/com/wangzan101/mika/ui/CallSettingsScreen.kt index b13d5be7d8..834f25d320 100644 --- a/app/src/main/java/com/wangzan101/mika/ui/CallSettingsScreen.kt +++ b/app/src/main/java/com/wangzan101/mika/ui/CallSettingsScreen.kt @@ -48,7 +48,8 @@ import java.util.Date fun CallSettingsScreen(runtime: CallRuntime, onInstructions: (() -> Unit)? = null, onBack: () -> Unit, standalone: Boolean = false, onHelperSetup: () -> Unit = {}, onAbout: () -> Unit = {}, initialHistoryCallId: String? = null, - updateAvailable: Boolean = false, focusRequest: Int = 0, onOpenVoiceCatalog: () -> Unit = {}) { + updateAvailable: Boolean = false, focusRequest: Int = 0, standbySettingsSignal: Int = 0, + onStandbySettingsOpened: () -> Unit = {}, onOpenVoiceCatalog: () -> Unit = {}) { var instructionsOpen by rememberSaveable { mutableStateOf(false) } var voiceProfilesOpen by rememberSaveable { mutableStateOf(false) } var handledFocusRequest by rememberSaveable { mutableIntStateOf(0) } @@ -61,6 +62,12 @@ fun CallSettingsScreen(runtime: CallRuntime, onInstructions: (() -> Unit)? = nul handledFocusRequest = focusRequest } } + LaunchedEffect(standbySettingsSignal) { + if (standbySettingsSignal != 0) { + instructionsOpen = false + voiceProfilesOpen = false + } + } when { // Post-migration the legacy realtime profile screen must never silently misbehave: // redirect to the unified voice catalog where realtime models are edited and tested. @@ -74,7 +81,8 @@ fun CallSettingsScreen(runtime: CallRuntime, onInstructions: (() -> Unit)? = nul instructionsOpen -> CallInstructionsScreen(runtime) { instructionsOpen = false } else -> workspaceState.SaveableStateProvider("call-workspace") { CallSettingsWorkspace(runtime, taskDraft, onBack, onInstructions ?: { instructionsOpen = true }, - { voiceProfilesOpen = true }, standalone, onHelperSetup, onAbout, updateAvailable, focusRequest, initialHistoryCallId) + { voiceProfilesOpen = true }, standalone, onHelperSetup, onAbout, updateAvailable, focusRequest, initialHistoryCallId, + standbySettingsSignal, onStandbySettingsOpened) } } } @@ -86,6 +94,7 @@ private fun CallSettingsWorkspace( standalone: Boolean, onHelperSetup: () -> Unit, onAbout: () -> Unit, updateAvailable: Boolean, focusRequest: Int, initialHistoryCallId: String?, + standbySettingsSignal: Int, onStandbySettingsOpened: () -> Unit, ) { val config by runtime.settings.state.collectAsState() val state by runtime.state.collectAsState() @@ -185,6 +194,15 @@ private fun CallSettingsWorkspace( deviceNavigation++ } + LaunchedEffect(standbySettingsSignal) { + if (standbySettingsSignal != 0) { + if (idle && pendingLockedDial == null) { + dialog = null + openDeviceSettings() + } + onStandbySettingsOpened() + } + } PageBackground(Modifier.testTag("call-settings")) { Column(Modifier.fillMaxSize().navigationBarsPadding().imePadding()) { if (standalone) TopBar(stringResource(R.string.app_name), MikaIcons.Gear, ::openDeviceSettings, @@ -667,6 +685,7 @@ private fun CallPreferencesPage( LaunchedEffect(openDeviceRequest) { if (openDeviceRequest != lastDeviceRequest) { deviceOpen = true + backgroundOpen = true lastDeviceRequest = openDeviceRequest } } diff --git a/app/src/main/java/com/wangzan101/mika/ui/MainActivity.kt b/app/src/main/java/com/wangzan101/mika/ui/MainActivity.kt index f53f079190..31c0bd616d 100644 --- a/app/src/main/java/com/wangzan101/mika/ui/MainActivity.kt +++ b/app/src/main/java/com/wangzan101/mika/ui/MainActivity.kt @@ -93,6 +93,7 @@ class MainActivity : ComponentActivity() { private lateinit var monitor: SystemStatusMonitor private var requestedConversation by mutableStateOf(null) private var requestedCalls by mutableStateOf(false) + private var requestedStandbySettings by mutableIntStateOf(0) private var requestedCallHistoryId by mutableStateOf(null) private var voiceCallSignal by mutableIntStateOf(0) private var openTeach by mutableStateOf(false) @@ -121,6 +122,7 @@ class MainActivity : ComponentActivity() { } requestedConversation = intent.getStringExtra(EXTRA_OPEN_CONVERSATION) requestedCalls = intent.getBooleanExtra(EXTRA_OPEN_CALLS, false) + takeStandbySettings(intent) requestedCallHistoryId = intent.getStringExtra(EXTRA_CALL_HISTORY_ID) takeVoiceCall(intent) takeTeach(intent) @@ -141,7 +143,8 @@ class MainActivity : ComponentActivity() { KeyboardDismissArea(Modifier.fillMaxSize()) { MikaRoot( store, monitor, ::perform, requestedConversation, { requestedConversation = null }, - requestedCalls, requestedCallHistoryId, { requestedCalls = false; requestedCallHistoryId = null }, + requestedCalls, requestedCallHistoryId, requestedStandbySettings, + { requestedCalls = false; requestedCallHistoryId = null }, voiceCallSignal, requestedSharedDraft, onSharedDraftOpened = { accepted, draft -> @@ -169,6 +172,7 @@ class MainActivity : ComponentActivity() { shareJob?.cancel() requestedConversation = intent.getStringExtra(EXTRA_OPEN_CONVERSATION) requestedCalls = intent.getBooleanExtra(EXTRA_OPEN_CALLS, false) + takeStandbySettings(intent) requestedCallHistoryId = intent.getStringExtra(EXTRA_CALL_HISTORY_ID) if (requestedConversation != null || intent.getBooleanExtra(EXTRA_OPEN_TEACH, false)) { app.chat.cancelPendingSharedDraft() @@ -183,6 +187,14 @@ class MainActivity : ComponentActivity() { receiveShare(intent, inCurrentConversation = true) } + private fun takeStandbySettings(intent: Intent) { + if (!intent.getBooleanExtra(EXTRA_OPEN_STANDBY_SETTINGS, false)) return + requestedCalls = true + requestedStandbySettings++ + intent.removeExtra(EXTRA_OPEN_STANDBY_SETTINGS) + intent.removeExtra(EXTRA_OPEN_CALLS) + } + override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(STATE_SHARE_IN_CURRENT, shareInCurrent) @@ -256,6 +268,13 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() foreground = true + val mika = application as MikaApp + com.wangzan101.mika.calls.CallStandbyRecoveryJob.acknowledgeUserOpen(mika) + if (com.wangzan101.mika.calls.CallSettings.hasStoredStandbyAuthorization(mika)) { + mika.calls.refreshStandbyRecovery() + } else { + mika.runningCalls?.refreshStandbyRecovery() + } monitor.refresh() // 回到前台时按最新设置查一次自动归档(启动时也查过,这里照顾长期不退出的进程) (application as MikaApp).autoArchiveNow() @@ -364,6 +383,7 @@ class MainActivity : ComponentActivity() { companion object { const val EXTRA_OPEN_CONVERSATION = "open_conversation" const val EXTRA_OPEN_CALLS = "open_calls" + internal const val EXTRA_OPEN_STANDBY_SETTINGS = "open_standby_settings" const val EXTRA_CALL_HISTORY_ID = "call_history_id" const val EXTRA_OPEN_TEACH = "open_teach" const val EXTRA_TEACH_GOAL = "teach_goal" @@ -404,6 +424,7 @@ private fun MikaRoot( onConversationOpened: () -> Unit, requestedCalls: Boolean, requestedCallHistoryId: String?, + requestedStandbySettings: Int, onCallsOpened: () -> Unit, voiceCallSignal: Int, sharedDraft: SharedDraftRequest?, @@ -413,6 +434,8 @@ private fun MikaRoot( ) { val context = LocalContext.current var focusedCallHistoryId by remember { mutableStateOf(null) } + var handledStandbySettings by remember { mutableIntStateOf(0) } + var standbySettingsSignal by remember { mutableIntStateOf(0) } val personalStart = remember { FeatureFlags.get(context).personalStart() } val nav = rememberNavStack(if (personalStart && requestedConversation == null) Route.Personal else Route.Chat) var filesFromDrawer by rememberSaveable { mutableStateOf(false) } @@ -490,9 +513,13 @@ private fun MikaRoot( onConversationOpened() } } - LaunchedEffect(requestedCalls, requestedCallHistoryId) { + LaunchedEffect(requestedCalls, requestedCallHistoryId, requestedStandbySettings) { if (requestedCalls) { focusedCallHistoryId = requestedCallHistoryId + if (requestedStandbySettings != handledStandbySettings) { + handledStandbySettings = requestedStandbySettings + standbySettingsSignal++ + } nav.push(Route.Calls) onCallsOpened() } @@ -818,7 +845,10 @@ private fun MikaRoot( app.chat.openConversation(it) nav.reset() }) - Route.Calls -> CallSettingsScreen(app.calls, onBack = back, standalone = true, initialHistoryCallId = focusedCallHistoryId, onOpenVoiceCatalog = { nav.push(Route.VoiceCatalog) }) + Route.Calls -> CallSettingsScreen(app.calls, onBack = back, standalone = true, + initialHistoryCallId = focusedCallHistoryId, standbySettingsSignal = standbySettingsSignal, + onStandbySettingsOpened = { standbySettingsSignal = 0 }, + onOpenVoiceCatalog = { nav.push(Route.VoiceCatalog) }) } } } diff --git a/app/src/test/java/com/wangzan101/mika/ManifestProvidersTest.kt b/app/src/test/java/com/wangzan101/mika/ManifestProvidersTest.kt index 573e9266b5..ba9b2df9df 100644 --- a/app/src/test/java/com/wangzan101/mika/ManifestProvidersTest.kt +++ b/app/src/test/java/com/wangzan101/mika/ManifestProvidersTest.kt @@ -64,6 +64,17 @@ class ManifestProvidersTest { assertEquals(0, s.getElementsByTagName("intent-filter").length) } + @Test + fun standbyRecoveryServiceOnlyAcceptsSystemJobBinding() { + val doc = DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true } + .newDocumentBuilder().parse(File("src/main/AndroidManifest.xml")) + val services = doc.getElementsByTagName("service") + val service = (0 until services.length).map { services.item(it) as Element } + .single { it.getAttributeNS(androidNs, "name") == ".calls.CallStandbyRecoveryJob" } + assertEquals("false", service.getAttributeNS(androidNs, "exported")) + assertEquals("android.permission.BIND_JOB_SERVICE", service.getAttributeNS(androidNs, "permission")) + } + /** 清单里登记的组件都按全名找得到类(搬了代码的入口留着同名的薄壳)。 */ @Test fun everyComponentClassExists() { diff --git a/app/src/test/java/com/wangzan101/mika/calls/CallStandbyRecoveryJobTest.kt b/app/src/test/java/com/wangzan101/mika/calls/CallStandbyRecoveryJobTest.kt new file mode 100644 index 0000000000..6438bc3519 --- /dev/null +++ b/app/src/test/java/com/wangzan101/mika/calls/CallStandbyRecoveryJobTest.kt @@ -0,0 +1,14 @@ +package com.wangzan101.mika.calls + +import android.app.ApplicationExitInfo +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class CallStandbyRecoveryJobTest { + @Test fun scheduledStandbyRespectsOwnerStopUntilTheNextOpen() { + assertTrue(CallStandbyRecoveryJob.explicitStopSinceOpen(ApplicationExitInfo.REASON_USER_REQUESTED, 101L, 100L)) + assertFalse(CallStandbyRecoveryJob.explicitStopSinceOpen(ApplicationExitInfo.REASON_USER_REQUESTED, 101L, 102L)) + assertFalse(CallStandbyRecoveryJob.explicitStopSinceOpen(ApplicationExitInfo.REASON_LOW_MEMORY, 101L, 100L)) + } +}