Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<MainActivity>()

@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()
}
}
5 changes: 5 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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" />
</service>

<service
android:name=".calls.CallStandbyRecoveryJob"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE" />

<receiver android:name=".calls.CallNotificationAction" android:exported="false" />

<!-- 应用内语音通话:通话期间撑住进程与后台麦克风;通知带挂断动作,锁屏时不打开通话页。 -->
Expand Down
29 changes: 26 additions & 3 deletions app/src/main/java/com/wangzan101/mika/calls/CallRuntime.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 ||
Expand Down Expand Up @@ -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 &&
Expand All @@ -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
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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
}
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/wangzan101/mika/calls/CallSettings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
}
26 changes: 19 additions & 7 deletions app/src/main/java/com/wangzan101/mika/calls/CallStandbyService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand All @@ -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
}

Expand All @@ -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))
Expand Down Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions app/src/main/java/com/wangzan101/mika/quit/MikaQuit.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
// 主动能力开着时不再读通知:请系统解绑监听,免得系统为了它把进程又拉起来
Expand Down
23 changes: 21 additions & 2 deletions app/src/main/java/com/wangzan101/mika/ui/CallSettingsScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand All @@ -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.
Expand All @@ -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)
}
}
}
Expand All @@ -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()
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -667,6 +685,7 @@ private fun CallPreferencesPage(
LaunchedEffect(openDeviceRequest) {
if (openDeviceRequest != lastDeviceRequest) {
deviceOpen = true
backgroundOpen = true
lastDeviceRequest = openDeviceRequest
}
}
Expand Down
Loading
Loading