Habit tracker with reminders
What you will build
The finished app lets a user create daily habits, check them off each day, and get a reminder notification around a chosen time. Streaks are calculated locally and shown on the home screen. As a stretch goal, a Jetpack Glance widget shows the day's progress.
What it proves to an employer: you can wire Room, DataStore, WorkManager, and the notification system into one coherent flow. You handle the POST_NOTIFICATIONS runtime permission on Android 13+, know that periodic work has a 15-minute minimum and is never exact, and can explain when an exact alarm is justified and when it is not. The streak logic is pure Kotlin with JUnit tests, including time zone and daylight saving time (DST) cases, which shows you keep business rules separate from Android.
Skills you practise
- Room entities, relations, and schema migrations
- Preferences DataStore for user settings
- WorkManager unique periodic work for a daily reminder
- Notification channels and the POST_NOTIFICATIONS runtime permission
- Exact alarm rules:
SCHEDULE_EXACT_ALARM,canScheduleExactAlarms(), and why a habit app should not useUSE_EXACT_ALARM - Pure Kotlin date logic with
java.timeand JUnit tests - Jetpack Compose with unidirectional data flow and type-safe navigation
- R8 and release-build preparation
Architecture
Keep the module count small. A pure Kotlin :domain module holds the models (Habit, StreakResult) and the date logic (StreakCalculator, ReminderSchedule). Because it has no Android dependencies, its tests run on the plain JVM in seconds. Everything else lives in :app, split into data, reminders, and ui packages. Split those into modules later only if the app grows.
The data package holds the Room database (HabitDao, CheckInDao) and a Preferences DataStore for settings (reminder time, reminders on or off). A HabitRepository exposes Flows from both and suspend functions for writes. Room suspend DAO calls and Flow queries already run on Room's own background executor, so the repository does not need withContext(Dispatchers.IO). DataStore is also main-safe.
The reminders package creates the notification channel, schedules one unique daily PeriodicWorkRequest, and holds the ReminderWorker. The worker reads Room, finds habits not yet checked in today, and posts one notification. It never touches the UI.
The ui package has HabitListScreen, CheckInScreen, and SettingsScreen. Each ViewModel turns repository flows into one StateFlow<UiState> with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ...). One-off things like a confirmation snackbar are fields in that state, not a Channel. Navigation uses @Serializable routes. Hilt wires it together.
Data flows one direction: Room / DataStore → repository → ViewModel → Compose. User actions go back through the ViewModel to the repository.
| Module or layer | Responsibility |
|---|---|
:domain (Kotlin JVM) | Models, StreakCalculator, and ReminderSchedule. No Android imports. |
:app data | Room entities, DAOs, and migrations; Preferences DataStore; HabitRepository. |
:app reminders | Notification channel, daily periodic worker, optional exact-alarm path with a boot receiver. |
:app ui | Compose screens, ViewModels with StateFlow<UiState>, type-safe NavHost. |
:app DI | Application class, Hilt modules, manifest permissions. |
:widget (stretch) | Jetpack Glance GlanceAppWidget and GlanceAppWidgetReceiver showing today's status. |
Milestones
1. Scaffold and Room database
Set up the project and define the Room schema for habits and check-ins.
- Create the
:appmodule and a Kotlin JVM:domainmodule. Add a version catalog with Room (with KSP), DataStore, WorkManager, Hilt, and the Compose BOM. - Define a
HabitEntityand aCheckInEntity(habitId: Long, date: LocalDate). GiveCheckInEntitya foreign key toHabitEntitywithonDelete = CASCADE, an index onhabitId, and a unique index on(habitId, date). StoredateasepochDay(aLong) with aTypeConverter. - Add a
HabitDaowithobserveAll(): Flow<List<HabitEntity>>andsuspendinsertanddelete. Add aCheckInDaowith asuspend@Upsertand aFlowquery that returns all check-in dates for a habit. - Create
HabitDatabaseatversion = 1withexportSchema = trueand a schema directory. Version 1 needs no migration; every later version does. - In debug builds only, seed two sample habits and a few check-ins so the UI has data on first launch.
Done when: The app compiles, the schema JSON for version 1 is generated, and the seeded habits appear in Logcat when you collect observeAll().
Lessons: room entities daos queries, android studio project structure, room migrations
2. DataStore settings and repository
Store settings in Preferences DataStore and expose a repository the ViewModels can use.
- Create one DataStore with the top-level
preferencesDataStore(name = "settings")delegate. Never create two instances for the same file. - Define keys for the reminder time (
intPreferencesKeyholding minutes after midnight) and a reminders-enabled flag. Read them by mappingdataStore.data, and catchIOExceptionto emitemptyPreferences(). Write withdataStore.edit { ... }. - Define a
HabitRepositorywithobserveHabitsWithCheckIns(): Flow<List<HabitWithDates>>,suspend fun checkIn(habitId: Long, date: LocalDate),suspend fun undoCheckIn(...), andobserveSettings(): Flow<Settings>. - Implement it with the DAOs and the DataStore. The repository returns
Flow; turning flows intoStateFlowis the ViewModel's job.
Done when: Changing the reminder time with edit makes observeSettings() emit the new value, and inserting a habit makes observeHabitsWithCheckIns() emit a list that includes it.
Lessons: datastore preferences and proto, repository pattern, flow basics cold streams
3. Streak and schedule logic with unit tests
Write pure Kotlin date logic in :domain and cover it with JUnit tests, including edge cases.
- Create
StreakCalculatoras a KotlinobjectwithcurrentStreak(checkIns, today)andlongestStreak(checkIns), both taking aSet<LocalDate>. - Handle the grace rule: if today is not checked in but yesterday was, the streak is still alive.
- Add
ReminderSchedule.delayUntilNext(time: LocalTime, now: ZonedDateTime): Durationfor the reminder in the next milestone. - Never call
LocalDate.now()inside this logic. The caller computestodaywithLocalDate.now(clock)from an injectedjava.time.Clock, so tests can fix the clock and zone. - Write tests for: empty set, one day, a 30-day run, a one-day gap, "yesterday but not today", a fixed
Clocknear midnight in two different zones giving two differenttodayvalues, anddelayUntilNextacross a spring-forward and a fall-back DST change. - Add a
StreakResultsealed interface (Active,AtRisk,None) so the UI can render each state.
Done when: All tests pass with ./gradlew :domain:test, and :domain has no Android dependency.
Lessons: unit tests with junit and mockk, test pyramid for android, sealed classes enums and when
4. Notifications and the daily reminder
Create the channel, ask for POST_NOTIFICATIONS at the right moment, and schedule a daily reminder with WorkManager.
- In
Application.onCreate, create areminderschannel withNotificationManagerCompat.from(this).createNotificationChannel(...)andIMPORTANCE_DEFAULT. Calling this again with the same id is safe; it does not reset the user's choices. - On Android 13+ (API 33), request
POST_NOTIFICATIONSwhen the user turns reminders on, not at first launch. In Compose userememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()). Do not cache the result in DataStore, because the user can change it in Settings. CheckareNotificationsEnabled()before posting. - Build a
PeriodicWorkRequestBuilder<ReminderWorker>(1, TimeUnit.DAYS)withsetInitialDelayset toReminderSchedule.delayUntilNext(...). Enqueue it withenqueueUniquePeriodicWork("daily-reminder", ...): useKEEPat app start andCANCEL_AND_REENQUEUEwhen the user picks a new time, so the new initial delay takes effect. When reminders are turned off, cancel the unique work. - In
ReminderWorker, load today's unchecked habits from Room. If there are none, returnResult.success()without posting. Otherwise post one notification whosePendingIntent(withFLAG_IMMUTABLE) opens the app on the check-in screen. - Optional: a "precise reminders" setting. Only when it is on, and only if
alarmManager.canScheduleExactAlarms()is true, usesetExactAndAllowWhileIdlewithSCHEDULE_EXACT_ALARM. Otherwise send the user toSettings.ACTION_REQUEST_SCHEDULE_EXACT_ALARMor stay on WorkManager. Do not declareUSE_EXACT_ALARM: Google Play allows it only for alarm clock, timer, and calendar apps. Alarms are cleared on reboot, so add aBOOT_COMPLETEDreceiver to reschedule them.
Done when: With the reminder set a few minutes ahead, a notification arrives near that time (WorkManager may run it later, especially in Doze); denying the permission leaves the app working with reminders shown as off; the scheduled work is still listed after a reboot (check with App Inspection's Background Task Inspector).
Lessons: notifications and channels, workmanager, alarms and exact timing
5. Compose UI: list, check-in, settings
Build the three screens and wire them to the repository through ViewModels.
- Create
HabitListScreenwith aLazyColumn(key = { it.id }) that shows each habit, its streak, and a check-in toggle. - Add
CheckInScreenwith a large toggle and a confirmation snackbar. Hold the message inUiState(for examplecheckInMessage: String?); show it in aLaunchedEffect, then callviewModel.messageShown()to clear it. - Add
SettingsScreenwith a Material 3TimePickerfor the reminder time and a reminders switch that triggers the permission request from milestone 4. - Set up a
NavHostwith@Serializableroutes:object HabitList,data class CheckIn(val habitId: Long), andobject Settings. Read the id withtoRoute<CheckIn>(). Add a bottom bar for the two top-level screens. - In each ViewModel, build
uiStatewithstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState()). Computetodayfrom the injectedClock. Collect withcollectAsStateWithLifecycle().
Done when: A user can add a habit, check it in, and change the reminder time; the list updates without manual refresh; rotating the device does not show the snackbar twice; Back works as expected.
Lessons: viewmodel and ui state, one off events done right, navigation in compose
6. Testing and release prep
Add ViewModel, database, and UI tests, then build a release version.
- Write a
FakeHabitRepositoryand test the list ViewModel on the JVM with aMainDispatcherRulethat setsStandardTestDispatcheras Main. Start a collector onuiStateinbackgroundScope(because ofWhileSubscribed), then check that a check-in updates the streak. - Write a DAO test against
Room.inMemoryDatabaseBuilder(as an instrumented test or with Robolectric) that checks the unique(habitId, date)index and the cascade delete. - Add a Compose UI test with
createComposeRule()that taps the check-in toggle and asserts the snackbar text appears. - Turn on
isMinifyEnabledandisShrinkResourcesfor the release build type. Room, WorkManager, and Hilt ship their own consumer keep rules, so add rules only for what R8 reports. - Run
./gradlew assembleRelease, install the APK, and check that a reminder still fires and the database still opens.
Done when: ./gradlew test and the UI test pass, the release build succeeds with R8 on, and the release APK works on a device.
Lessons: viewmodel tests, compose ui tests, r8 shrinking and obfuscation
Key code
// :domain — pure Kotlin, no Android dependencies
import java.time.Duration
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZonedDateTime
object StreakCalculator {
fun currentStreak(checkIns: Set<LocalDate>, today: LocalDate): Int {
val anchor = when {
today in checkIns -> today
today.minusDays(1) in checkIns -> today.minusDays(1) // grace: today not done yet
else -> return 0
}
var streak = 0
var cursor = anchor
while (cursor in checkIns) {
streak++
cursor = cursor.minusDays(1)
}
return streak
}
fun longestStreak(checkIns: Set<LocalDate>): Int {
if (checkIns.isEmpty()) return 0
val sorted = checkIns.sorted()
var best = 1
var run = 1
for (i in 1 until sorted.size) {
run = if (sorted[i] == sorted[i - 1].plusDays(1)) run + 1 else 1
best = maxOf(best, run)
}
return best
}
}
object ReminderSchedule {
// Time until the next occurrence of `time` in now's zone. ZonedDateTime handles DST:
// the gap is 23 h on a spring-forward day and 25 h on a fall-back day.
fun delayUntilNext(time: LocalTime, now: ZonedDateTime): Duration {
var next = now.with(time)
if (!next.isAfter(now)) next = next.plusDays(1)
return Duration.between(now, next)
}
}// :app reminders — schedule the daily reminder
fun scheduleDailyReminder(
workManager: WorkManager,
time: LocalTime,
policy: ExistingPeriodicWorkPolicy, // KEEP at app start, CANCEL_AND_REENQUEUE on a new time
) {
val delay = ReminderSchedule.delayUntilNext(time, ZonedDateTime.now())
val request = PeriodicWorkRequestBuilder<ReminderWorker>(1, TimeUnit.DAYS)
.setInitialDelay(delay.toMillis(), TimeUnit.MILLISECONDS)
.build()
workManager.enqueueUniquePeriodicWork("daily-reminder", policy, request)
}// :domain tests
@Test
fun springForwardDayIs23Hours() {
val london = ZoneId.of("Europe/London") // clocks go forward on 29 March 2026
val now = ZonedDateTime.of(2026, 3, 28, 9, 0, 0, 0, london)
assertEquals(Duration.ofHours(23), ReminderSchedule.delayUntilNext(LocalTime.of(9, 0), now))
}
@Test
fun yesterdayKeepsStreakAlive() {
val today = LocalDate.of(2026, 5, 10)
val dates = setOf(today.minusDays(1), today.minusDays(2))
assertEquals(2, StreakCalculator.currentStreak(dates, today))
}Set<LocalDate>makes eachincheck O(1); the repository builds the set from the Room query.- The grace rule (yesterday counts while today is still open) is a common source of streak bugs, so it gets its own branch and its own test.
longestStreaksorts once, which is O(n log n). For a few hundred dates per habit this is fine.- Check-ins are stored as a
LocalDate, the day the user saw when they checked in. Travelling to a new time zone does not rewrite past days. Onlytodaydepends on the zone, and it comes from an injectedClock. - A periodic request with a fixed 1-day interval does not follow DST, so the reminder can shift by an hour after a clock change. Re-run
scheduleDailyReminderwithCANCEL_AND_REENQUEUEwhen the zone or the clock changes, or, on WorkManager 2.9+, setsetNextScheduleTimeOverridefrom the worker with theUPDATEpolicy.
Pitfalls
- Expecting code to change a channel after it exists. Calling
createNotificationChannelagain with the same id is a no-op for settings the user owns. You cannot raise its importance later. Fix: choose the importance carefully the first time; to change behaviour, create a channel with a new id and delete the old one. - Asking for a periodic interval under 15 minutes, or expecting it to be exact. WorkManager raises the interval to 15 minutes with a log warning, and every run can be delayed by Doze, App Standby buckets, and constraints. Fix: use a daily request with an initial delay and tell the user reminders arrive "around" the time.
- Reaching for
USE_EXACT_ALARMin a habit app. Google Play allows it only for alarm clock, timer, and calendar apps, andSCHEDULE_EXACT_ALARMis denied by default for most new installs on Android 14+. CallingsetExact*()without access throwsSecurityException. Fix: default to WorkManager; offer exact timing only as an opt-in, guarded bycanScheduleExactAlarms(). - Forgetting that alarms are cleared on reboot. If you use the exact-alarm path, reminders stop after a restart. Fix: keep the reminder time in DataStore and reschedule from a
BOOT_COMPLETEDreceiver. WorkManager work does not need this; WorkManager reschedules itself. - Forgetting POST_NOTIFICATIONS on Android 13+. For apps targeting API 33+, notifications start off on new installs. Without the permission,
notify()posts nothing and throws nothing. Fix: request it in context withRequestPermission, and checkareNotificationsEnabled()before posting. - Using
LocalDate.now()inside the streak logic. Tests depend on the real date and zone, and midnight bugs are hard to reproduce. Fix: passtodayin, computed from an injectedClock. - Collecting a Room
Flowin a plainLaunchedEffect. The collection keeps running while the app is in the background, because the composition stays alive when the activity is stopped. Fix: usecollectAsStateWithLifecycle. - Changing an entity without a migration. If you change the schema but not the version, Room throws
IllegalStateException("Room cannot verify the data integrity"). If you bump the version with no migration, it throws because a migration was not found. Fix: bumpversion, add aMigrationor anAutoMigration, and test it withMigrationTestHelper.
Code review finding
- The reminder is a
PeriodicWorkRequestwith a 15-minute interval. Each run checks whether it is "about 8 a.m." and posts if so. - The work runs about 96 times a day for one notification, and Doze and App Standby still delay the run nearest 8 a.m., so the reminder sometimes arrives well after 8 a.m. or not that day at all.
- A second attempt added
USE_EXACT_ALARMto the manifest, which Google Play does not allow for a habit tracker.
- Replace it with one unique daily
PeriodicWorkRequestwhose initial delay isReminderSchedule.delayUntilNext(...). UseKEEPat app start andCANCEL_AND_REENQUEUEwhen the user changes the time. - Remove
USE_EXACT_ALARM. If users really need precise timing, add an opt-in "precise reminders" setting that usesSCHEDULE_EXACT_ALARM, checkscanScheduleExactAlarms(), falls back to WorkManager when access is denied, and reschedules onBOOT_COMPLETED. - In the UI, say "around 8:00" for the default mode so the behaviour matches what users are told.
Stretch goals
- Add a Jetpack Glance widget: a
GlanceAppWidgetthat loads today's status inprovideGlanceand renders it inprovideContent, aGlanceAppWidgetReceiverdeclared in the manifest, and a call toupdateAll(context)after each check-in. Get the repository through a Hilt@EntryPoint, since the widget is not created by Hilt. - Allow a different reminder time per habit, with one unique work name per habit.
- Add a notification action "Mark done" that checks in through a
BroadcastReceiverwithout opening the app. - Add a weekly summary screen with a Compose
Canvaschart of check-ins over the last 7 days. - Add a Room migration test with
MigrationTestHelperfor a new column, such as a habit colour.
Done checklist
- Room has an exported schema for every version and a tested migration for every version after 1.
POST_NOTIFICATIONSis requested in context on Android 13+, and posting is skipped when notifications are disabled.- The daily reminder is one unique periodic work request (1 day, initial delay to the chosen time); no periodic work runs every 15 minutes "just in case".
USE_EXACT_ALARMis not declared. If an exact path exists, it is opt-in, checkscanScheduleExactAlarms(), and reschedules after reboot.StreakCalculatorandReminderSchedulehave no Android imports and are tested for empty, single-day, gap, grace, time zone, and DST cases.- ViewModels expose
StateFlow<UiState>withWhileSubscribed(5_000); screens usecollectAsStateWithLifecycle; one-off messages live in state. - Navigation uses
@Serializableroutes. - The release build runs with R8 enabled and has been tested on a device.
Talking about it in an interview
- Explain the reminder trade-off: periodic WorkManager work is battery-friendly, survives reboot, and has a 15-minute minimum, but it is never exact. Exact alarms need special access (
SCHEDULE_EXACT_ALARMis denied by default for most new installs on Android 14+), are cleared on reboot, andUSE_EXACT_ALARMis reserved by Play policy for alarm, timer, and calendar apps. So the default is "around 8:00", with exact timing only as an opt-in. - Walk through the streak logic as pure Kotlin.
todaycomes from an injectedClock, check-ins are stored asLocalDate, and the tests cover zones near midnight and DST days. Mention the 23-hour and 25-hour days and why a fixed 1-day periodic interval drifts across a clock change. - Describe the data flow: Room and DataStore feed a repository that returns
Flow; ViewModels combine them withstateIn(WhileSubscribed(5_000)); Compose renders. The worker reads Room and posts a notification but never touches the UI. - Mention the details that make it shippable: the channel is created once and the user owns it afterwards, the notification permission is asked in context, and the release build is tested with R8 on.
- If you built the Glance widget, explain that
provideGlanceruns in a background worker, so you load data beforeprovideContentand callupdateAllwhen data changes elsewhere in the app.