From 69cfc6270b71e56d0c4f8863c25552b5e8e19062 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Sun, 22 Nov 2026 13:55:45 +0100 Subject: [PATCH] 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 --- .../android/app/src/main/AndroidManifest.xml | 15 +++ .../kuhy/wake_alarm_sync/AlarmScheduler.kt | 2 + .../com/kuhy/wake_alarm_sync/AlarmService.kt | 2 +- .../com/kuhy/wake_alarm_sync/AlarmWatchdog.kt | 2 + .../com/kuhy/wake_alarm_sync/BootReceiver.kt | 2 + .../kotlin/com/kuhy/wake_alarm_sync/Bypass.kt | 5 +- .../com/kuhy/wake_alarm_sync/NotifAlarm.kt | 105 ++++++++++++++++++ .../com/kuhy/wake_alarm_sync/NotifState.kt | 68 ++++++++++++ .../kuhy/wake_alarm_sync/NotifRulesTest.kt | 57 ++++++++++ 9 files changed, 253 insertions(+), 5 deletions(-) create mode 100644 phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/NotifAlarm.kt create mode 100644 phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/NotifState.kt create mode 100644 phone_app/android/app/src/test/kotlin/com/kuhy/wake_alarm_sync/NotifRulesTest.kt diff --git a/phone_app/android/app/src/main/AndroidManifest.xml b/phone_app/android/app/src/main/AndroidManifest.xml index 276e6c6..117cb62 100644 --- a/phone_app/android/app/src/main/AndroidManifest.xml +++ b/phone_app/android/app/src/main/AndroidManifest.xml @@ -94,6 +94,21 @@ + + + + + + + + + = Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !manager.canUseFullScreenIntent() diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/NotifAlarm.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/NotifAlarm.kt new file mode 100644 index 0000000..c6ace80 --- /dev/null +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/NotifAlarm.kt @@ -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) + } +} diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/NotifState.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/NotifState.kt new file mode 100644 index 0000000..73cdd1d --- /dev/null +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/NotifState.kt @@ -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 = + 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) + } +} diff --git a/phone_app/android/app/src/test/kotlin/com/kuhy/wake_alarm_sync/NotifRulesTest.kt b/phone_app/android/app/src/test/kotlin/com/kuhy/wake_alarm_sync/NotifRulesTest.kt new file mode 100644 index 0000000..c0e4ed4 --- /dev/null +++ b/phone_app/android/app/src/test/kotlin/com/kuhy/wake_alarm_sync/NotifRulesTest.kt @@ -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)) + } +}