We're building ReClaim, a minimalist Android launcher that's on Google Play. The newest thing we've built for its Home screen is a practice timer: you name something you want to spend time on, like reading, and tap its Home icon to start a countdown or a stopwatch. A practice can also hold a few apps until it ends, mark a habit when it's done, and turn on Do Not Disturb while it runs.
That last option is the subject of this post. Turning Do Not Disturb on is one line of code. Turning it back off correctly is the actual work, because the phone's notification mode isn't ours. It belongs to the user, and the timer is only borrowing it. This is how our code records what it borrowed, pays it back when the process dies or the coroutine doing the paying gets cancelled, keeps that state out of backups, and where Android 15 changed the rules under us.
Stack: Kotlin, Jetpack Compose, Hilt, Room, coroutines, minSdk 26, targetSdk 36. All code below is copied from the repo.
The permission is a settings page, not a dialog
To change Do Not Disturb, an app declares android.permission.ACCESS_NOTIFICATION_POLICY. The Manifest.permission reference calls it a marker permission with protection level normal, so declaring it grants nothing by itself. The real switch is a per-app toggle the user flips in system settings, and the app checks it with NotificationManager.isNotificationPolicyAccessGranted().
The Settings reference for ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS says "a matching Activity may not exist, so ensure you safeguard against this", and that managed profiles can't grant this access at all. So the intent is wrapped, and there's no result to wait for. We re-read the grant every time Home resumes:
@Composable
fun RefreshNotificationAccess(viewModel: WidgetsViewModel) {
val owner = LocalLifecycleOwner.current
LaunchedEffect(viewModel) { viewModel.refreshNotificationAccess() }
DisposableEffect(owner, viewModel) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) viewModel.refreshNotificationAccess()
}
owner.lifecycle.addObserver(observer)
onDispose { owner.lifecycle.removeObserver(observer) }
}
}
fun openNotificationPolicySettings(context: Context) {
val intent = Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
if (context !is Activity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
runCatching { context.startActivity(intent) }
}
If the user never grants it, the practice still runs. The running card just says "Notifications are still on." and offers an "Allow Do Not Disturb" button. Silence is optional. It shouldn't block the feature.
Borrow, don't set
All Do Not Disturb access goes through one small class:
@Singleton
class NotificationSilencer @Inject constructor(
@ApplicationContext context: Context,
) {
private val notifications = context.getSystemService(NotificationManager::class.java)
fun canSilence(): Boolean = notifications.isNotificationPolicyAccessGranted
/** Returns the filter to restore later, or null when the system would not allow the change. */
fun silence(): Int? {
if (!canSilence()) return null
val previous = notifications.currentInterruptionFilter
return runCatching {
notifications.setInterruptionFilter(quietFilter())
previous
}.getOrNull()
}
/** Re-applies the quiet mode after the process died, without forgetting the original filter. */
fun ensureSilenced() {
if (!canSilence()) return
val target = quietFilter()
if (notifications.currentInterruptionFilter == target) return
runCatching { notifications.setInterruptionFilter(target) }
}
fun restore(previous: Int) {
if (previous < 0 || !canSilence()) return
runCatching { notifications.setInterruptionFilter(previous) }
}
private fun quietFilter(): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
NotificationManager.INTERRUPTION_FILTER_ALARMS
} else {
NotificationManager.INTERRUPTION_FILTER_PRIORITY
}
}
The important part is the shape of silence(). It never just sets a mode. It reads the current filter first and hands it back to the caller as a debt to repay. A user who already had priority-only mode on before starting should get priority-only back, not "everything allowed".
The quiet mode is INTERRUPTION_FILTER_ALARMS. The NotificationManager reference defines it as "all notifications except those of category Notification.CATEGORY_ALARM are suppressed". Waking up on time matters more than a clean session.
One thing in that class we can't back up with docs yet. The comment says Android 8 has no alarms-only mode, so it falls back to INTERRUPTION_FILTER_PRIORITY below API 28. But the same reference lists all the INTERRUPTION_FILTER_* constants, including ALARMS, as added in API level 23. Either there's device behavior we saw and didn't write down, or the branch is unnecessary. Until we test on an Android 8 phone, it stays, and it's on the open list.
Write the debt down where the process can't lose it
A launcher's process lives a long time, but it isn't immortal. If the filter to restore lived only in memory, a process death mid-session would leave Do Not Disturb on with nobody left who remembers it should come off. So the debt goes into the session row in Room:
/**
* One stretch of time on a practice. [endedAt] is null only while it is still running.
* [plannedMillis] is the countdown length, or null when the session counts up.
* [previousInterruptionFilter] is the Do Not Disturb mode to restore, or -1 when this session
* did not change it. [blockPackages] are held only until the session ends, separate from a
* block the user set themselves, because stopping the practice must lift them.
*/
@Entity(tableName = "practice_sessions")
data class PracticeSessionEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val practiceId: Long,
val startedAt: Long,
val endedAt: Long?,
val plannedMillis: Long?,
val previousInterruptionFilter: Int,
val silenceNotifications: Boolean,
val blockPackages: String,
)
-1 means "we didn't touch it", so every restore path can tell a session that silenced the phone from one that didn't (because access was missing or the call failed). The start path does things in a deliberate order:
if (open != null) finishLocked(open, now)
val practice = dao.find(practiceId) ?: return@withLock false
val planned = if (practice.mode == PracticeMode.COUNTDOWN.name) {
practice.durationMinutes.coerceAtLeast(1) * 60_000L
} else {
null
}
val previous = if (practice.silenceNotifications) silencer.silence() ?: -1 else -1
Starting a practice while another one runs finishes the old session first, and that restores its filter. Only then does silence() read the current filter. Swap those two lines and the new session would record the old session's quiet mode as the user's own, and Do Not Disturb would never come off.
Paying it back when the payer is the one being cancelled
Every way a session ends, whether that's stop, delete, the countdown finishing or a new start, goes through one function, under a Mutex:
private suspend fun finishLocked(
session: PracticeSessionEntity,
endedAt: Long,
markHabit: Boolean = true,
) {
val job = endJob
endJob = null
if (job != null && job != coroutineContext[Job]) job.cancel()
cancelAlarm()
// The countdown job is the caller when it reaches its end. Cancelling it and then
// suspending would drop the save and leave notifications silenced.
withContext(NonCancellable) {
val end = endedAt.coerceAtLeast(session.startedAt)
dao.updateSession(session.copy(endedAt = end))
if (session.previousInterruptionFilter >= 0) silencer.restore(session.previousInterruptionFilter)
if (markHabit) markLinkedHabit(session, end)
}
}
The countdown is a coroutine that sleeps until the planned end and then calls into this function. So sometimes the job being cleaned up is the one doing the cleanup. In coroutines, cancellation lands at the next suspension point, and the Room write is a suspension point. Without protection, a cancelled caller could skip both the save and the restore, which is exactly the "Do Not Disturb stuck on" bug.
The code does two things about it. It doesn't cancel the job when the job is itself the caller. And the write-and-restore block runs in withContext(NonCancellable), which the kotlinx.coroutines docs describe as "designed for withContext function to prevent cancellation of code blocks that need to be executed without cancellation". The same page warns against using it with launch, which we don't.
Two clocks, and a cold start that reconciles
A countdown arms an in-process delay and a backup alarm. We went into this two-clock race in detail in our post on racing AlarmManager with a coroutine, so here's just the alarm half:
private fun armAlarm(endsAt: Long?) {
val pending = pendingIntent()
if (endsAt == null) {
alarmManager.cancel(pending)
return
}
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, endsAt, pending)
}
The AlarmManager reference says the system won't dispatch these alarms "more than about every minute" normally, and in idle the gap can be much longer, "such as 15 minutes". That's fine here. The alarm is a safety net for a dead process, not the clock the user sees. The receiver it targets isn't exported, the PendingIntent is immutable, and it uses goAsync() so the Room write and the restore happen off the main thread. The BroadcastReceiver reference notes that the broadcast time limit still covers everything up to finish(), and our work is one row and one system call.
When the repository is created in a fresh process, it reconciles:
suspend fun reconcile() = mutex.withLock {
val open = dao.open() ?: return@withLock
val plannedEnd = open.plannedMillis?.let { open.startedAt + it }
val now = System.currentTimeMillis()
if (plannedEnd != null && now >= plannedEnd) {
finishLocked(open, plannedEnd)
return@withLock
}
if (open.previousInterruptionFilter >= 0) silencer.ensureSilenced()
armAlarm(plannedEnd)
armInProcess(plannedEnd)
}
An overdue countdown closes at its planned end, not at "now", so a late alarm doesn't credit extra minutes. A session still running gets its quiet mode re-applied with ensureSilenced(), which doesn't touch the stored "previous" value. Reading the current filter there would record our own quiet mode as the user's.
Reboots are a known gap. The AlarmManager reference says alarms "will be cleared if it is turned off and rebooted", and our boot receiver only re-arms app reminders, not practices. In practice the launcher comes back as Home after a reboot, and Home drawing the practice icon creates the repository, which runs reconcile(). That only holds while ReClaim is the default Home app and the practice icon is switched on.
A backup must not carry the debt to another phone
ReClaim's backup includes practice history, and a backup can move a whole setup to another phone. A copied session row with a live previousInterruptionFilter would mean the new phone "restores" a mode from the old one. So the writer closes any open session at the moment of the backup and erases the debt:
private fun PracticeSessionEntity.toJson() = JSONObject().apply {
// A backup is a snapshot, not a live timer. Close an open session at this moment so the
// other phone does not inherit Do Not Disturb or a countdown that belongs here.
val plannedEnd = plannedMillis?.let { startedAt + it }
val end = endedAt ?: plannedEnd?.let { minOf(System.currentTimeMillis(), it) } ?: System.currentTimeMillis()
put("id", id)
put("practiceId", practiceId)
put("startedAt", startedAt)
put("endedAt", end)
put("plannedMillis", plannedMillis ?: JSONObject.NULL)
put("previousInterruptionFilter", -1)
put("silenceNotifications", silenceNotifications)
put("blockPackages", blockPackages)
}
The reader forces -1 too, so even a hand-edited file can't bring one back.
Android 15 changed what "set" means
This is the part we got wrong on paper. The Android 15 behavior changes say apps targeting API 35 and higher "can no longer change the global state or policy of Do Not Disturb". Instead, setInterruptionFilter creates or updates "an implicit AutomaticZenRule", which the system combines with other rules under a "most-restrictive-policy-wins scheme". The setInterruptionFilter reference says the call will "activate or deactivate an AutomaticZenRule associated to the app".
We target 36, so on Android 15 and newer we aren't borrowing the user's mode anymore. We're switching our own rule on and off. In the common case, where nothing was silenced before, that changes nothing: we read ALL, restore ALL, and our rule switches off. The edge case is a user who already had Do Not Disturb on. Our code reads the global filter, say priority-only, and at the end "restores" it by setting priority-only on our own rule. As we read the docs, that leaves our rule active after the session, and it could keep the phone quiet after the user turns their own mode off. We haven't confirmed this on a device yet. Either way, the right repayment on Android 15+ is "switch my rule off", not "write back the old global value".
What's still open
None of these are fixed in the current code:
- Restoring a backup during a running practice. The restore clears every session row, including the open one that holds the debt. Do Not Disturb stays on until the user turns it off themselves. The fix is to stop the running practice before the restore transaction.
- The Android 15+ repayment described above.
-
INTERRUPTION_FILTER_UNKNOWNis 0, and the reference says it's returned "when the value is unavailable for any reason". Our sentinel is-1, so a 0 gets stored as a real filter and written back later. That should be treated as "restore to all". - Changes the user makes mid-session get overwritten. If they switch Do Not Disturb off during a practice, the end of the session sets the old value anyway, and a process restart re-applies quiet mode.
- The Android 8 branch that the docs don't explain.
-
No tests cover
NotificationSilencerorPracticeRepository. The repo's unit tests cover other features.
Takeaways
- Treat a global setting you change as a loan. Store the old value with the session that changed it, in persistent storage, with a sentinel for "untouched".
- Put every exit path through one function, and make its cleanup
NonCancellable. The coroutine that ends a session can be the one getting cancelled. - Strip live state out of backups. A snapshot shouldn't carry a promise to undo something on a different phone.
- Re-read the behavior changes for your
targetSdk. On Android 15+, "set the filter" means "toggle my rule", and "restore" has to follow.
ReClaim is free on Google Play. If you want the user-side view of these modes, our guides cover how to turn on Do Not Disturb on Android and focus mode on Android.
This post was drafted with AI assistance and reviewed by the ReClaim team.
Top comments (0)