Notification summaries on request: NotificationListenerService, off by default
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
- LembasNotificationListener keeps nothing; NotificationReader.read takes the notifications up now (not ours, not ongoing, not group summaries; newest 40, 600 chars each, 12k in all) and returns nothing while the phone is locked. - The assistant sends them with one question: its "Summarise my notifications" chip, or a question naming them (assist_notifications_phrases, per language). - Settings › Assistant › Notification summaries: the app's switch (off) and, when on, Android's notification-access page with whether it is given; a privacy paragraph. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
20 files changed
+399
-4
No files matched your search
@@ -15,6 +15,7 @@ import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationReader
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.explain
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -76,6 +77,8 @@ data class AssistUiState(
|
||||
* until the person says stop, taps End, types, or says nothing.
|
||||
*/
|
||||
val conversation: Boolean = false,
|
||||
/** Whether the person let the assistant read the notifications when asked (Settings and Android both). */
|
||||
val canReadNotifications: Boolean = false,
|
||||
) {
|
||||
val screenAvailable: Boolean get() = screenText || screenshot != null
|
||||
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
|
||||
@@ -100,6 +103,7 @@ interface AssistActions {
|
||||
fun readAloud() {}
|
||||
fun stopReading() {}
|
||||
fun endConversation() {}
|
||||
fun summariseNotifications() {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,6 +149,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
signedIn = instance != null,
|
||||
instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(),
|
||||
voiceReply = prefs.readAloudSpoken,
|
||||
canReadNotifications = prefs.notificationSummaries && NotificationReader.granted(context),
|
||||
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
)
|
||||
@@ -366,7 +371,10 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
ask(prompt, spoken = false)
|
||||
}
|
||||
|
||||
fun ask(question: String, spoken: Boolean) {
|
||||
/** The sheet's "Summarise my notifications": the notifications up now go with the question. */
|
||||
override fun summariseNotifications() = ask(context.getString(R.string.assist_notifications_prompt), spoken = false, notifications = true)
|
||||
|
||||
fun ask(question: String, spoken: Boolean, notifications: Boolean = false) {
|
||||
if (question.isBlank()) return
|
||||
if (_state.value.listening) type()
|
||||
following?.cancel()
|
||||
@@ -386,7 +394,19 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
val attachments = buildList {
|
||||
if (withScreen) now.screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot), now.chatId).id) }
|
||||
}
|
||||
val text = if (withScreen && screenText != null) "$question\n\n---\nOn my screen:\n\n$screenText" else question
|
||||
// The notifications, when asked for by the chip or by name ("my notifications") --
|
||||
// read now, only while unlocked (NotificationReader.read), and for this question only.
|
||||
val phrases = context.getString(R.string.assist_notifications_phrases).split("|")
|
||||
val notices = if (now.canReadNotifications && (notifications || NotificationReader.asksAbout(question, phrases))) {
|
||||
NotificationReader.asText(NotificationReader.read(context)).ifBlank { NO_NOTIFICATIONS }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val text = buildString {
|
||||
append(question)
|
||||
if (withScreen && screenText != null) append("\n\n---\nOn my screen:\n\n$screenText")
|
||||
if (notices != null) append("\n\n---\nMy notifications:\n\n$notices")
|
||||
}
|
||||
// The screen goes with one question, not every one after it.
|
||||
_state.update { it.copy(includeScreen = false) }
|
||||
val chatId = now.chatId
|
||||
@@ -523,6 +543,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
|
||||
companion object {
|
||||
const val MAX_SCREEN_CHARS = 8_000
|
||||
private const val NO_NOTIFICATIONS = "(none)"
|
||||
|
||||
// Listening, for the instance's speech-to-text (the phone's recogniser finds the end of
|
||||
// speech itself). Levels are the RMS of 16-bit samples, 0..1: a room is under 0.01,
|
||||
|
||||
@@ -47,6 +47,7 @@ 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.Mic
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.ScreenshotMonitor
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Summarize
|
||||
@@ -443,6 +444,10 @@ private fun Starting(state: AssistUiState, actions: AssistActions, locked: Boole
|
||||
QuickAction(Icons.Filled.Lightbulb, stringResource(R.string.assist_quick_explain)) { actions.quick(explain) }
|
||||
}
|
||||
}
|
||||
// The notifications, read only now that it is asked, and never over the lock screen.
|
||||
if (state.canReadNotifications && !locked) {
|
||||
QuickAction(Icons.Filled.Notifications, stringResource(R.string.assist_notifications)) { actions.summariseNotifications() }
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(stringResource(R.string.assist_help), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
Text(stringResource(R.string.assist_wake_word_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
|
||||
@@ -93,6 +93,8 @@ data class Prefs(
|
||||
val wakePhrase: String = "hey_lembas",
|
||||
/** Listen only while the screen is on. */
|
||||
val wakeScreenOnly: Boolean = true,
|
||||
/** The assistant may read the notifications when asked (with Android's notification access). */
|
||||
val notificationSummaries: Boolean = false,
|
||||
val assistantModel: String = "",
|
||||
val lastAssistChat: String = "",
|
||||
val lastAssistTitle: String = "",
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package eu.llembas.android.notify
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import android.app.Notification
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
|
||||
/**
|
||||
* Notification summaries on request: the assistant reads the notifications on the phone only when
|
||||
* the person asks it to ("summarise my notifications", or the sheet's chip), and sends their text
|
||||
* with that one question. Off by default, twice over: Android's own notification-access switch
|
||||
* (which only the person can turn on, in the system's settings) and Settings › Assistant's.
|
||||
*
|
||||
* The listener keeps nothing: it is how Android lets an app read the notifications that are up
|
||||
* right now ([activeNotifications]), and nothing is read until a question asks for it. Never over
|
||||
* the lock screen ([read] returns nothing while the phone is locked).
|
||||
*/
|
||||
class LembasNotificationListener : NotificationListenerService() {
|
||||
override fun onListenerConnected() {
|
||||
super.onListenerConnected()
|
||||
current = this
|
||||
}
|
||||
|
||||
override fun onListenerDisconnected() {
|
||||
if (current === this) current = null
|
||||
super.onListenerDisconnected()
|
||||
}
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
var current: LembasNotificationListener? = null
|
||||
private set
|
||||
}
|
||||
}
|
||||
|
||||
/** One notification, as the question carries it. */
|
||||
data class Notice(val app: String, val title: String, val text: String, val at: Long)
|
||||
|
||||
object NotificationReader {
|
||||
/** Whether the person gave LLeMbas notification access in the system's settings. */
|
||||
fun granted(context: Context): Boolean = context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
|
||||
|
||||
/** The system's page for this app's notification access (the detail page where Android has one). */
|
||||
fun settingsIntent(context: Context): Intent = if (Build.VERSION.SDK_INT >= 30) {
|
||||
Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS)
|
||||
.putExtra(Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME, ComponentName(context, LembasNotificationListener::class.java).flattenToString())
|
||||
} else {
|
||||
Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
|
||||
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/** The notifications up now, newest first -- or none, when locked or not allowed. */
|
||||
fun read(context: Context): List<Notice> {
|
||||
if (context.getSystemService(KeyguardManager::class.java).isKeyguardLocked) return emptyList()
|
||||
val listener = LembasNotificationListener.current ?: return emptyList()
|
||||
val shown = runCatching { listener.activeNotifications }.getOrNull().orEmpty()
|
||||
return shown
|
||||
.filter { it.packageName != context.packageName && !it.isOngoing && it.notification.flags and Notification.FLAG_GROUP_SUMMARY == 0 }
|
||||
.sortedByDescending { it.postTime }
|
||||
.mapNotNull { notice(context, it) }
|
||||
.take(MAX_NOTICES)
|
||||
}
|
||||
|
||||
private fun notice(context: Context, sbn: StatusBarNotification): Notice? {
|
||||
val extras = sbn.notification.extras
|
||||
val title = extras.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
|
||||
val lines = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES)?.joinToString("\n").orEmpty()
|
||||
val text = (extras.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras.getCharSequence(Notification.EXTRA_TEXT))?.toString()
|
||||
?.ifBlank { null } ?: lines
|
||||
if (title.isBlank() && text.isBlank()) return null
|
||||
val app = runCatching {
|
||||
val pm = context.packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
|
||||
}.getOrDefault(sbn.packageName)
|
||||
return Notice(app, title, text.take(MAX_TEXT), sbn.postTime)
|
||||
}
|
||||
|
||||
/** The notifications as the question's attachment of text: one block per notification. */
|
||||
fun asText(notices: List<Notice>, now: Long = System.currentTimeMillis()): String = notices.joinToString("\n\n") { n ->
|
||||
val minutes = ((now - n.at) / 60_000).coerceAtLeast(0)
|
||||
val ago = if (minutes < 60) "${minutes}m ago" else "${minutes / 60}h ago"
|
||||
listOf("[${n.app} · $ago] ${n.title}".trim(), n.text).filter { it.isNotBlank() }.joinToString("\n")
|
||||
}.take(MAX_CHARS)
|
||||
|
||||
/**
|
||||
* Whether a question asks about the notifications: one of [phrases] (in the app's language,
|
||||
* "my notifications" and the like) is in it.
|
||||
*/
|
||||
fun asksAbout(question: String, phrases: List<String>): Boolean {
|
||||
val q = question.lowercase()
|
||||
return phrases.map { it.trim().lowercase() }.any { it.isNotEmpty() && it in q }
|
||||
}
|
||||
|
||||
private const val MAX_NOTICES = 40
|
||||
private const val MAX_TEXT = 600
|
||||
private const val MAX_CHARS = 12_000
|
||||
}
|
||||
@@ -45,6 +45,7 @@ import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material.icons.filled.RecordVoiceOver
|
||||
import androidx.compose.material.icons.filled.Science
|
||||
import androidx.compose.material.icons.filled.ScreenLockPortrait
|
||||
import androidx.compose.material.icons.filled.Security
|
||||
import androidx.compose.material.icons.filled.SystemUpdate
|
||||
import androidx.compose.material.icons.filled.Timer
|
||||
import androidx.compose.material.icons.filled.Translate
|
||||
@@ -87,6 +88,7 @@ import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationReader
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.update.AppVersion
|
||||
@@ -119,6 +121,8 @@ interface SettingsActions {
|
||||
fun wakePhrase(id: String) {}
|
||||
fun wakeScreenOnly(on: Boolean) {}
|
||||
fun batterySettings() {}
|
||||
fun notificationSummaries(on: Boolean) {}
|
||||
fun notificationAccess() {}
|
||||
fun readAloud(on: Boolean) {}
|
||||
fun checkUpdate() {}
|
||||
fun openRelease() {}
|
||||
@@ -145,6 +149,8 @@ data class SettingsState(
|
||||
val phoneRecognizer: Boolean = false,
|
||||
/** Whether this build has a wake-word engine (the F-Droid build has none). */
|
||||
val wakeAvailable: Boolean = false,
|
||||
/** Whether Android's notification access is given to LLeMbas. */
|
||||
val notificationAccess: Boolean = false,
|
||||
)
|
||||
|
||||
@Composable
|
||||
@@ -258,6 +264,16 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
runCatching { context.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
|
||||
// On: Android's own switch is the person's to flip, so its page opens if it is off.
|
||||
override fun notificationSummaries(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(notificationSummaries = on) } }
|
||||
if (on && !NotificationReader.granted(context)) notificationAccess()
|
||||
}
|
||||
|
||||
override fun notificationAccess() {
|
||||
runCatching { context.startActivity(NotificationReader.settingsIntent(context)) }
|
||||
}
|
||||
|
||||
override fun readAloud(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } }
|
||||
}
|
||||
@@ -313,6 +329,8 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
beta = beta,
|
||||
phoneRecognizer = remember { PhoneRecognizer.available(context) },
|
||||
wakeAvailable = WakeEngine.AVAILABLE,
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
notificationAccess = NotificationReader.granted(context),
|
||||
),
|
||||
actions,
|
||||
onBack,
|
||||
@@ -495,6 +513,7 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
)
|
||||
}
|
||||
item { WakeWordGroup(state, actions) }
|
||||
item { NotificationSummaryGroup(state, actions) }
|
||||
item {
|
||||
// Which recogniser turns speech into words: the instance's or the phone's -- what
|
||||
// each one is, and where the recording goes, said in the row itself.
|
||||
@@ -629,6 +648,38 @@ private fun WakeWordGroup(state: SettingsState, actions: SettingsActions) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Notification summaries: off by default; on needs Android's notification access too, which this explains. */
|
||||
@Composable
|
||||
private fun NotificationSummaryGroup(state: SettingsState, actions: SettingsActions) {
|
||||
val palette = LocalPalette.current
|
||||
val on = state.prefs.notificationSummaries
|
||||
Group(stringResource(R.string.notification_summaries)) {
|
||||
SettingRow(
|
||||
Icons.Filled.Notifications,
|
||||
stringResource(R.string.notification_summaries_switch),
|
||||
subtitle = stringResource(R.string.notification_summaries_line),
|
||||
onClick = { actions.notificationSummaries(!on) },
|
||||
trailing = { Switch(checked = on, onCheckedChange = actions::notificationSummaries) },
|
||||
)
|
||||
if (on) {
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Security,
|
||||
stringResource(R.string.notification_access),
|
||||
subtitle = stringResource(if (state.notificationAccess) R.string.notification_access_on else R.string.notification_access_off),
|
||||
tint = if (state.notificationAccess) null else palette.warning,
|
||||
onClick = actions::notificationAccess,
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.notification_summaries_privacy),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Group(title: String, content: @Composable () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
|
||||
Reference in new issue
Block a user