DEV Community

Programming Central
Programming Central

Posted on

An Android alarm that restarts itself without you unlocking the phone

Every interval timer I have ever used has the same flaw: it works beautifully while the screen is in your hand, and the moment you lock the phone and put it in your pocket, the thing that matters is behind a PIN. It rings. You take the phone out, you are on a treadmill or mid-sentence in a meeting, and you have to unlock the device, find the app, and press something.

I wanted a timer where 00:00 is a complete interaction, not the start of one. So I built CycleClock: a looping interval alarm that rings at zero, shows a full-screen panel over the lock screen, and puts "STOP ALARM & RESTART" right there — one tap, next cycle scheduled, no PIN, no fingerprint, no app hunting.

This is how it works, and what it actually costs to build it.

What the app does

You set a duration in minutes and seconds — typed, or with 5 and 15 minute presets and ±5 minute steppers — pick an alarm sound if you do not want the system default, tap Start Looping Timer, and the app counts down. At 00:00 it starts a looping alarm sound and vibration, and a full-screen panel appears over whatever is on the lock screen. Two buttons:

  • STOP ALARM & RESTART — silences the alarm and immediately schedules the next cycle with the same duration.
  • Stop & End Session — silences everything and clears the alarm.

The notification shows the same thing, so you can also act from the shade: Cycle #7 · 04:32 remaining, with a Stop action while running and Stop & Restart 01:00 while ringing.

That is the entire product. Everything clever is in how it stays alive.

The four moving parts

There are only four components, and each one exists to solve a specific Android restriction.

Component Job Restriction it works around
LoopTimerService Owns the countdown, the sound, the notification A background app is killed, frozen or Dozed
AlarmManager + TimerActionReceiver Wakes the app at exactly T + interval CountDownTimer dies with the process
LockScreenAlarmActivity Panel on top of the lock screen Activities don't start from the background any more
MainActivity Set the duration, read live state —
                 tap "Start"
MainActivity ───────────────────────┐
   │                                ▼
   │ startForegroundService   LoopTimerService
   │                          ├─ AlarmManager (exact, allow-while-idle)
   │                          │    └─► fires at T+interval, survives Doze
   │                          ├─ foreground notification (live countdown)
   │                          └─ MediaPlayer(USAGE_ALARM) + vibration loop
   │                                   │
   │                                   │ 00:00
   │                                   ▼
   │                          alarm notification + full-screen intent
   │                                   │
   │                                   ▼
   │                          LockScreenAlarmActivity (over lock screen)
   │                                   │
   │                     "STOP ALARM & RESTART"
   │                                   │
   └───── SharedPreferences ◄──────────┘  → next cycle, no unlock
Enter fullscreen mode Exit fullscreen mode

Part 1: the countdown you can trust is not a timer

The tempting design is a CountDownTimer inside the activity. It is also the design that fails: the activity is destroyed the moment the phone locks, and your timer evaporates.

So the countdown is not a timer at all. It is a stored deadline plus a system alarm:

private fun startCountdownCycle(durationSec: Long, cycleCount: Int) {
    val triggerAt = SystemClock.elapsedRealtime() + durationSec * 1000L
    getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit()
        .putBoolean(KEY_IS_RUNNING, true)
        .putBoolean(KEY_IS_RINGING, false)
        .putLong(KEY_TARGET_ELAPSED, triggerAt)
        .apply()

    scheduleExactAlarm(triggerAt)
    startForeground(NOTIF_ID, buildRunningNotification(durationSec, cycleCount))

    uiTicker?.cancel()
    uiTicker = object : CountDownTimer(durationSec * 1000L, 1000L) {
        override fun onTick(millisUntilFinished: Long) {
            val secLeft = (millisUntilFinished + 999L) / 1000L
            val nm = getSystemService(NotificationManager::class.java)
            nm.notify(NOTIF_ID, buildRunningNotification(secLeft, cycleCount))
        }
        override fun onFinish() {}
    }.start()
}
Enter fullscreen mode Exit fullscreen mode

Three things are happening here, and only one of them matters for correctness:

  1. triggerAt is stored as an elapsed-realtime deadline, the single source of truth.
  2. scheduleExactAlarm is registered with the system, which will fire even if this process is dead.
  3. The CountDownTimer only repaints the notification once per second. It is cosmetic. If it is killed, nothing is lost.

Note SystemClock.elapsedRealtime() and not System.currentTimeMillis(). Elapsed realtime is monotonic and includes deep sleep. Wall-clock time can jump backwards when the network corrects it or the user changes the timezone, and an alarm scheduled on a clock that moves is an alarm that fires an hour early or never.

The actual registration is four lines:

private fun scheduleExactAlarm(triggerAtElapsed: Long) {
    val am = getSystemService(AlarmManager::class.java)
    val alarmIntent = PendingIntent.getBroadcast(
        this,
        100,
        Intent(this, TimerActionReceiver::class.java).apply {
            action = ACTION_ALARM_FIRED
        },
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )
    am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtElapsed, alarmIntent)
}
Enter fullscreen mode Exit fullscreen mode

ELAPSED_REALTIME_WAKEUP wakes the CPU from sleep. setExactAndAllowWhileIdle is the only API that still honours the deadline inside Doze. Together they are the difference between "rings at 00:00" and "rings at 00:00, or whenever the system feels like it".

The receiver is deliberately dumb — it just re-enters the service:

class TimerActionReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == LoopTimerService.ACTION_ALARM_FIRED) {
            val serviceIntent = Intent(context, LoopTimerService::class.java).apply {
                action = LoopTimerService.ACTION_ALARM_FIRED
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent)
            } else {
                context.startService(serviceIntent)
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

A BroadcastReceiver gets about ten seconds of main-thread time before the system considers it hung. Doing real work there is how you get an ANR. The service has its own lifetime and, being foreground, keeps one.

Part 2: the service that is allowed to keep running

LoopTimerService is a foreground service with foregroundServiceType="mediaPlayback". That is not a trick to stay alive for free: it is the honest declaration of what the service does — it plays an alarm through AudioAttributes.USAGE_ALARM. Android 14 checks that declaration against runtime behaviour.

Everything the service owns is a private field, and every action arrives as a string extra on onStartCommand:

when (intent?.action) {
    ACTION_START -> {
        val sec = intent.getLongExtra(
            EXTRA_DURATION_SEC,
            prefs.getLong(KEY_DURATION_SEC, 60L)
        )
        prefs.edit()
            .putLong(KEY_DURATION_SEC, sec)
            .putInt(KEY_CYCLE_COUNT, 1)
            .apply()
        startCountdownCycle(sec, 1)
    }
    ACTION_ALARM_FIRED -> {
        triggerContinuousAlarm()
    }
    ACTION_STOP_AND_RESTART -> {
        stopAlarmAudioAndVibration()
        val sec = prefs.getLong(KEY_DURATION_SEC, 60L)
        val nextCycle = prefs.getInt(KEY_CYCLE_COUNT, 1) + 1
        prefs.edit().putInt(KEY_CYCLE_COUNT, nextCycle).apply()
        startCountdownCycle(sec, nextCycle)
    }
    ACTION_STOP_ALL -> {
        stopAlarmAudioAndVibration()
        cancelExactAlarm()
        uiTicker?.cancel()
        prefs.edit()
            .putBoolean(KEY_IS_RUNNING, false)
            .putBoolean(KEY_IS_RINGING, false)
            .apply()
        stopForeground(STOP_FOREGROUND_REMOVE)
        stopSelf()
    }
}
Enter fullscreen mode Exit fullscreen mode

That is the entire state machine: four actions. No bound service, no Binder, no callbacks. onStartCommand returns START_STICKY, and every action is idempotent enough that being started twice is harmless.

When the alarm fires, the service resolves which sound to play — the one the user picked, if any — and hands it to a helper that either returns a playing MediaPlayer or fails quietly:

private fun playAlarmSound(uri: Uri): Boolean {
    val player = MediaPlayer()
    return try {
        player.setAudioAttributes(
            AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build()
        )
        player.setDataSource(applicationContext, uri)
        player.isLooping = true
        player.prepare()
        player.start()
        mediaPlayer = player
        true
    } catch (_: Exception) {
        player.release()
        false
    }
}
Enter fullscreen mode Exit fullscreen mode

USAGE_ALARM routes it through the alarm volume channel, which is what makes it audible when the media volume is down and, on most devices, when the phone is on vibrate. isLooping = true is the whole "continuous" behaviour — no re-triggering, no gaps.

The caller tries the saved URI first and falls back to the system alarm when the helper returns false, which is how a stale ringtone stops being a crash and becomes a slightly wrong sound. The picker never touches the service: MainActivity launches RingtoneManager.ACTION_RINGTONE_PICKER through registerForActivityResult, restricted to alarm-type sounds with the silent option disabled, and writes the returned URI into the same preferences file. The service reads it at ring time. That is the entire coupling between the two: one string.

One trap worth knowing: RingtoneManager.getRingtone(...).getTitle(...) hands back a title localised by the system. The same line of code renders "Predefinita" on an Italian phone and "Par défaut" on a French one, in an app whose every other label is English. The screen therefore shows the file's display name — OpenableColumns.DISPLAY_NAME, minus the audio extension — and hardcodes "Default Alarm" for the default URI. Labels the app owns stay in one language; names the system owns do not have to.

Vibration is started right after the audio, in the same function. That branch is uglier than it should be because VibratorManager only exists from API 31:

val pattern = longArrayOf(0, 500, 250, 500, 350)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    val vm = getSystemService(VibratorManager::class.java)
    vm.defaultVibrator.vibrate(VibrationEffect.createWaveform(pattern, 0))
} else {
    @Suppress("DEPRECATION")
    val v = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        v.vibrate(VibrationEffect.createWaveform(pattern, 0))
    } else {
        @Suppress("DEPRECATION")
        v.vibrate(pattern, 0)
    }
}
Enter fullscreen mode Exit fullscreen mode

The trailing 0 in createWaveform(pattern, 0) is the repeat index: zero means "loop from the beginning forever". Without it the phone buzzes once and goes quiet, which is worse than no vibration at all because you stop trusting it.

Part 3: getting on top of the lock screen

An activity cannot simply be launched over a locked phone from the background. Android 10 removed that, and Android 12 tightened it. The supported path is a full-screen intent on a high-importance notification, and an activity that declares it wants to be seen over the keyguard:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
    setShowWhenLocked(true)
    setTurnScreenOn(true)
} else {
    @Suppress("DEPRECATION")
    window.addFlags(
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
    )
}
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
Enter fullscreen mode Exit fullscreen mode

setShowWhenLocked draws over the keyguard, setTurnScreenOn lights the display, FLAG_KEEP_SCREEN_ON stops the panel from dimming while the alarm is still ringing. The same three flags are declared in the manifest, so they apply even before onCreate runs:

<activity
    android:name=".LockScreenAlarmActivity"
    android:exported="false"
    android:launchMode="singleTop"
    android:showWhenLocked="true"
    android:turnScreenOn="true"
    android:excludeFromRecents="true" />
Enter fullscreen mode Exit fullscreen mode

singleTop matters: a second alarm while the panel is already open must not stack a duplicate panel.

The service also calls startActivity() on a best-effort basis, but do not be fooled by it — on modern Android that call is frequently refused when the app is in the background. The reliable path is the notification:

return NotificationCompat.Builder(this, CHANNEL_ALARM)
    .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
    .setContentTitle("Cycle #$cycleCount Complete ($label)")
    .setContentText("Tap Stop & Restart to begin $label again")
    .setCategory(NotificationCompat.CATEGORY_ALARM)
    .setPriority(NotificationCompat.PRIORITY_MAX)
    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
    .setOngoing(true)
    .setFullScreenIntent(fullScreenPending, true)
    .addAction(0, "Stop & Restart $label", restartPending)
    .build()
Enter fullscreen mode Exit fullscreen mode

CATEGORY_ALARM is not decoration. It tells the system this is an alarm rather than a chat, which affects ranking, DND and the full-screen policy. setFullScreenIntent(pending, true) with the high-priority argument is what turns a heads-up notification into a lock-screen takeover.

Two channels do all the work:

nm.createNotificationChannel(
    NotificationChannel(CHANNEL_RUNNING, "Active Loop Timer", NotificationManager.IMPORTANCE_LOW)
)
nm.createNotificationChannel(
    NotificationChannel(CHANNEL_ALARM, "Loop Alarm Alert", NotificationManager.IMPORTANCE_HIGH).apply {
        lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        setBypassDnd(true)
    }
)
Enter fullscreen mode Exit fullscreen mode

IMPORTANCE_LOW for the running countdown keeps it silent and pinned; IMPORTANCE_HIGH plus VISIBILITY_PUBLIC is what allows the alarm content on the lock screen at all. The channel ID is cycleclock_alarm_v1 on purpose: channel settings are immutable once created, so the v1 suffix is the only honest way to ship different behaviour later.

Part 4: the button that does not need an unlock

Here is the part I care about most. The button on the lock-screen panel is not an activity transition. It targets the service directly:

btnStopRestart.setOnClickListener {
    val restartIntent = Intent(this, LoopTimerService::class.java).apply {
        action = LoopTimerService.ACTION_STOP_AND_RESTART
    }
    startService(restartIntent)
    finish()
}
Enter fullscreen mode Exit fullscreen mode

And the notification action does the same thing without the activity at all:

val restartPending = PendingIntent.getService(
    this,
    103,
    Intent(this, LoopTimerService::class.java).apply { action = ACTION_STOP_AND_RESTART },
    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
Enter fullscreen mode Exit fullscreen mode

PendingIntent.getService means the system can deliver that intent to the service even though the app is locked and in the background. No screen unlock, no permission prompt, no activity launch. The service silences the media player, cancels the vibration, increments the cycle counter and schedules the next exact alarm. The whole restart is a single onStartCommand.

This is also why the app needs no "background restart" hack, no accessibility service and no screen-wake trickery. The button is a notification action, and notification actions are one of the few interactions Android genuinely allows from a locked device.

State, and why it lives in SharedPreferences

The activity and the service are different processes-worth of lifetime, and the activity is destroyed constantly. They talk through one thing only: the default SharedPreferences file.

if (ringing) {
    tvCountdown.text = "00:00"
    tvStatus.text = "ALARM RINGING · Cycle #$cycle Complete"
} else if (running) {
    val target = prefs.getLong(LoopTimerService.KEY_TARGET_ELAPSED, 0L)
    val leftSec = ((target - SystemClock.elapsedRealtime()).coerceAtLeast(0L) + 999L) / 1000L
    tvCountdown.text = String.format("%02d:%02d", leftSec / 60, leftSec % 60)
    tvStatus.text = "Cycle #$cycle Running · Lock-Screen Ready"
} else {
    tvCountdown.text = String.format("%02d:%02d", durationSec / 60, durationSec % 60)
    tvStatus.text = "Ready · Set interval and tap Start"
}
Enter fullscreen mode Exit fullscreen mode

Six keys — duration, cycle count, running, ringing, the elapsed-realtime deadline and the chosen ringtone URI — in a single preferences file. The countdown the user sees is recomputed from the stored deadline every 250 ms, so it cannot drift out of sync with the alarm that is actually pending: both read the same deadline.

The + 999L) / 1000L idiom is rounding up rather than truncating. Without it, 59.6 seconds displays as 00:59 for almost a full second after it should read 01:00, and the display looks like it is losing time.

The permissions, and which ones fail silently

Seven manifest permissions. Three of them are the ones that ruin first runs:

Permission Needed for If it is missing
SCHEDULE_EXACT_ALARM setExactAndAllowWhileIdle The alarm is dropped or delivered late
POST_NOTIFICATIONS The running notification and the alarm The service runs, the panel may still appear, but there is no way to act from the shade
USE_FULL_SCREEN_INTENT The lock-screen takeover A normal heads-up notification instead
FOREGROUND_SERVICE + FOREGROUND_SERVICE_MEDIA_PLAYBACK The service Immediate crash on startForeground
WAKE_LOCK Waking the CPU The alarm can be missed in deep sleep
VIBRATE The waveform Silent vibration

Exact alarms have their own gate from Android 12, and it is a Settings screen rather than a dialog:

private fun ensureExactAlarmPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        val am = getSystemService(AlarmManager::class.java)
        if (!am.canScheduleExactAlarms()) {
            startActivity(
                Intent(
                    Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM,
                    Uri.parse("package:$packageName")
                )
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The app calls this on every Start tap, which is the right place: checking once at launch gives you a permission prompt the user has long forgotten by the time it matters.

Building it

There is nothing exotic in the build. AGP 8.5.2, Kotlin 1.9.24, compileSdk 35, targetSdk 35, and a deliberately low minSdk 26 so the app installs on anything from 2017 onwards:

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

android {
    namespace = "com.cycleclock.app"
    compileSdk = 35

    defaultConfig {
        applicationId = "com.cycleclock.app"
        minSdk = 26
        targetSdk = 35
        versionCode = 1
        versionName = "1.0.0"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }
    kotlinOptions {
        jvmTarget = "17"
    }
}

dependencies {
    implementation("androidx.core:core-ktx:1.13.1")
    implementation("androidx.appcompat:appcompat:1.7.0")
}
Enter fullscreen mode Exit fullscreen mode

Two dependencies, both AndroidX, because the UI is a ScrollView of LinearLayouts with hardcoded hex colours and the only thing borrowed is NotificationCompat. minSdk 26 also has a side effect worth admitting: half the Build.VERSION.SDK_INT >= O checks in the code are dead branches kept for readability, not necessity.

The interesting part is that you do not need a computer with Android Studio to get an APK. The workflow in .github/workflows/build-apk.yml builds it on GitHub's runners:

name: Build Android APK

on:
  push:
    branches: [ main, master ]
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '17'
      - uses: gradle/actions/setup-gradle@v4
        with:
          gradle-version: '8.7'
      - name: Build Debug APK
        run: gradle assembleDebug
      - name: Upload APK Artifact
        uses: actions/upload-artifact@v4
        with:
          name: CycleClock-debug-apk
          path: app/build/outputs/apk/debug/app-debug.apk
Enter fullscreen mode Exit fullscreen mode

No Gradle wrapper is committed. gradle/actions/setup-gradle installs the requested version on the runner, and the command is plain gradle assembleDebug. That is a deliberate trade: the repo stays small and there is no gradlew binary to keep in sync, at the cost of being tied to whatever Gradle the workflow pins.

The build takes under two minutes and the artifact is a ~3 MB debug APK, signed with the debug key. Good enough for sideloading onto your own phone, not for the Play Store.

Things that will still bite you

Six hard-won notes if you build something similar:

  1. Android 14 doesn't grant full-screen intent to everyone. Since API 34, USE_FULL_SCREEN_INTENT is only auto-granted to calling and alarm apps. Everything else has to send the user to ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT. With targetSdk 35 this is a real, testable failure: the notification arrives and the panel does not.
  2. Do Not Disturb beats setBypassDnd. The channel asks to bypass DND, but Android only honours it when the user has granted notification policy access. Without it, a DND phone rings nothing.
  3. OEM battery managers ignore all of this. Xiaomi, Huawei, Samsung and OnePlus have their own killers that fire after the app has been in the background for a while. The exact alarm helps; nothing in the app can fully prevent it. This needs a per-device allowlist, documented rather than coded.
  4. There is no reboot receiver. The deadline is stored in elapsedRealtime, which resets on reboot, and nothing listens for BOOT_COMPLETED. Reboot during a cycle and the loop is simply gone.
  5. Channel settings are forever. Once IMPORTANCE_HIGH is registered, changing the code does nothing for existing installs. Bump the channel ID — hence _v1.
  6. startActivity from a service is not a guarantee. It works when you are in the foreground and is refused otherwise. Treat the full-screen intent as the contract and the explicit call as a nicety.

What I would build next

The honest list, in the order I would do it: a BOOT_COMPLETED receiver that re-arms the alarm from a wall-clock deadline, since elapsedRealtime resets on reboot; a "grant DND access" step in the setup flow; an audible confirmation when a cycle restarts (so the restart is verifiable without looking); and a foreground service type that survives the stricter Android 15 checks.

None of those change the core design, which is the point. An interval alarm is not a timer problem. It is a problem of persistence and permission: who wakes you up, and who lets you say stop.


The whole thing — 631 lines of Kotlin, the workflow, the layouts — is here, under the MIT license:

github.com/edgarmilvus/CycleClock

Build it in CI, download CycleClock-debug-apk, install it, and let it ring in your pocket. Then tell me which OEM killed it first.

Going further: the Android AI side

CycleClock is deliberately dumb — no network, no model, just the platform doing what it promises. That was the point, and it is why it is a good teacher.

My other work goes the opposite way. The Kotlin & AI Masterclass is a three-volume Leanpub bundle for Android engineers moving into on-device AI:

  • On-Device GenAI with Android Kotlin — Gemini Nano and AICore, Gemma and Llama through MediaPipe, local RAG with Room and embeddings, token streaming with Flow and Compose.
  • Edge AI Performance with Android Kotlin — NPU, GPU and DSP delegates, INT8 and FP16 quantization, pruning and distillation, zero-copy CameraX pipelines, thermal profiling.
  • Android AI Agents — tool calling and function injection, ReAct loops, screen and intent awareness, human-in-the-loop guardrails.

Get the bundle on Leanpub →

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The stored-deadline-plus-exact-alarm design is the part I would steal — making the CountDownTimer purely cosmetic so a dead process loses nothing is the kind of decision that only comes from having a timer die on you in the field. The permission table is honest too: SCHEDULE_EXACT_ALARM failing silently is exactly the kind of first-run bug that looks like your code is broken when it is actually a Settings screen the user never saw.

Two things I am curious about: you flagged that OEM battery managers ignore all of this — have you actually seen CycleClock get killed on a Xiaomi or Samsung yet, and did anything (like the mediaPlayback foreground type) help at all? And on the missing BOOT_COMPLETED receiver, would you re-arm from a wall-clock deadline, or store both the elapsed and wall-clock deadlines so a reboot can rebuild the cycle?