Habit tracker with reminders

Build a habit tracker with Jetpack Compose, Room, DataStore, and WorkManager that sends daily reminder notifications and calculates streaks in tested Kotlin. About 26 hours.

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 use USE_EXACT_ALARM
  • Pure Kotlin date logic with java.time and 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 layerResponsibility
:domain (Kotlin JVM)Models, StreakCalculator, and ReminderSchedule. No Android imports.
:app dataRoom entities, DAOs, and migrations; Preferences DataStore; HabitRepository.
:app remindersNotification channel, daily periodic worker, optional exact-alarm path with a boot receiver.
:app uiCompose screens, ViewModels with StateFlow<UiState>, type-safe NavHost.
:app DIApplication 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.

  1. Create the :app module and a Kotlin JVM :domain module. Add a version catalog with Room (with KSP), DataStore, WorkManager, Hilt, and the Compose BOM.
  2. Define a HabitEntity and a CheckInEntity(habitId: Long, date: LocalDate). Give CheckInEntity a foreign key to HabitEntity with onDelete = CASCADE, an index on habitId, and a unique index on (habitId, date). Store date as epochDay (a Long) with a TypeConverter.
  3. Add a HabitDao with observeAll(): Flow<List<HabitEntity>> and suspend insert and delete. Add a CheckInDao with a suspend @Upsert and a Flow query that returns all check-in dates for a habit.
  4. Create HabitDatabase at version = 1 with exportSchema = true and a schema directory. Version 1 needs no migration; every later version does.
  5. 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.

  1. Create one DataStore with the top-level preferencesDataStore(name = "settings") delegate. Never create two instances for the same file.
  2. Define keys for the reminder time (intPreferencesKey holding minutes after midnight) and a reminders-enabled flag. Read them by mapping dataStore.data, and catch IOException to emit emptyPreferences(). Write with dataStore.edit { ... }.
  3. Define a HabitRepository with observeHabitsWithCheckIns(): Flow<List<HabitWithDates>>, suspend fun checkIn(habitId: Long, date: LocalDate), suspend fun undoCheckIn(...), and observeSettings(): Flow<Settings>.
  4. Implement it with the DAOs and the DataStore. The repository returns Flow; turning flows into StateFlow is 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.

  1. Create StreakCalculator as a Kotlin object with currentStreak(checkIns, today) and longestStreak(checkIns), both taking a Set<LocalDate>.
  2. Handle the grace rule: if today is not checked in but yesterday was, the streak is still alive.
  3. Add ReminderSchedule.delayUntilNext(time: LocalTime, now: ZonedDateTime): Duration for the reminder in the next milestone.
  4. Never call LocalDate.now() inside this logic. The caller computes today with LocalDate.now(clock) from an injected java.time.Clock, so tests can fix the clock and zone.
  5. Write tests for: empty set, one day, a 30-day run, a one-day gap, "yesterday but not today", a fixed Clock near midnight in two different zones giving two different today values, and delayUntilNext across a spring-forward and a fall-back DST change.
  6. Add a StreakResult sealed 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.

  1. In Application.onCreate, create a reminders channel with NotificationManagerCompat.from(this).createNotificationChannel(...) and IMPORTANCE_DEFAULT. Calling this again with the same id is safe; it does not reset the user's choices.
  2. On Android 13+ (API 33), request POST_NOTIFICATIONS when the user turns reminders on, not at first launch. In Compose use rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()). Do not cache the result in DataStore, because the user can change it in Settings. Check areNotificationsEnabled() before posting.
  3. Build a PeriodicWorkRequestBuilder<ReminderWorker>(1, TimeUnit.DAYS) with setInitialDelay set to ReminderSchedule.delayUntilNext(...). Enqueue it with enqueueUniquePeriodicWork("daily-reminder", ...): use KEEP at app start and CANCEL_AND_REENQUEUE when the user picks a new time, so the new initial delay takes effect. When reminders are turned off, cancel the unique work.
  4. In ReminderWorker, load today's unchecked habits from Room. If there are none, return Result.success() without posting. Otherwise post one notification whose PendingIntent (with FLAG_IMMUTABLE) opens the app on the check-in screen.
  5. Optional: a "precise reminders" setting. Only when it is on, and only if alarmManager.canScheduleExactAlarms() is true, use setExactAndAllowWhileIdle with SCHEDULE_EXACT_ALARM. Otherwise send the user to Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM or stay on WorkManager. Do not declare USE_EXACT_ALARM: Google Play allows it only for alarm clock, timer, and calendar apps. Alarms are cleared on reboot, so add a BOOT_COMPLETED receiver 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.

  1. Create HabitListScreen with a LazyColumn (key = { it.id }) that shows each habit, its streak, and a check-in toggle.
  2. Add CheckInScreen with a large toggle and a confirmation snackbar. Hold the message in UiState (for example checkInMessage: String?); show it in a LaunchedEffect, then call viewModel.messageShown() to clear it.
  3. Add SettingsScreen with a Material 3 TimePicker for the reminder time and a reminders switch that triggers the permission request from milestone 4.
  4. Set up a NavHost with @Serializable routes: object HabitList, data class CheckIn(val habitId: Long), and object Settings. Read the id with toRoute<CheckIn>(). Add a bottom bar for the two top-level screens.
  5. In each ViewModel, build uiState with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState()). Compute today from the injected Clock. Collect with collectAsStateWithLifecycle().

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.

  1. Write a FakeHabitRepository and test the list ViewModel on the JVM with a MainDispatcherRule that sets StandardTestDispatcher as Main. Start a collector on uiState in backgroundScope (because of WhileSubscribed), then check that a check-in updates the streak.
  2. 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.
  3. Add a Compose UI test with createComposeRule() that taps the check-in toggle and asserts the snackbar text appears.
  4. Turn on isMinifyEnabled and isShrinkResources for the release build type. Room, WorkManager, and Hilt ship their own consumer keep rules, so add rules only for what R8 reports.
  5. 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 each in check 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.
  • longestStreak sorts 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. Only today depends on the zone, and it comes from an injected Clock.
  • 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 scheduleDailyReminder with CANCEL_AND_REENQUEUE when the zone or the clock changes, or, on WorkManager 2.9+, set setNextScheduleTimeOverride from the worker with the UPDATE policy.

Pitfalls

  • Expecting code to change a channel after it exists. Calling createNotificationChannel again 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_ALARM in a habit app. Google Play allows it only for alarm clock, timer, and calendar apps, and SCHEDULE_EXACT_ALARM is denied by default for most new installs on Android 14+. Calling setExact*() without access throws SecurityException. Fix: default to WorkManager; offer exact timing only as an opt-in, guarded by canScheduleExactAlarms().
  • 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_COMPLETED receiver. 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 with RequestPermission, and check areNotificationsEnabled() 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: pass today in, computed from an injected Clock.
  • Collecting a Room Flow in a plain LaunchedEffect. The collection keeps running while the app is in the background, because the composition stays alive when the activity is stopped. Fix: use collectAsStateWithLifecycle.
  • 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: bump version, add a Migration or an AutoMigration, and test it with MigrationTestHelper.

Code review finding

Reminder runs every 15 minutes and still arrives late
  • The reminder is a PeriodicWorkRequest with 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_ALARM to the manifest, which Google Play does not allow for a habit tracker.
The fix
  • Replace it with one unique daily PeriodicWorkRequest whose initial delay is ReminderSchedule.delayUntilNext(...). Use KEEP at app start and CANCEL_AND_REENQUEUE when the user changes the time.
  • Remove USE_EXACT_ALARM. If users really need precise timing, add an opt-in "precise reminders" setting that uses SCHEDULE_EXACT_ALARM, checks canScheduleExactAlarms(), falls back to WorkManager when access is denied, and reschedules on BOOT_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 GlanceAppWidget that loads today's status in provideGlance and renders it in provideContent, a GlanceAppWidgetReceiver declared in the manifest, and a call to updateAll(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 BroadcastReceiver without opening the app.
  • Add a weekly summary screen with a Compose Canvas chart of check-ins over the last 7 days.
  • Add a Room migration test with MigrationTestHelper for 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_NOTIFICATIONS is 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_ALARM is not declared. If an exact path exists, it is opt-in, checks canScheduleExactAlarms(), and reschedules after reboot.
  • StreakCalculator and ReminderSchedule have no Android imports and are tested for empty, single-day, gap, grace, time zone, and DST cases.
  • ViewModels expose StateFlow<UiState> with WhileSubscribed(5_000); screens use collectAsStateWithLifecycle; one-off messages live in state.
  • Navigation uses @Serializable routes.
  • 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_ALARM is denied by default for most new installs on Android 14+), are cleared on reboot, and USE_EXACT_ALARM is 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. today comes from an injected Clock, check-ins are stored as LocalDate, 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 with stateIn(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 provideGlance runs in a background worker, so you load data before provideContent and call updateAll when data changes elsewhere in the app.