Wake word: what it tried and how it went is kept and shown; the screen comes on
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
The phrase was heard, LLeMbas was the assistant, and still only "Heard you. Tap to ask." came: wake() reached the notification when the assistant service was not connected or showSession threw, and kept neither reason. - WakeAttempt: when, the phrase, the way tried (wakeWay: session, the sheet's activity through the assistant service when the screen is off, the activity while the app is on screen, a notification), the outcome (opened / not connected / refused with the exception / no sheet came), the fallback, whether the role was held, and when Android last connected and disconnected the service in this process. The last five live in the settings, are logged under LLeMbasWake, and are shown as "Last wake". An attempt that found the service not connected is told when a later onReady arrives. - "Opened" is counted only once a sheet says it is up (AssistLink.shown, 2.5 s); otherwise the fallback follows. - Settings says when LLeMbas holds the role but the service is not connected, with the way to the system's assistant setting. - The sheet opened by the wake word turns the screen on: setTurnScreenOn on the activity; with the screen off and the service connected the activity is started through the service instead of a session, whose window wakes nothing. - The fallback notification says "Could not open by itself -- tap to ask" when LLeMbas is the assistant. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
23 files changed
+818
-50
No files matched your search
@@ -6,6 +6,7 @@ import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
@@ -18,6 +19,7 @@ import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
|
||||
@@ -75,7 +77,11 @@ class AssistActivity : ComponentActivity() {
|
||||
controller = AssistController(this, lifecycleScope)
|
||||
keyguard = getSystemService(KeyguardManager::class.java)
|
||||
locked.value = keyguard.isKeyguardLocked
|
||||
// Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch,
|
||||
// so nothing else has woken the phone).
|
||||
if (intent?.getBooleanExtra(EXTRA_WAKE, false) == true) setTurnScreenOn(true)
|
||||
AssistPresence.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// The sheet is up: "Heard you. Tap to ask." has been answered, however it was opened.
|
||||
getSystemService(NotificationManager::class.java).cancel(WakeWordService.HEARD_ID)
|
||||
take(intent)
|
||||
@@ -172,6 +178,12 @@ class AssistActivity : ComponentActivity() {
|
||||
/** The sheet, listening. */
|
||||
fun listening(context: Context): Intent = Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN)
|
||||
|
||||
/** On the intent the wake word opens the sheet with: turn the screen on. */
|
||||
const val EXTRA_WAKE = "eu.llembas.android.WAKE"
|
||||
|
||||
/** The sheet, listening, as the wake word opens it. */
|
||||
fun woken(context: Context): Intent = listening(context).putExtra(EXTRA_WAKE, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/** The sheet, at the last assistant chat. */
|
||||
fun continuing(context: Context): Intent = Intent(context, AssistActivity::class.java).setAction(ACTION_CONTINUE)
|
||||
}
|
||||
|
||||
@@ -2,14 +2,17 @@ package eu.llembas.android.assist
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import android.app.assist.AssistStructure
|
||||
import android.app.role.RoleManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.service.voice.VoiceInteractionService
|
||||
import android.service.voice.VoiceInteractionSession
|
||||
import android.service.voice.VoiceInteractionSessionService
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -27,12 +30,15 @@ import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.wakeLogConnected
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
/**
|
||||
@@ -46,10 +52,18 @@ class LembasAssistService : VoiceInteractionService() {
|
||||
override fun onReady() {
|
||||
super.onReady()
|
||||
current = this
|
||||
// When Android connected it is kept: the wake word's record says whether it was, and an
|
||||
// attempt that found it not connected is told that it came later.
|
||||
val now = System.currentTimeMillis()
|
||||
AssistLink.ready(now)
|
||||
Log.i(TAG, "assistant service connected by Android")
|
||||
background.launch { runCatching { lembas.instances.savePrefs { it.copy(wakeLog = wakeLogConnected(it.wakeLog, now)) } } }
|
||||
}
|
||||
|
||||
override fun onShutdown() {
|
||||
if (current === this) current = null
|
||||
AssistLink.shutdown(System.currentTimeMillis())
|
||||
Log.i(TAG, "assistant service disconnected by Android")
|
||||
super.onShutdown()
|
||||
}
|
||||
|
||||
@@ -62,6 +76,13 @@ class LembasAssistService : VoiceInteractionService() {
|
||||
@Volatile
|
||||
var current: LembasAssistService? = null
|
||||
private set
|
||||
|
||||
private const val TAG = "LLeMbasWake"
|
||||
private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
/** Whether Android says LLeMbas holds the assistant role (Settings › Default apps › Digital assistant app). */
|
||||
fun holdsRole(context: Context): Boolean =
|
||||
runCatching { context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) }.getOrNull() ?: false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,6 +153,7 @@ class LembasAssistSession(context: Context) :
|
||||
super.onShow(args, showFlags)
|
||||
registry.currentState = Lifecycle.State.RESUMED
|
||||
AssistPresence.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// The wake word asks for the sheet listening, whatever Settings says about opening.
|
||||
controller.opened(locked(), listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.wake.WakeAttempt
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -93,6 +94,8 @@ data class Prefs(
|
||||
val wakePhrase: String = "hey_assistant",
|
||||
/** WakeSensitivity's id: low, normal or high. */
|
||||
val wakeSensitivity: String = "normal",
|
||||
/** What happened the last times the wake word was heard (WakeLog): shown in Settings, nothing of the account in it. */
|
||||
val wakeLog: List<WakeAttempt> = emptyList(),
|
||||
/** Listen only while the screen is on. */
|
||||
val wakeScreenOnly: Boolean = true,
|
||||
/** The assistant may read the notifications when asked (with Android's notification access). */
|
||||
|
||||
@@ -4,7 +4,6 @@ package eu.llembas.android.ui.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.role.RoleManager
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.SystemClock
|
||||
@@ -40,6 +39,7 @@ import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.GraphicEq
|
||||
import androidx.compose.material.icons.filled.Hearing
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MyLocation
|
||||
@@ -93,6 +93,7 @@ import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.actions.NavApp
|
||||
import eu.llembas.android.assist.LembasAssistService
|
||||
import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
@@ -107,6 +108,8 @@ import eu.llembas.android.update.UpdateResult
|
||||
import eu.llembas.android.update.Updater
|
||||
import eu.llembas.android.update.checksUpdates
|
||||
import eu.llembas.android.update.offersBetas
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.WakeAttempt
|
||||
import eu.llembas.android.wake.WakeEngine
|
||||
import eu.llembas.android.wake.WakeFailure
|
||||
import eu.llembas.android.wake.WakePause
|
||||
@@ -117,6 +120,7 @@ import eu.llembas.android.wake.WakeState
|
||||
import eu.llembas.android.wake.WakeStatus
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import eu.llembas.android.wake.WakeWords
|
||||
import eu.llembas.android.wake.wakeAttemptWords
|
||||
import eu.llembas.android.wake.wakeTitle
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -181,6 +185,8 @@ data class SettingsState(
|
||||
val wakeTest: WakeTestShown = WakeTestShown(),
|
||||
/** Whether LLeMbas is the phone's digital assistant app: only then can the wake word open it over other apps. */
|
||||
val isAssistant: Boolean = true,
|
||||
/** Whether Android has the assistant service connected right now: without it the wake word cannot open the sheet by itself. */
|
||||
val assistantConnected: Boolean = true,
|
||||
/** Whether Android's notification access is given to LLeMbas. */
|
||||
val notificationAccess: Boolean = false,
|
||||
/** Whether this build can read notifications at all (only the `notifications` build declares the listener). */
|
||||
@@ -198,6 +204,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
val active by store.active.collectAsState(initial = null)
|
||||
val prefs by store.prefs.collectAsState(initial = Prefs())
|
||||
val wakeState by WakeStatus.state.collectAsState()
|
||||
val assistantConnected by AssistLink.connected.collectAsState()
|
||||
// The test's ten seconds: its deadline is WakeStatus's, the clock that watches it is here.
|
||||
val trial by WakeStatus.trial.collectAsState()
|
||||
var clock by remember { mutableStateOf(SystemClock.elapsedRealtime()) }
|
||||
@@ -403,7 +410,8 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
wakeAvailable = WakeEngine.AVAILABLE,
|
||||
wakeState = wakeState,
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
isAssistant = context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) ?: false,
|
||||
isAssistant = LembasAssistService.holdsRole(context),
|
||||
assistantConnected = assistantConnected,
|
||||
wakeTest = WakeTestShown(running = clock < trial.until, done = tested && clock >= trial.until, heard = if (tested) trial.heard else 0),
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
notificationAccess = NotificationAccess.granted(context),
|
||||
@@ -733,6 +741,17 @@ internal fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onCho
|
||||
subtitle = stringResource(R.string.wake_not_assistant_line),
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
} else if (!state.assistantConnected) {
|
||||
// The assistant in name, but Android holds no connection to it at this moment:
|
||||
// the one thing that lets the sheet open from the background is missing.
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Assistant,
|
||||
stringResource(R.string.wake_assistant_unbound),
|
||||
subtitle = stringResource(R.string.wake_assistant_unbound_line),
|
||||
tint = palette.warning,
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.wakeAvailable) {
|
||||
@@ -770,6 +789,8 @@ internal fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onCho
|
||||
Rule()
|
||||
WakeTestRow(state, on, phrase.words, actions)
|
||||
Rule()
|
||||
WakeLogRow(state.prefs.wakeLog)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.ScreenLockPortrait,
|
||||
stringResource(R.string.wake_screen_only),
|
||||
@@ -1005,6 +1026,28 @@ private fun WakeTestRow(state: SettingsState, on: Boolean, phrase: String, actio
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* "Last wake": what happened the last time the phrase was heard -- what was tried and how it
|
||||
* went, in plain words, with Android's own where it refused -- and, on a tap, the few before it.
|
||||
*/
|
||||
@Composable
|
||||
private fun WakeLogRow(log: List<WakeAttempt>) {
|
||||
val context = LocalContext.current
|
||||
var all by remember { mutableStateOf(false) }
|
||||
val shown = if (all) log else log.take(1)
|
||||
SettingRow(
|
||||
Icons.Filled.History,
|
||||
stringResource(R.string.wake_last),
|
||||
subtitle = if (log.isEmpty()) {
|
||||
stringResource(R.string.wake_last_none)
|
||||
} else {
|
||||
shown.joinToString("\n\n") { wakeAttemptWords(context, it).joinToString("\n") }
|
||||
},
|
||||
enabled = log.isNotEmpty(),
|
||||
onClick = { all = !all },
|
||||
)
|
||||
}
|
||||
|
||||
private const val GOOGLE = "google"
|
||||
|
||||
private fun sensitivityLabel(sensitivity: WakeSensitivity): Int = when (sensitivity) {
|
||||
|
||||
@@ -14,6 +14,9 @@ import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
@@ -147,27 +150,6 @@ object AssistPresence {
|
||||
}
|
||||
}
|
||||
|
||||
/** How the assistant is opened when the word was heard, from what Android will allow. */
|
||||
enum class WakeOpening {
|
||||
/** LLeMbas is the phone's assistant: its voice-interaction service shows the sheet, from anywhere. */
|
||||
Session,
|
||||
|
||||
/** The app is on screen: the sheet's activity may start. */
|
||||
Activity,
|
||||
|
||||
/**
|
||||
* Neither: Android blocks an activity started from the background, and says nothing when it
|
||||
* does -- so it is not relied on, and a notification to tap is posted.
|
||||
*/
|
||||
Notification,
|
||||
}
|
||||
|
||||
fun wakeOpening(isAssistant: Boolean, appVisible: Boolean): WakeOpening = when {
|
||||
isAssistant -> WakeOpening.Session
|
||||
appVisible -> WakeOpening.Activity
|
||||
else -> WakeOpening.Notification
|
||||
}
|
||||
|
||||
/** Whether the app has an activity on screen: counted from every activity's start and stop (LembasApp). */
|
||||
object AppVisibility {
|
||||
private val started = AtomicInteger(0)
|
||||
@@ -301,6 +283,34 @@ object WakeStatus {
|
||||
const val TRIAL_MS = 10_000L
|
||||
}
|
||||
|
||||
/**
|
||||
* One [attempt] in plain words, a line each: when and for which phrase; what was tried and how it
|
||||
* went (Android's own words where it refused); what was done instead; and, where the assistant
|
||||
* could not be used, what Android had said of it -- whether LLeMbas held the role, and when the
|
||||
* service was connected and disconnected in this run of the app.
|
||||
*/
|
||||
fun wakeAttemptWords(context: Context, attempt: WakeAttempt, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): List<String> {
|
||||
fun time(at: Long): String = DateTimeFormatter.ofPattern("EEE d MMM, HH:mm:ss", locale).format(Instant.ofEpochMilli(at).atZone(zone))
|
||||
val lines = mutableListOf("${time(attempt.at)} · “${attempt.phrase}”")
|
||||
lines += when (attempt.outcome) {
|
||||
WakeAttempt.OUT_OPENED -> context.getString(R.string.wake_out_opened)
|
||||
WakeAttempt.OUT_TESTED -> context.getString(R.string.wake_out_tested)
|
||||
WakeAttempt.OUT_NO_SHEET -> context.getString(R.string.wake_out_no_sheet)
|
||||
WakeAttempt.OUT_REFUSED -> context.getString(R.string.wake_out_refused, attempt.detail)
|
||||
else -> context.getString(R.string.wake_out_not_connected)
|
||||
}
|
||||
when (attempt.fallback) {
|
||||
WakeWay.Activity.id -> lines += context.getString(R.string.wake_out_activity)
|
||||
WakeWay.Notification.id -> lines += context.getString(R.string.wake_out_notification)
|
||||
}
|
||||
if (attempt.outcome == WakeAttempt.OUT_OPENED || attempt.outcome == WakeAttempt.OUT_TESTED) return lines
|
||||
lines += context.getString(if (attempt.assistant) R.string.wake_role_held else R.string.wake_role_not_held)
|
||||
lines += if (attempt.readyAt == 0L) context.getString(R.string.wake_link_never) else context.getString(R.string.wake_link_ready, time(attempt.readyAt))
|
||||
if (attempt.shutdownAt != 0L) lines += context.getString(R.string.wake_link_shutdown, time(attempt.shutdownAt))
|
||||
if (attempt.connectedLater != 0L) lines += context.getString(R.string.wake_link_later, time(attempt.connectedLater))
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* What the service's notification says the moment Android starts it (again): what is true --
|
||||
* [current], while its loop is [running]; "starting" for a service that has only just begun.
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* What happened the last times the wake word was heard: kept (the last [WAKE_LOG_SIZE], in the
|
||||
* phone's settings) and shown in Settings › Wake word, because "it heard me and nothing opened"
|
||||
* cannot be put right without knowing which step said no. Nothing of the account is in it: the
|
||||
* phrase, clock times, and Android's own words where it refused.
|
||||
*/
|
||||
@Serializable
|
||||
data class WakeAttempt(
|
||||
/** When the phrase was heard (wall clock, ms). */
|
||||
val at: Long = 0,
|
||||
val phrase: String = "",
|
||||
/** What was tried first: a [WakeWay]'s id. */
|
||||
val way: String = "",
|
||||
/** How that went: one of the `OUT_…` words. */
|
||||
val outcome: String = "",
|
||||
/** Android's own words when it refused: the exception's class and message. */
|
||||
val detail: String = "",
|
||||
/** What was done instead, when the first way did not open the sheet: `activity`, `notification` or nothing. */
|
||||
val fallback: String = "",
|
||||
/** Whether Android said LLeMbas holds the assistant role at that moment. */
|
||||
val assistant: Boolean = false,
|
||||
/** When Android last connected the assistant service in this run of the app, and last disconnected it; 0: never. */
|
||||
val readyAt: Long = 0,
|
||||
val shutdownAt: Long = 0,
|
||||
/** Set afterwards, when the service was not connected and Android connected it later. */
|
||||
val connectedLater: Long = 0,
|
||||
) {
|
||||
companion object {
|
||||
/** The sheet came up. */
|
||||
const val OUT_OPENED = "opened"
|
||||
|
||||
/** Android was asked and did not refuse, but no sheet came up in time. */
|
||||
const val OUT_NO_SHEET = "no_sheet"
|
||||
|
||||
/** The assistant service was not connected (`LembasAssistService.current` was null). */
|
||||
const val OUT_NOT_CONNECTED = "not_connected"
|
||||
|
||||
/** Android refused, with [detail]. */
|
||||
const val OUT_REFUSED = "refused"
|
||||
|
||||
/** A test in Settings took the word: nothing was to open. */
|
||||
const val OUT_TESTED = "tested"
|
||||
}
|
||||
}
|
||||
|
||||
const val WAKE_LOG_SIZE = 5
|
||||
|
||||
/** [log] with [attempt] put first, cut to the last [WAKE_LOG_SIZE]. */
|
||||
fun wakeLogAdd(log: List<WakeAttempt>, attempt: WakeAttempt): List<WakeAttempt> = (listOf(attempt) + log).take(WAKE_LOG_SIZE)
|
||||
|
||||
/**
|
||||
* Android connected the assistant service at [now]: the newest attempt that found it not
|
||||
* connected, and has not been answered yet, is told so. Anything else is left as it is.
|
||||
*/
|
||||
fun wakeLogConnected(log: List<WakeAttempt>, now: Long): List<WakeAttempt> {
|
||||
val newest = log.firstOrNull() ?: return log
|
||||
if (newest.outcome != WakeAttempt.OUT_NOT_CONNECTED || newest.connectedLater != 0L || now < newest.at) return log
|
||||
return listOf(newest.copy(connectedLater = now)) + log.drop(1)
|
||||
}
|
||||
|
||||
/** The ways the assistant may be opened when the word was heard, in the order they are worth trying. */
|
||||
enum class WakeWay(val id: String) {
|
||||
/** The assistant service is connected and the screen is on: it shows its sheet, from anywhere. */
|
||||
Session("session"),
|
||||
|
||||
/**
|
||||
* The assistant service is connected and the screen is off: a session's window turns no
|
||||
* screen on, so the sheet's activity is started through the service instead (Android lets an
|
||||
* app whose service the system has bound start one), and the activity turns the screen on.
|
||||
*/
|
||||
AssistantActivity("assistant_activity"),
|
||||
|
||||
/** No connected assistant service, but the app is on screen: the sheet's activity may start. */
|
||||
Activity("activity"),
|
||||
|
||||
/**
|
||||
* Neither: Android blocks an activity started from the background, and says nothing when it
|
||||
* does -- so it is not relied on, and a notification to tap is posted.
|
||||
*/
|
||||
Notification("notification"),
|
||||
|
||||
// A further way (answering by voice without a sheet) would be one more entry here, chosen in
|
||||
// [wakeWay] and carried out where the others are.
|
||||
}
|
||||
|
||||
/** The first way to try, from what is true at that moment. */
|
||||
fun wakeWay(connected: Boolean, screenOn: Boolean, appVisible: Boolean): WakeWay = when {
|
||||
connected && screenOn -> WakeWay.Session
|
||||
connected -> WakeWay.AssistantActivity
|
||||
appVisible -> WakeWay.Activity
|
||||
else -> WakeWay.Notification
|
||||
}
|
||||
|
||||
/** What is left when the assistant's own way did not open the sheet. */
|
||||
fun wakeFallback(appVisible: Boolean): WakeWay = if (appVisible) WakeWay.Activity else WakeWay.Notification
|
||||
|
||||
/**
|
||||
* The assistant service's life in this run of the app, as Android told it: when it was made,
|
||||
* connected (`onReady`), disconnected (`onShutdown`), and when a sheet last came up. Written by
|
||||
* the assistant service, the session and the sheet's activity; read when the word is heard.
|
||||
*/
|
||||
object AssistLink {
|
||||
@Volatile var readyAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var shutdownAt = 0L
|
||||
private set
|
||||
|
||||
private val _shown = MutableStateFlow(0L)
|
||||
|
||||
/** When a sheet last came up, on the phone's elapsed clock (ms); 0: not yet. */
|
||||
val shown: StateFlow<Long> = _shown.asStateFlow()
|
||||
|
||||
private val _connected = MutableStateFlow(false)
|
||||
|
||||
/** Whether Android has the assistant service connected right now. */
|
||||
val connected: StateFlow<Boolean> = _connected.asStateFlow()
|
||||
|
||||
fun ready(now: Long) {
|
||||
readyAt = now
|
||||
_connected.value = true
|
||||
}
|
||||
|
||||
fun shutdown(now: Long) {
|
||||
shutdownAt = now
|
||||
_connected.value = false
|
||||
}
|
||||
|
||||
fun sheetShown(elapsed: Long) {
|
||||
_shown.value = elapsed
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* Listening for the wake word: opt-in (Settings › Assistant › Wake word), off by default.
|
||||
@@ -169,7 +170,13 @@ class WakeWordService : LifecycleService() {
|
||||
engine = { keywords -> WakeEngine.create(this, keywords) },
|
||||
microphone = { PhoneMicrophone() },
|
||||
// A test in Settings takes the word; otherwise the assistant opens.
|
||||
heard = { if (!WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) wake() },
|
||||
heard = { phrase ->
|
||||
if (WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) {
|
||||
record(WakeAttempt(at = System.currentTimeMillis(), phrase = phrase.words, outcome = WakeAttempt.OUT_TESTED))
|
||||
} else {
|
||||
wake(phrase)
|
||||
}
|
||||
},
|
||||
log = { message, cause -> Log.w(TAG, message, cause) },
|
||||
)
|
||||
}
|
||||
@@ -197,25 +204,67 @@ class WakeWordService : LifecycleService() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The word was heard: the assistant opens listening. Through the voice-interaction service
|
||||
* when LLeMbas is the phone's assistant (Android lets it open the sheet from the background);
|
||||
* as an activity while the app is on screen; and otherwise with a notification to tap,
|
||||
* because Android blocks an activity started from the background and says nothing when it
|
||||
* does ([wakeOpening]). The activity is still tried then -- where a phone allows it, it
|
||||
* opens and takes the notification away.
|
||||
* The word was heard: the assistant opens listening, by the first way Android allows
|
||||
* ([wakeWay]) -- and what was tried and how it went is written down ([WakeAttempt], kept in
|
||||
* the settings and shown in Settings › Wake word), because a silent "no" here looks to the
|
||||
* person like a wake word that does not work.
|
||||
*
|
||||
* A way that Android does not refuse is not yet a sheet on screen: the sheet says when it
|
||||
* is up ([AssistLink.shown]), and when it has not said so in time the fallback follows --
|
||||
* the activity while the app is on screen, else a notification to tap (the activity is
|
||||
* still tried then; where a phone allows it, it opens and takes the notification away).
|
||||
*/
|
||||
private fun wake() {
|
||||
private suspend fun wake(phrase: WakePhrase) {
|
||||
// The microphone is the sheet's from here: for a moment by this hold, then for as long as a sheet says it is up.
|
||||
AssistPresence.holdFor(SHEET_GRACE_MS)
|
||||
val session = LembasAssistService.current
|
||||
val shownBySystem = session != null &&
|
||||
runCatching { session.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0) }.isSuccess
|
||||
val opening = wakeOpening(shownBySystem, AppVisibility.visible)
|
||||
if (opening == WakeOpening.Session) return
|
||||
val started = runCatching { startActivity(AssistActivity.listening(this).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.isSuccess
|
||||
if (opening == WakeOpening.Notification || !started) {
|
||||
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this))
|
||||
val asked = SystemClock.elapsedRealtime()
|
||||
val assistant = LembasAssistService.current
|
||||
val way = wakeWay(connected = assistant != null, screenOn = power().isInteractive, appVisible = AppVisibility.visible)
|
||||
var attempt = WakeAttempt(
|
||||
at = System.currentTimeMillis(),
|
||||
phrase = phrase.words,
|
||||
way = way.id,
|
||||
assistant = LembasAssistService.holdsRole(this),
|
||||
readyAt = AssistLink.readyAt,
|
||||
shutdownAt = AssistLink.shutdownAt,
|
||||
)
|
||||
// The assistant's own ways first, where it is connected.
|
||||
val refused: Throwable? = when (way) {
|
||||
WakeWay.Session -> runCatching { assistant?.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0) }.exceptionOrNull()
|
||||
WakeWay.AssistantActivity -> runCatching { assistant?.startActivity(AssistActivity.woken(this)) }.exceptionOrNull()
|
||||
else -> null
|
||||
}
|
||||
if (way == WakeWay.Session || way == WakeWay.AssistantActivity) {
|
||||
if (refused == null && sheetCame(asked)) return record(attempt.copy(outcome = WakeAttempt.OUT_OPENED))
|
||||
attempt = if (refused != null) {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_REFUSED, detail = WakeError(WakeFailure.Engine, refused).detail)
|
||||
} else {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_NO_SHEET)
|
||||
}
|
||||
} else {
|
||||
attempt = attempt.copy(outcome = WakeAttempt.OUT_NOT_CONNECTED)
|
||||
}
|
||||
// Then what is left: the sheet's activity, relied on only while the app is on screen.
|
||||
val fallback = wakeFallback(AppVisibility.visible)
|
||||
val started = runCatching { startActivity(AssistActivity.woken(this)) }
|
||||
if (fallback == WakeWay.Activity && started.isSuccess && sheetCame(asked)) {
|
||||
return record(attempt.copy(fallback = WakeWay.Activity.id))
|
||||
}
|
||||
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this, attempt.assistant))
|
||||
record(attempt.copy(fallback = WakeWay.Notification.id))
|
||||
}
|
||||
|
||||
/** Whether a sheet came up since [asked] (the phone's elapsed clock), waiting a moment for it. */
|
||||
private suspend fun sheetCame(asked: Long): Boolean = withTimeoutOrNull(SHEET_WAIT_MS) { AssistLink.shown.first { it >= asked } } != null
|
||||
|
||||
/** Write [attempt] down: in the log under a fixed tag, and first among the last few in the settings. */
|
||||
private suspend fun record(attempt: WakeAttempt) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"wake word heard: way=${attempt.way} outcome=${attempt.outcome} fallback=${attempt.fallback} assistant=${attempt.assistant} " +
|
||||
"readyAt=${attempt.readyAt} shutdownAt=${attempt.shutdownAt} ${attempt.detail}",
|
||||
)
|
||||
runCatching { lembas.instances.savePrefs { it.copy(wakeLog = wakeLogAdd(it.wakeLog, attempt)) } }
|
||||
}
|
||||
|
||||
private fun power() = getSystemService(PowerManager::class.java)
|
||||
@@ -234,6 +283,9 @@ class WakeWordService : LifecycleService() {
|
||||
private const val NOTIFICATION_ID = 7001
|
||||
const val HEARD_ID = 7002
|
||||
private const val SHEET_GRACE_MS = 3_000L
|
||||
|
||||
/** How long a sheet has to say it is up before the way that was tried counts as not having opened it. */
|
||||
private const val SHEET_WAIT_MS = 2_500L
|
||||
private const val TAG = "LLeMbasWake"
|
||||
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
|
||||
|
||||
@@ -280,12 +332,14 @@ class WakeWordService : LifecycleService() {
|
||||
* "Heard you. Tap to ask.": what the wake word posts when it cannot open the assistant itself.
|
||||
* A fixed sentence, nothing from the account; the tap opens the assistant listening.
|
||||
*/
|
||||
fun wakeHeardNotification(context: Context): Notification {
|
||||
fun wakeHeardNotification(context: Context, assistant: Boolean = false): Notification {
|
||||
val ask = PendingIntent.getActivity(context, 1, AssistActivity.listening(context), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
return NotificationCompat.Builder(context, WakeWordService.CHANNEL_HEARD)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.wake_heard))
|
||||
.setContentText(context.getString(R.string.wake_heard_line))
|
||||
// Why it is a notification and not the sheet, in fixed words: LLeMbas is not the phone's
|
||||
// assistant -- or it is, and could not open by itself this time (Settings says which step said no).
|
||||
.setContentText(context.getString(if (assistant) R.string.wake_heard_could_not else R.string.wake_heard_line))
|
||||
.setContentIntent(ask)
|
||||
.setAutoCancel(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)
|
||||
|
||||
Reference in new issue
Block a user