Report notifications state at 21:00 and on change

NotifState holds the off rule Bypass used (now shared). An exact
21:00 alarm (request code 1007) and a receiver for the app and
ring-channel block broadcasts log a notifications event and push it
through publishNowMain, holding the broadcast 25 s so the headless
engine is not frozen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-22 13:55:45 +01:00
parent 8c511c148c
commit 69cfc6270b
9 changed files with 253 additions and 5 deletions

View File

@ -94,6 +94,21 @@
<receiver
android:name=".PoolSyncReceiver"
android:exported="false"/>
<!-- The 21:00 notifications check (NotifAlarm.kt); not exported,
only this app's own PendingIntent reaches it. -->
<receiver
android:name=".NotifCheckReceiver"
android:exported="false"/>
<!-- Sent by the system to this app only: its notifications or the
ring channel blocked or unblocked in Settings (NotifAlarm.kt). -->
<receiver
android:name=".NotifBlockReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.app.action.APP_BLOCK_STATE_CHANGED"/>
<action android:name="android.app.action.NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED"/>
</intent-filter>
</receiver>
<!-- The silent buzz before a session deadline (SessionWarn.kt). -->
<receiver
android:name=".SessionWarnReceiver"

View File

@ -67,6 +67,8 @@ object AlarmScheduler {
StickAlarm.schedule(context, LocalTime.of(hour, minute))
// Same funnel for the pre-alarm day-pool sync (PoolSyncAlarm.kt).
PoolSyncAlarm.schedule(context, LocalTime.of(hour, minute))
// And the 21:00 notifications check (NotifAlarm.kt).
NotifAlarm.schedule(context)
}
/** Cancels the armed alarm and forgets the stored time. */

View File

@ -40,7 +40,7 @@ class AlarmService : Service() {
companion object {
private const val TAG = "AlarmService"
private const val CHANNEL_ID = "wake_alarm_ring"
private const val CHANNEL_ID = NotifState.RING_CHANNEL_ID
private const val NOTIFICATION_ID = 42
/** Vibration: 1s buzz, 1s gap, repeating from index 0. */

View File

@ -54,6 +54,8 @@ object AlarmWatchdog {
fun verify(context: Context) {
val rearmed = AlarmScheduler.rearmFromStorage(context)
Log.i(TAG, "daily check: rearmed=$rearmed")
// rearmFromStorage arms it too, but only with an alarm stored.
NotifAlarm.schedule(context)
// Third net behind the exact check and boot: within a day, whatever
// dropped the other two, today's miss is still caught here.
StickRunner.run(context, "watchdog")

View File

@ -25,6 +25,8 @@ class BootReceiver : BroadcastReceiver() {
// has to be re-established here or it silently stops after the first
// restart — exactly when a watchdog is most needed.
AlarmWatchdog.schedule(context)
// The 21:00 notifications check, also with no alarm stored.
NotifAlarm.schedule(context)
// A phone switched off before the alarm and back on after A + 15 has
// missed: this is the path that closes that hole (rearmFromStorage
// above has already armed the exact check for a phone back earlier).

View File

@ -43,7 +43,6 @@ object BypassRules {
*/
object Bypass {
private const val TAG = "WakeAlarmBypass"
private const val RING_CHANNEL_ID = "wake_alarm_ring"
// One launch runs the checks from MainActivity and then AlarmActivity
// (emulator, 2026-11-22: two events, two publishes for one revoke).
@ -94,9 +93,7 @@ object Bypass {
/** Checks the permissions the ring needs; a revoked one on a live morning is a bypass. */
fun checkPermissions(context: Context) {
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = manager.getNotificationChannel(RING_CHANNEL_ID)
val blocked = channel != null && channel.importance == NotificationManager.IMPORTANCE_NONE
if (!manager.areNotificationsEnabled() || blocked) {
if (NotifState.off(context)) {
record(context, BypassCause.NOTIFICATIONS_OFF)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
!manager.canUseFullScreenIntent()

View File

@ -0,0 +1,105 @@
package com.kuhy.wake_alarm_sync
import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import java.time.LocalDateTime
import java.time.ZoneId
/**
* The exact daily alarm at [NotifRules.EVENING] (21:00) that runs
* [NotifState.report] (trigger `evening`), so the PC can ring while the
* notifications are still off and there is time to fix them before sleeping.
*
* Same shape as [PoolSyncAlarm]: setExactAndAllowWhileIdle (never an
* alarm-clock entry, which would show as the "next alarm"), inexact when
* exact alarms are refused, its own receiver and request code
* ([REQUEST_CODE]), never [AlarmReceiver], which would ring.
*
* Armed from [AlarmScheduler.schedule] (every arm path: launch, dismiss,
* skip), from [BootReceiver] and from the watchdog, and re-armed by its own
* receiver. Always the next future 21:00 ([NotifRules.nextEvening]), so a
* re-arm never restores an instant that has passed.
*/
object NotifAlarm {
private const val REQUEST_CODE = 1007
private const val TAG = "WakeAlarmNotifAlarm"
/**
* How long a receiver holds its broadcast open after starting the
* publish: a receiver that returns lets Android freeze the headless Dart
* engine mid-request (see [PoolSyncReceiver]). Well inside the 60 s a
* background broadcast may stay open.
*/
const val HOLD_MS = 25_000L
fun schedule(context: Context) {
val at = NotifRules.nextEvening(LocalDateTime.now())
val millis = at.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
Log.i(TAG, "notifications check armed for $at via ${arm(context, millis)}")
}
/** Arms [millis], exactly when permitted; returns which API did it. */
private fun arm(context: Context, millis: Long): String {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val exactAllowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
manager.canScheduleExactAlarms()
if (exactAllowed) {
try {
manager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
millis,
pendingIntent(context),
)
return "setExactAndAllowWhileIdle"
} catch (e: SecurityException) {
Log.w(TAG, "exact alarm refused; arming inexact", e)
}
}
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, millis, pendingIntent(context))
return "setAndAllowWhileIdle"
}
/** Holds [receiver]'s broadcast open for [HOLD_MS], then lets it go. */
fun hold(receiver: BroadcastReceiver) {
val pending = receiver.goAsync()
Handler(Looper.getMainLooper()).postDelayed({ pending.finish() }, HOLD_MS)
}
private fun pendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, NotifCheckReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
/** Receives [NotifAlarm]: re-arms tomorrow's first, so a crash below cannot end the chain. */
class NotifCheckReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
NotifAlarm.schedule(context)
NotifAlarm.hold(this)
NotifState.report(context, "evening")
}
}
/**
* The app's notifications, or the ring channel, blocked or unblocked in
* Settings. The system sends both to this app alone; switching them back on
* publishes `enabled=true` at once, which stops the PC's evening ring.
*/
class NotifBlockReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val channel = intent.getStringExtra(NotificationManager.EXTRA_NOTIFICATION_CHANNEL_ID)
val trigger = NotifRules.trigger(intent.action, channel) ?: return
NotifAlarm.hold(this)
NotifState.report(context, trigger)
}
}

View File

@ -0,0 +1,68 @@
package com.kuhy.wake_alarm_sync
import android.app.NotificationManager
import android.content.Context
import android.util.Log
import java.time.LocalDateTime
import java.time.LocalTime
/** The notifications check's rules as pure functions; [NotifState] gathers the inputs. */
object NotifRules {
/** When the evening check runs: early enough to fix it before sleeping. */
val EVENING: LocalTime = LocalTime.of(21, 0)
/**
* Off when the app's notifications are blocked or the ring channel is set
* to none. A channel not created yet ([ringImportance] null) is not a block.
*/
fun off(appEnabled: Boolean, ringImportance: Int?): Boolean =
!appEnabled || ringImportance == NotificationManager.IMPORTANCE_NONE
/** The next [EVENING] strictly after [now]: never one that has passed. */
fun nextEvening(now: LocalDateTime): LocalDateTime {
val tonight = now.toLocalDate().atTime(EVENING)
return if (tonight.isAfter(now)) tonight else tonight.plusDays(1)
}
/** The `notifications` event's data. */
fun eventData(enabled: Boolean, trigger: String): Map<String, Any?> =
mapOf("enabled" to enabled, "trigger" to trigger)
/** The event trigger for a block-state broadcast, or null when it is not about the ring. */
fun trigger(action: String?, channelId: String?): String? = when (action) {
NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED -> "app_block"
NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED ->
if (channelId == NotifState.RING_CHANNEL_ID) "channel_block" else null
else -> null
}
}
/**
* Whether the ring can show at all: "All WakeAlarm notifications" switched
* off, or the ring channel blocked, silences it, and no device policy can
* lock that switch (2026-11-22).
*
* Two readers: [Bypass.checkPermissions] at ring time (a bypass), and
* [report] at 21:00 ([NotifAlarm]) and whenever the switch moves
* ([NotifBlockReceiver]), which logs a `notifications` event and pushes it
* at once so the PC rings in the evening while it is still off.
*/
object NotifState {
const val RING_CHANNEL_ID = "wake_alarm_ring"
private const val TAG = "WakeAlarmNotif"
/** Whether notifications that the ring needs are switched off now. */
fun off(context: Context): Boolean {
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = manager.getNotificationChannel(RING_CHANNEL_ID)
return NotifRules.off(manager.areNotificationsEnabled(), channel?.importance)
}
/** Logs the state as a `notifications` event and publishes it now. Main thread. */
fun report(context: Context, trigger: String) {
val enabled = !off(context)
Log.i(TAG, "notifications enabled=$enabled ($trigger)")
EventLog.append(context, "notifications", NotifRules.eventData(enabled, trigger))
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
}
}

View File

@ -0,0 +1,57 @@
package com.kuhy.wake_alarm_sync
import android.app.NotificationManager
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.LocalDateTime
/** The 21:00 notifications check (2026-11-22): when it runs and what it says. */
class NotifRulesTest {
private fun at(day: Int, hour: Int, minute: Int = 0, second: Int = 0) =
LocalDateTime.of(2026, 11, day, hour, minute, second)
@Test
fun beforeNineTheCheckIsTonight() {
assertEquals(at(22, 21), NotifRules.nextEvening(at(22, 3)))
assertEquals(at(22, 21), NotifRules.nextEvening(at(22, 20, 59, 59)))
}
@Test
fun theInstantThatJustFiredIsNeverReturned() {
assertEquals(at(23, 21), NotifRules.nextEvening(at(22, 21)))
assertEquals(at(23, 21), NotifRules.nextEvening(at(22, 23, 59)))
}
@Test
fun offWhenTheAppIsBlockedOrTheRingChannelIsNone() {
assertTrue(NotifRules.off(appEnabled = false, ringImportance = null))
assertTrue(
NotifRules.off(appEnabled = true, ringImportance = NotificationManager.IMPORTANCE_NONE),
)
assertFalse(
NotifRules.off(appEnabled = true, ringImportance = NotificationManager.IMPORTANCE_HIGH),
)
// The channel is created at the first ring; none yet is not a block.
assertFalse(NotifRules.off(appEnabled = true, ringImportance = null))
}
@Test
fun theEventCarriesEnabledAndTheTrigger() {
assertEquals(
mapOf("enabled" to false, "trigger" to "evening"),
NotifRules.eventData(enabled = false, trigger = "evening"),
)
}
@Test
fun onlyTheAppOrTheRingChannelCounts() {
val app = NotificationManager.ACTION_APP_BLOCK_STATE_CHANGED
val channel = NotificationManager.ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED
assertEquals("app_block", NotifRules.trigger(app, null))
assertEquals("channel_block", NotifRules.trigger(channel, NotifState.RING_CHANNEL_ID))
assertEquals(null, NotifRules.trigger(channel, "wake_alarm_session"))
assertEquals(null, NotifRules.trigger("android.intent.action.BOOT_COMPLETED", null))
}
}