Wake word with the screen off: the sheet stays over the lock screen and listens
CI / check (push) Canceled after 0s

A phone whose screen is off is locked. AssistActivity.take() sent every
locked opening through requestDismissKeyguard and finished the activity on
onDismissCancelled / onDismissError -- which is Android's answer when nobody
unlocks. So the wake word lit the screen, showed the sheet, and closed it.

lockedStart() decides now: a way in that means to speak (the wake word, a
headset's button) stays and listens; what is heard is held in the state
(waiting), shown as the person's own question with "Unlock to send", and
Android is asked to unlock at once. Not unlocking leaves the sheet as it is.
The question is asked on unlock (the dismiss callback or USER_PRESENT). The
other locked openings ask to unlock first, as before.

Nothing from the account over the lock screen still holds, and a little more
than before: turns that were on the sheet when the phone locked are not
drawn while it is locked (onStart reads the keyguard again), and a sheet
over the lock screen goes when the screen goes off. The screen is kept on
while it listens or works.

The session (screen on, locked) listens over the lock screen as well and
hands what it heard to the activity.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-13 14:30:41 +00:00
1 parent 7ca44ef5e2
commit 5e45293462
19 files changed
+303 -26

No files matched your search

@@ -3,10 +3,13 @@ package eu.llembas.android.assist
import android.Manifest
import android.app.KeyguardManager
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.SystemClock
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
@@ -14,6 +17,7 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import eu.llembas.android.AppLanguage
import eu.llembas.android.auth.Prefs
@@ -22,6 +26,9 @@ 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
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
/** What a way into the sheet asks for. */
@@ -51,13 +58,45 @@ enum class Opening {
}
}
/** How the sheet starts, given whether the phone is locked. */
enum class LockedStart {
/** Not locked: do what the way in asked for. */
Go,
/** Locked, and the way in means to speak: stay over the lock screen and listen; what is heard waits for the unlock. */
Listen,
/** Locked, with a question handed over: it is shown and waits for the unlock. */
Hold,
/** Locked, anything else: ask Android to unlock first; the sheet goes if that is turned down. */
Unlock,
}
/**
* What a sheet opened while the phone is [locked] does. The wake word with the screen off, and a
* headset's button, open it listening ([Opening.Listen]) and nobody is there to unlock: asking
* Android to unlock first -- and closing when that is cancelled, which is what happens when
* nobody answers the lock screen -- showed the sheet for a moment and took it away again. So it
* stays and listens, and only *sending* waits for the unlock. Without the microphone's
* permission there is nothing to listen with, and its prompt needs the phone unlocked anyway.
*/
fun lockedStart(locked: Boolean, opening: Opening, question: Boolean, micAllowed: Boolean): LockedStart = when {
!locked -> LockedStart.Go
question -> LockedStart.Hold
opening == Opening.Listen && micAllowed -> LockedStart.Listen
else -> LockedStart.Unlock
}
/**
* The assistant as an activity: what the Quick Settings tile, the "Ask" shortcut and a plain
* `ACTION_ASSIST` open, and where the voice-interaction session hands over what needs an
* activity -- a question asked over the lock screen, or the microphone's permission prompt
* ([EXTRA_LISTEN]). The same sheet as the session's, in a see-through window over the app
* underneath. Shown over the lock screen, but it asks Android to unlock before it sends
* anything -- and shows nothing from the account until then.
* anything -- and shows nothing from the account until then. Opened there to listen (the wake
* word, a headset's button) it stays up and listens; the question it heard is shown and waits
* for the unlock ([lockedStart]).
*/
class AssistActivity : ComponentActivity() {
private lateinit var controller: AssistController
@@ -71,6 +110,20 @@ class AssistActivity : ComponentActivity() {
if (granted) controller.listen()
}
/**
* The phone was unlocked by the person themselves (a fingerprint while the sheet is up): the
* question that waited is sent. And the screen went off over the lock screen: the sheet goes,
* so that it is not what the phone shows when it is next picked up.
*/
private val screen = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_USER_PRESENT -> unlockedNow()
Intent.ACTION_SCREEN_OFF -> if (locked.value) finish()
}
}
}
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
@@ -80,6 +133,28 @@ class AssistActivity : ComponentActivity() {
controller = AssistController(this, lifecycleScope)
keyguard = getSystemService(KeyguardManager::class.java)
locked.value = keyguard.isKeyguardLocked
ContextCompat.registerReceiver(
this,
screen,
IntentFilter().apply {
addAction(Intent.ACTION_USER_PRESENT)
addAction(Intent.ACTION_SCREEN_OFF)
},
ContextCompat.RECEIVER_NOT_EXPORTED,
)
// A question waits for the unlock: Android is asked for it at once (a face or a
// fingerprint is then enough), and the sheet stays if nobody answers.
lifecycleScope.launch {
controller.state.map { it.waiting }.distinctUntilChanged().collect { waiting ->
if (waiting.isNotBlank() && locked.value) askToUnlock()
}
}
// The lock screen turns the display off after a few seconds: not in the middle of a question.
lifecycleScope.launch {
controller.state.map { it.listening || it.busy }.distinctUntilChanged().collect { on ->
if (on) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
// 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).
woken(intent)
@@ -91,15 +166,9 @@ class AssistActivity : ComponentActivity() {
controller = controller,
locked = locked.value,
onUnlockAndAsk = { text ->
keyguard.requestDismissKeyguard(
this@AssistActivity,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
locked.value = false
if (text.isBlank()) controller.opened(locked = false) else controller.ask(text)
}
},
)
askToUnlock(askWaiting = text.isBlank()) {
if (text.isBlank()) controller.opened(locked = false) else controller.ask(text)
}
},
onOpenApp = {
startActivity(controller.appIntent())
@@ -107,6 +176,7 @@ class AssistActivity : ComponentActivity() {
},
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
onDismiss = { finish() },
onUnlock = { askToUnlock() },
)
}
}
@@ -140,6 +210,8 @@ class AssistActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
started = true
// The phone may have locked, or been unlocked, while the sheet was out of sight.
if (keyguard.isKeyguardLocked) locked.value = true else unlockedNow()
open = WeakReference(this)
AssistPresence.shown()
AssistLink.sheetShown(SystemClock.elapsedRealtime())
@@ -156,28 +228,37 @@ class AssistActivity : ComponentActivity() {
/**
* What the way in asked for: a question handed over by the session, listening (the headset's
* voice button, the widget's microphone, the Speak shortcut), the last assistant chat (the
* widget, the shortcut), or just the sheet. Over the lock screen each waits for Android to
* unlock first.
* voice button, the widget's microphone, the Speak shortcut, the wake word), the last
* assistant chat (the widget, the shortcut), or just the sheet. Over the lock screen:
* [lockedStart].
*/
private fun take(intent: Intent) {
val opening = Opening.of(intent)
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
val go = {
when {
waiting.isNotBlank() -> controller.ask(waiting)
waiting.isNotBlank() -> controller.ask(waiting, spoken = intent.getBooleanExtra(EXTRA_SPOKEN, false))
opening == Opening.Continue -> controller.continueWhenReady()
opening == Opening.Listen && !controller.micAllowed() -> mic.launch(Manifest.permission.RECORD_AUDIO)
opening == Opening.Listen -> controller.opened(locked = false, listen = true)
else -> controller.opened(locked = false)
}
}
if (keyguard.isKeyguardLocked) {
keyguard.requestDismissKeyguard(
val isLocked = keyguard.isKeyguardLocked
if (isLocked) locked.value = true
when (lockedStart(isLocked, opening, waiting.isNotBlank(), controller.micAllowed())) {
LockedStart.Go -> go()
LockedStart.Listen -> controller.listenOverLock()
// Shown, and Android asked to unlock (the collector in onCreate): it stays if nobody does.
LockedStart.Hold -> controller.hold(waiting, spoken = intent.getBooleanExtra(EXTRA_SPOKEN, false))
LockedStart.Unlock -> keyguard.requestDismissKeyguard(
this,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
locked.value = false
unlockedNow()
go()
}
@@ -186,12 +267,35 @@ class AssistActivity : ComponentActivity() {
override fun onDismissError() = finish()
},
)
} else {
go()
}
}
/**
* Ask Android to unlock. When it does, the question that waited is sent (unless [askWaiting]
* says another takes its place) and [then] runs. When it does not -- nobody there, or Back
* on the lock screen -- nothing happens: the sheet stays as it is, with the way to try again.
*/
private fun askToUnlock(askWaiting: Boolean = true, then: () -> Unit = {}) {
keyguard.requestDismissKeyguard(
this,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
unlockedNow(askWaiting)
then()
}
},
)
}
/** The phone is unlocked now, however that came about: once. */
private fun unlockedNow(askWaiting: Boolean = true) {
if (!locked.value) return
locked.value = false
controller.unlocked(ask = askWaiting)
}
override fun onDestroy() {
runCatching { unregisterReceiver(screen) }
controller.close()
super.onDestroy()
}
@@ -199,6 +303,9 @@ class AssistActivity : ComponentActivity() {
companion object {
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
/** With [EXTRA_QUESTION]: it was spoken, and is answered as a spoken one. */
const val EXTRA_SPOKEN = "eu.llembas.android.SPOKEN"
/** Handed over by the session: ask for the microphone, then listen. */
const val EXTRA_LISTEN = "eu.llembas.android.LISTEN"
@@ -88,6 +88,11 @@ data class AssistUiState(
val conversation: Boolean = false,
/** Whether the person let the assistant read the notifications when asked (Settings and Android both). */
val canReadNotifications: Boolean = false,
/**
* A question that waits for the phone to be unlocked: heard (or typed) over the lock screen,
* the person's own words and nothing from the account. Asked once the phone is unlocked.
*/
val waiting: String = "",
) {
val screenAvailable: Boolean get() = screenText || screenshot != null
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
@@ -155,6 +160,12 @@ class AssistController(private val context: Context, private val scope: Coroutin
* that chat's own; a new chat goes back to this one.
*/
private var newChatModel: String? = null
/** Over the lock screen: what is heard is held ([AssistUiState.waiting]), not asked. */
private var overLock = false
/** Whether the held question was spoken (and is answered aloud like one). */
private var waitingSpoken = false
private val ready: Job
init {
@@ -227,6 +238,36 @@ class AssistController(private val context: Context, private val scope: Coroutin
}
}
/**
* The sheet came up over the lock screen by a way in that means to speak -- the wake word, a
* headset's button: it listens, and what it hears is held for the unlock ([hold]), never
* asked from here. The reply is not for the lock screen (nothing from the account shows there).
*/
fun listenOverLock() {
overLock = true
scope.launch {
ready.join()
val s = _state.value
if (overLock && s.signedIn && s.canListen && !s.listening && s.waiting.isBlank() && micAllowed()) listen()
}
}
/** Keep [question] until the phone is unlocked ([unlocked]). */
fun hold(question: String, spoken: Boolean) {
if (question.isBlank()) return
overLock = true
waitingSpoken = spoken
_state.update { it.copy(waiting = question, conversation = false) }
}
/** The phone is unlocked: the question that waited is asked now -- unless [ask] says another one takes its place. */
fun unlocked(ask: Boolean = true) {
overLock = false
val waited = _state.value.waiting
_state.update { it.copy(waiting = "") }
if (ask && waited.isNotBlank()) ask(waited, spoken = waitingSpoken)
}
/** Open at the last assistant chat, once it is known which that is. */
fun continueWhenReady() {
scope.launch {
@@ -416,6 +457,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
/** What was said: in a conversation, "stop" (or the like) ends it; anything else is asked. */
private fun askOrStop(words: String) {
if (overLock) return hold(words, spoken = true)
val phrases = context.getString(R.string.assist_stop_words).split("|")
if (_state.value.conversation && isStopPhrase(words, phrases)) endConversation() else ask(words, spoken = true)
}
@@ -18,6 +18,7 @@ fun AssistPanel(
onOpenApp: () -> Unit,
onNeedMic: () -> Unit,
onDismiss: () -> Unit,
onUnlock: () -> Unit = {},
) {
val state by controller.state.collectAsState()
AssistSheetFrame(onDismiss = onDismiss) { handle, _ ->
@@ -27,6 +28,7 @@ fun AssistPanel(
locked = locked,
handle = handle,
onOpenApp = onOpenApp,
onUnlock = onUnlock,
onSend = { text -> if (locked) onUnlockAndAsk(text) else controller.ask(text) },
onMic = {
when {
@@ -36,9 +36,11 @@ import eu.llembas.android.wake.AssistPresence
import eu.llembas.android.wake.wakeLogConnected
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@@ -144,6 +146,9 @@ class LembasAssistSession(context: Context) :
/** Whether this session's sheet is up, as far as the wake word's pause is concerned. */
private var up = false
/** Over the lock screen: waiting for what is heard, to hand it to the sheet's activity. */
private var handing: Job? = null
override val lifecycle: Lifecycle get() = registry
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
@@ -203,7 +208,18 @@ class LembasAssistSession(context: Context) :
// this one was slow to come, goes now that this one is here.
AssistActivity.closeWoken()
// The wake word asks for the sheet listening, whatever Settings says about opening.
controller.opened(locked(), listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
val listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true
if (listen && locked()) {
// Over the lock screen too: it listens, and what it hears goes to the sheet's
// activity, which shows it and asks Android to unlock before anything is sent.
val showing = controller
showing.listenOverLock()
// Once: Android may call onShow again while the sheet is up.
handing?.cancel()
handing = scope.launch { handOff(showing.state.map { it.waiting }.first { it.isNotBlank() }, spoken = true) }
} else {
controller.opened(locked(), listen = listen)
}
}
/**
@@ -261,10 +277,11 @@ class LembasAssistSession(context: Context) :
* which asks Android to unlock first and only then sends it. The microphone's permission
* prompt needs an activity too.
*/
private fun handOff(text: String, listen: Boolean = false) {
private fun handOff(text: String, listen: Boolean = false, spoken: Boolean = false) {
startAssistantActivity(
Intent(context, AssistActivity::class.java)
.putExtra(AssistActivity.EXTRA_QUESTION, text)
.putExtra(AssistActivity.EXTRA_SPOKEN, spoken)
.putExtra(AssistActivity.EXTRA_LISTEN, listen)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
@@ -46,6 +46,7 @@ import androidx.compose.material.icons.filled.Forum
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Keyboard
import androidx.compose.material.icons.filled.Lightbulb
import androidx.compose.material.icons.filled.LockOpen
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.ScreenshotMonitor
@@ -197,7 +198,9 @@ fun AssistSheetFrame(onDismiss: () -> Unit, content: @Composable ColumnScope.(ha
* - **the foot**: Use screen, then the microphone first -- while listening, the words as they are
* heard and how loud -- or the words typed, and Send.
*
* Nothing from the account is on it while the phone is [locked]: no model list, no last chat.
* Nothing from the account is on it while the phone is [locked]: no model list, no last chat,
* no question asked earlier and no answer. A question heard over the lock screen is shown -- the
* person's own words -- with the way to unlock, which sends it ([onUnlock]).
*/
@Composable
fun ColumnScope.AssistSheetContent(
@@ -206,6 +209,7 @@ fun ColumnScope.AssistSheetContent(
locked: Boolean,
handle: Modifier = Modifier,
onOpenApp: () -> Unit = {},
onUnlock: () -> Unit = {},
onSend: (String) -> Unit = actions::ask,
onMic: () -> Unit = actions::listen,
) {
@@ -267,10 +271,15 @@ fun ColumnScope.AssistSheetContent(
Modifier.weight(1f).fillMaxWidth().verticalScroll(scroll).padding(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
if (state.empty) {
Starting(state, actions, locked)
} else {
state.turns.forEachIndexed { i, turn ->
when {
locked && state.waiting.isNotBlank() -> Waiting(state.waiting, onUnlock)
// A conversation that was on the sheet when the phone locked: not for the lock screen.
locked && !state.empty -> Text(stringResource(R.string.assist_locked_line), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
state.empty -> Starting(state, actions, locked)
else -> state.turns.forEachIndexed { i, turn ->
Turn(turn, last = i == state.turns.lastIndex, state, actions, onOpenApp)
}
}
@@ -468,6 +477,31 @@ private fun QuickAction(icon: androidx.compose.ui.graphics.vector.ImageVector, l
)
}
/**
* Over the lock screen: the question that was heard, as its bubble, and the one thing to do about
* it. Unlocking sends it; nothing is sent and no answer shown before.
*/
@Composable
private fun Waiting(question: String, onUnlock: () -> Unit) {
val palette = LocalPalette.current
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
Surface(color = palette.bubbleUser, contentColor = palette.ink, shape = RoundedCornerShape(20.dp), modifier = Modifier.widthIn(max = 300.dp)) {
Text(question, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
}
}
Text(stringResource(R.string.assist_locked_line), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
AssistChip(
onClick = onUnlock,
label = { Text(stringResource(R.string.assist_unlock_to_send)) },
leadingIcon = { Icon(Icons.Filled.LockOpen, contentDescription = null, modifier = Modifier.size(18.dp)) },
colors = AssistChipDefaults.assistChipColors(containerColor = palette.surfaceRaised, leadingIconContentColor = palette.accent),
border = BorderStroke(1.dp, palette.border),
modifier = Modifier.heightIn(min = 48.dp),
)
}
}
/** One question, as a bubble on the right, and its answer at full width -- as in the app's chats. */
@Composable
private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions: AssistActions, onOpenApp: () -> Unit) {