ReClaim Android 主畫面專注計時器:完成判定、滾動週統計與不另寫封鎖資料列
A focus timer on an Android Home screen: what counts as done, a rolling week, and blocks that aren't rows
ReClaim 這款 Android 啟動器正為主畫面開發練習計時器,支援倒數及正計時,目前尚未納入 Google Play 版本。倒數計時須運行至預設時長才算完成;提早停止仍會保存時長,但不計作完成當日。完成判定亦用於連續天數及關聯習慣標記,計時期間的應用程式封鎖會在工作階段結束時解除。
We're building ReClaim, a minimalist Android launcher that's on Google Play. One of the newest things we've built for its Home screen (not in the Play build yet) is a practice timer: you name something you want to spend time on, like reading, put it on the Home icon, and tap to start. It can count down or count up. We already wrote about how it borrows Do Not Disturb and how a finished session can mark a linked habit. This post is the rest of that timer: what "finished" actually means, how the streak and "this week" numbers are derived, and how a practice can hold apps without writing block rows.
A timer sounds like a clock and a button. The clock was the easy part. The part that took longer was the rule underneath it: stopping early still saves the time, but it does not complete the day. Once that rule exists, the streak, the habit mark, and a set of temporary app blocks all have to follow it.
Stack: Kotlin, Jetpack Compose, Hilt, Room, coroutines, minSdk 26, targetSdk 36. All code below is copied from the repo.
Two modes, one open session
The database stores the practice and every stretch of time you've run it. The mode is a name on the row, COUNTDOWN or STOPWATCH. A countdown stores its length as plannedMillis on the session. A stopwatch leaves that column null, and the running session's countingDown flag is simply "is plannedMillis set?"
/**
* A named activity the home icon can time, such as reading.
* [mode] is the [com.reclaim.launcher.data.practice.PracticeMode] name.
* [blockPackages] is a comma-separated list. Package names never contain commas.
*/
@Entity(tableName = "practices")
data class PracticeEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val name: String,
val mode: String,
val durationMinutes: Int,
val minimumMinutes: Int,
val silenceNotifications: Boolean,
val blockPackages: String,
val position: Int,
val createdAt: Long,
/** Habit marked once when this practice is finished. Null marks nothing. */
val habitId: Long? = null,
)
/**
* 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,
)
You can create more than one practice, but only one sits on the Home icon, and only one session can be running. The open-session queries are WHERE endedAt IS NULL LIMIT 1. Starting a practice goes through one repository function, under a Mutex:
/** Starts [practiceId]. False when that practice no longer exists. */
suspend fun start(practiceId: Long): Boolean = mutex.withLock {
val now = System.currentTimeMillis()
val open = dao.open()
if (open != null && open.practiceId == practiceId && now - open.startedAt < 800L) return@withLock true
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
}
A second tap in the first 800 milliseconds is treated as the same start, so the session is not restarted and the time you already have is not thrown away. A tap on a different practice, or a later tap on the same one, finishes the session that's already open at now and then opens the new one. That matters for the rule in the next section: if you were in a 25-minute countdown and you switch practices at minute 10, the first session is an early stop. The time is saved. The day is not completed.
A new practice defaults to a 25-minute countdown with notification silence on. Duration is kept between 1 and 180 minutes. The settings copy is blunt about how each mode ends: "The day counts when it finishes" for a countdown, and "The day counts when you stop it" for a stopwatch. The icon "counts down and then rests." There is no sound when it hits zero. The alarm we do schedule is only a backup so the session can end if the process is gone, which we covered in the Do Not Disturb post and, in more detail, in our post on racing AlarmManager with a coroutine.
What "finished" means
One small function is the source of truth:
/**
* A countdown is complete when it runs to its planned end. A stopwatch is complete when it is
* stopped. Stopping a countdown early still saves the time and does not complete the day.
*/
fun practiceCompleted(startedAt: Long, endedAt: Long, plannedMillis: Long?): Boolean {
val elapsed = (endedAt - startedAt).coerceAtLeast(0L)
return if (plannedMillis != null) elapsed >= plannedMillis else elapsed > 0L
}
Elapsed time and completion are not the same thing. Every finished session writes endedAt and adds its duration to that day's total, even a countdown you stopped after two minutes. Completion is a separate yes or no. A countdown needs elapsed >= plannedMillis. A stopwatch needs any elapsed time at all, which is how "the day counts when you stop it" is implemented: stopping is the finish line, as long as the clock actually moved.
That one boolean is reused in three places. It decides whether the day counts for the streak. It decides whether a linked habit gets a mark, which we walked through in the habits post: the mark goes on the local day the session started, and it goes through the same logOne path as a tap. And it is why deleting a practice finishes an open session with markHabit = false. Deleting is not completing.
Derived stats, with the live session folded in
There is no streak column. Totals and the streak are derived from finished sessions by a pure function. The Home sheet and the settings screen both call it, and they pass the still-running elapsed time in as extraMillis so the "today" number moves before the row is saved:
/**
* Seven days ending today, plus a streak. [extraMillis] is the still-running session, added to
* today so the numbers move before the session is saved. A day counts toward the streak only after
* a session from that day is complete.
*/
fun statsFor(
practice: Practice,
finished: List<PracticeSessionEntity>,
extraMillis: Long = 0L,
now: Long = System.currentTimeMillis(),
zone: ZoneId = ZoneId.systemDefault(),
): PracticeStats {
val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate()
val own = finished.filter { it.practiceId == practice.id && it.endedAt != null }
val byDay = HashMap<LocalDate, Long>()
val completed = HashSet<LocalDate>()
for (session in own) {
val end = session.endedAt ?: continue
val day = Instant.ofEpochMilli(session.startedAt).atZone(zone).toLocalDate()
val duration = (end - session.startedAt).coerceAtLeast(0L)
byDay[day] = (byDay[day] ?: 0L) + duration
if (practiceCompleted(session.startedAt, end, session.plannedMillis)) completed += day
}
val days = (6 downTo 0).map { offset ->
val date = today.minusDays(offset.toLong())
val base = byDay[date] ?: 0L
DayTotal(date, if (date == today) base + extraMillis.coerceAtLeast(0L) else base)
}
val todayTotal = days.last().millis
var cursor = if (today in completed) today else today.minusDays(1)
var streak = 0
while (streak < 3_650) {
if (cursor !in completed) break
streak++
cursor = cursor.minusDays(1)
}
return PracticeStats(
streakDays = streak,
todayMillis = todayTotal,
weekMillis = days.sumOf { it.millis },
days = days,
)
}
A few choices are packed in there.
The day is the local calendar day the session started, from startedAt in the phone's time zone, not from endedAt and not from a UTC instant. A 25-minute countdown that begins at 11:50 PM belongs to the evening you were in, even if it rings after midnight. That matches the habit mark. And because the walk is minusDays on a LocalDate, a daylight saving night cannot turn a day into 23 or 25 hours.
extraMillis is added only to today's total. It does not put today in the completed set. You can watch the minutes climb during a countdown and still have no streak for today until the session actually finishes.
The streak gives today the same kind of grace our habits do. If today is not yet complete, the walk starts at yesterday, so an unfinished morning does not read as a broken streak. The loop is capped at 3,650 steps, a little over ten years, so a bad row cannot spin forever.
The number the UI labels "this week" is weekMillis, and that is the sum of those seven days ending today, including the live session. It is a rolling seven-day window, not a Monday-to-Sunday week. Our habit streaks, by contrast, use a Monday week. The KDoc is the accurate name: "Seven days ending today." I have not changed the label. If you are building a "week" number, pick the week you mean and name it that way, because "this week" will otherwise mean different things in different parts of the same app.
Blocks that aren't rows
A practice can hold a list of apps until the session ends, so a reading timer can keep the usual distractions closed without you setting a separate block. The important design choice is that those holds are not rows in the block table. They are a comma-separated package list copied onto the session when it starts. The session KDoc is explicit: they are "held only until the session ends, separate from a block the user set themselves, because stopping the practice must lift them."
When the held apps should open again is another small function:
/** Far-future until used when a stopwatch is holding apps. Callers must not render it as a countdown. */
const val OPEN_ENDED_HOLD_UNTIL = Long.MAX_VALUE / 4
fun String.decodePackages(): List<String> =
split(',').map { it.trim() }.filter { it.isNotEmpty() }
fun List<String>.encodePackages(): String = distinct().joinToString(",")
fun PracticeSessionEntity.heldPackages(): Set<String> = blockPackages.decodePackages().toSet()
/**
* When this session's held apps should open again. Null when it holds nothing or the countdown
* has already passed. A stopwatch holds until the session row is closed.
*/
fun PracticeSessionEntity.holdUntil(now: Long = System.currentTimeMillis()): Long? {
if (heldPackages().isEmpty()) return null
val planned = plannedMillis ?: return OPEN_ENDED_HOLD_UNTIL
val end = startedAt + planned
return end.takeIf { it > now }
}
A countdown hold expires at the planned end, even if the session row is somehow still open. A stopwatch has no planned end, so the function returns a far-future sentinel — Long.MAX_VALUE / 4, not Long.MAX_VALUE itself — and the block screen is told not to draw a countdown. The check for that is isOpenEndedPracticeHold: the open session has a null plannedMillis, the package is in the held set, and holdUntil is not null.
The block repository folds those holds into the same blockedPackages flow the accessibility service already uses for temporary blocks and schedules:
val blockedPackages: Flow<Set<String>> = combine(
blockDao.observeAll(),
scheduleRepository.schedules,
practiceDao.observeOpen(),
scheduleTicker(),
) { rows, _, open, _ ->
val now = System.currentTimeMillis()
val temporary = rows.filter { it.blockedUntil > now }.map { it.packageName }.toSet()
val held = if (open?.holdUntil(now) != null) open.heldPackages() else emptySet()
temporary + held + scheduleRepository.blockedPackagesNow()
}
When the session closes, observeOpen() emits null, the held set becomes empty, and those apps open again. A block you set by hand is a real row with its own blockedUntil, so it is still there when the practice ends. The two mechanisms can overlap: if both are holding the same package, the app stays blocked until the later of the two ends. That is also how the app list computes blockedUntil, taking maxOf the existing block and the practice hold.
This is the same idea as the rest of ReClaim's app blocking: the apps stay installed, and the rule is a hold you chose, not a uninstall. The practice hold is just shorter-lived, and it must not outlive the timer that created it.
Other open items
-
minimumMinutesis stored and never used. It is on the entity, coerced to 1..180 on save, defaulted to 25, and written into backups. Nothing in completion, stats, or the editor reads it. A "minimum time before the day counts" would be a reasonable rule for a stopwatch. It is not the rule we shipped. The stopwatch counts as long as elapsed time is greater than zero. -
No unique constraint on the open session. "Only one running session" is a
LIMIT 1query plus aMutex. The table would allow a second row withendedAt IS NULL. The repository is a Hilt singleton and the only writer during normal use, so in ordinary use it holds. The database itself would not stop a second open row, and the readers would see only one of them. -
Boot does not re-arm this timer. Our
BootReceiverre-arms App Reminder timers after a reboot or an app update. It does not call into the practice repository. Android'sAlarmManagerdocs say registered alarms "will be cleared if it is turned off and rebooted." An overdue countdown hold still expires on its own, becauseholdUntilreturns null once the planned end has passed. An open stopwatch hold, and the still-open session row, wait until the process starts andreconcile()runs. I have not added a boot path for practices yet. -
No tests cover
practiceCompletedorstatsFor. Both are pure and take the clock as a parameter, so they are straightforward to unit test. Right now nothing tests them. - Not in the Play build yet. Practice is new code, from the same unreleased work as habits. The Play listing is still 0.6.6.0.1, last updated October 29, 2026. Treat this as work in progress.
Takeaways
- Separate "time spent" from "the day is complete." Saving an early stop is useful. Counting it as a finished day is a different decision, and it should be one function both the streak and any side effect call.
- If the UI has to move while a session is still open, pass the live elapsed time into the same pure function. Do not put today in the completed set until the session actually qualifies.
- Give today grace in a streak walk, or every unfinished morning looks like a break.
- If a hold should end when the timer ends, do not write a block row. Copy the package list onto the session and fold it into the existing blocked set. A user-set block can then keep its own end time.
- A "week" is either a rolling seven days or a week with a start day. Say which one, especially if another feature in the same app already picked Monday.
ReClaim is free on Google Play. The practice timer is the "build" side of the Home screen: a way to spend a stretch of time on purpose. The system Focus mode on the phone is a different tool, and our post on how to set up Focus mode on Android walks through that from the user's side.
This post was drafted with AI assistance and reviewed by the ReClaim team.
來源:DEV Community · dev.to