On this page
Testing exact time-based execution and hardware clock synchronization on Android physical devices has long been one of the most unpredictable challenges in mobile quality assurance. While standard software unit tests can easily verify that a timestamp calculation utility functions in memory, validating real hardware wakeups requires navigating Android's aggressive battery optimization policies, system Doze states, and shifting OS permission boundaries. Ever since Android 6.0 Marshmallow introduced Doze mode and App Standby, the operating system has reserved the authority to defer, batch, and throttle background tasks to preserve device battery life. For background workers that tolerate latency windows, Google recommends WorkManager. However, for time-critical features such as medicine reminder alerts, trading trigger alarms, critical calendar alerts, and automated security handshakes, applications must schedule exact alarms via Android's AlarmManager. With Android 12 (API level 31) and Android 13/14 (API levels 33 and 34), Google drastically tightened exact alarm scheduling by introducing the SCHEDULE_EXACT_ALARM and USE_EXACT_ALARM permissions, revoking default access for non-calendar and non-alarm apps, and terminating processes that fail to check canScheduleExactAlarms() before dispatch. In-process test runners like Espresso cannot simulate device sleep cycles, verify system alarm queues, or grant system appops privileges without crashing. By connecting autonomous AI coding agents like Claude Code to real physical Android smartphones through ScreenSync MCP, developers can orchestrate comprehensive, deterministic exact alarm verification pipelines directly from the terminal.
Key Takeaways
- System-level alarm queue auditing: ScreenSync MCP empowers Claude Code to inspect the Android OS system alarm queue directly via
adb shell dumpsys alarm, validating pending alarm trigger timestamps, batching flags, and WakeLock states without relying on in-process test mocks. - Dynamic permission and AppOps simulation: Claude Code programmatically grants, revokes, and verifies
SCHEDULE_EXACT_ALARMpermissions usingadb shell cmd appops setcommands, thoroughly testing application fallbacks and settings redirection dialogs. - Physical Doze and deep idle verification: AI agents force connected devices into deep Doze mode via
adb shell dumpsys deviceidle force-idle, asserting that alarms configured withsetExactAndAllowWhileIdle()andsetAlarmClock()wake the hardware CPU and deliver broadcast intents on schedule. - Ultra-low latency visual mirroring: Physical device display frames stream to the desktop workstation via native Android MediaProjection at approximately 94 milliseconds median latency over local Wi-Fi, requiring zero root privileges and zero ADB bandwidth.
- Comprehensive UI and telemetry triage: Claude Code combines semantic accessibility node inspection through
get_ui_hierarchy, real-time system log parsing viaget_logcat, and high-resolution screen verification viaget_latest_screenshotto catchSecurityExceptioncrashes and UI timing regressions. - Unified 226-tool automation plane: ScreenSync MCP bridges 29 mobile and desktop tools (12
control_*, 3os_*, and 14 capture tools) with 197 browser tools to validate end-to-end multi-surface workflows linking Android hardware alerts to cloud dashboards.
Why In-Process Test Suites Fail at Exact Alarm and Clock Synchronization
In-process test suites like Espresso fail at exact alarm testing because execution takes place inside an isolated application sandbox rather than the system server process. Test runners cannot simulate device sleep, cannot inspect the system AlarmManagerService state, and cannot observe hardware wakeups after the CPU enters deep low-power sleep states.
To comprehend why automated exact alarm testing has historically proven so fragile, software engineers must analyze the execution architecture of Android instrumentation runners. When a developer triggers an automated test suite through Espresso, AndroidX Test, or standard JUnit runners, the Android framework compiles an auxiliary test APK that shares the target application's Linux user identifier (UID) and memory space via InstrumentationRegistry. The test runner interacts strictly with the application's main thread looper (Looper.getMainLooper()) and decor view hierarchy.
However, when an application invokes AlarmManager.setExact() or AlarmManager.setExactAndAllowWhileIdle(), the application does not execute the timer itself. Instead, it marshals an intent parcel across Binder IPC to the central system service: com.android.server.alarm.AlarmManagerService. Once the alarm intent is registered within the operating system's internal priority queue, the application activity can be paused, backgrounded, or completely destroyed by the kernel low-memory killer (LMK).
When the scheduled execution moment arrives, the hardware Real-Time Clock (RTC) or CPU elapsed timer triggers an interrupt. The Linux kernel wakes from its low-power sleep state, acquires a kernel-level WakeLock, and notifies AlarmManagerService. The system service then constructs an explicit broadcast intent or launches the registered PendingIntent, waking the target application process from a cold state.
Because in-process test runners like Espresso execute inside the application process, they suffer from three fatal structural limitations:
- Inability to Simulate Power Suspensions: Espresso cannot force the operating system into Doze mode or simulate hardware sleep states. If the test runner forces the device into sleep mode, the test runner's own background threads are frozen alongside the target application, causing the continuous integration test runner to time out and fail.
- Blindness to System Service Queues: In-process view matchers (
onView(withId(R.id.status_text))) can only inspect the application's immediate UI state. They have no visibility into whether the OS accepted the exact alarm, whether the system batched the alarm into an inexact maintenance window, or whether the alarm is scheduled under RTC vs. ELAPSED_REALTIME clocks. - Crashing on Process Death: When evaluating whether an exact alarm successfully wakes an application from a completely terminated or backgrounded state, killing the app process terminates the instrumentation runner immediately, aborting the test before the alarm can fire.
ScreenSync MCP resolves this architectural dilemma by decoupling the test orchestrator from the target device process. Operating over a Model Context Protocol interface, Claude Code executes on the host workstation. ScreenSync MCP communicates with the physical Android device over ADB and local network sockets. Claude Code can manipulate system power states, inspect system alarm queues, trigger synthetic time skips, and observe real device screen responses via MediaProjection—without its own execution loop ever being suspended.
| Testing Dimension | In-Process Espresso / Robolectric | Standalone UIAutomator Scripts | Cloud Device Farms (SauceLabs / Firebase) | ScreenSync MCP + Claude Code (Physical Device) |
|---|---|---|---|---|
| System Alarm Queue Auditing | Impossible; cannot read system server memory | Partial; requires external shell execution scripts | Limited; cloud wrappers restrict adb dumpsys access | Native; Claude Code parses adb shell dumpsys alarm in real time |
| Doze Mode Simulation | Impossible; freezing CPU halts test runner | Brittle; requires coordinating async sleep commands | Inconsistent; cloud hosts frequently disable deviceidle | Deterministic; forces Doze via ADB and monitors wakeups |
| Exact Permission Manipulation | Mocked only; cannot toggle real OS appops | Possible via manual adb commands in bash | Highly restricted; appops commands often blocked | Automated; agent toggles SCHEDULE_EXACT_ALARM dynamically |
| Process Death Relaunch | Fails; killing app kills the test instrumentation | Difficult; requires complex lifecycle monitoring | Slow; re-establishing cloud video stream adds lag | Instantaneous; agent monitors process rebirth via get_logcat |
| System Settings Navigation | Fails; cannot cross into com.android.settings |
Prone to OEM selector breakage across Android versions | High flakiness due to cloud touch coordinate drift | Robust; inspects real accessibility trees via get_ui_hierarchy |
| Display Verification Overhead | High in-memory bitmap capture latency | Low framerate screencap consuming ADB bandwidth | Video stream compressed with significant WebRTC delay | Native MediaProjection stream (~94 ms latency) via get_latest_screenshot |
Android Exact Alarm Architecture: SCHEDULE_EXACT_ALARM, AppOps, and Doze Mode
Android exact alarm architecture enforces strict battery governance through dangerous AppOps permissions and system power states. Android 12 introduced SCHEDULE_EXACT_ALARM, while Android 13 and 14 restrict default grants to alarm clock and calendar applications, requiring explicit permission checks, user settings redirections, and specialized idle-wake APIs to prevent background execution failures.
Understanding modern exact alarm development requires a comprehensive grasp of Android's power management evolution across recent API levels. Android distinguishes sharply between inexact alarms and exact alarms:
- Inexact Alarms (
set(),setInexactRepeating()): The Android OS groups inexact alarms across all running applications into shared execution batches. The OS fires these alarms simultaneously to minimize how frequently the radio and CPU wake from low-power states. Inexact alarms are ideal for general background synchronizations and cache invalidations, and developers should pair them with testing Android WorkManager with Claude Code and MCP for battery-efficient scheduling. - Exact Alarms (
setExact(),setExactAndAllowWhileIdle(),setAlarmClock()): The OS guarantees delivery at the exact scheduled millisecond, with zero batching or deferral under normal operational conditions. Because exact alarms force the CPU out of low-power states, excessive exact alarms cause severe battery drain, as explored in our guide on testing Android battery drain and Doze with Claude Code and MCP.
Modern Android Permission Restrictions: Android 12 to Android 15
To protect device battery longevity, Google introduced progressive security barriers around exact alarms:
- Android 12 (API 31) - The
SCHEDULE_EXACT_ALARMPermission: Android 12 introducedandroid.permission.SCHEDULE_EXACT_ALARM. Declaring this in the manifest grants the capability by default, but users can revoke it at any time in system settings under Special App Access > Alarms & reminders. CallingsetExact()without this permission throws a fatalSecurityException. - Android 13 (API 33) - The
USE_EXACT_ALARMPermission: For dedicated alarm clocks, stopwatches, and calendar applications, Google introducedandroid.permission.USE_EXACT_ALARM. This permission is granted automatically on installation and cannot be revoked by the user. However, apps published on Google Play must undergo strict policy evaluations; non-qualifying apps that declare this permission face store rejection. - Android 14 (API 34) - Default-Deny Policy for
SCHEDULE_EXACT_ALARM: In Android 14, newly installed applications targeting API 34+ haveSCHEDULE_EXACT_ALARMdenied by default. Applications must dynamically checkalarmManager.canScheduleExactAlarms(). If false, the application must display an educational rationale dialog and direct the user toSettings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM. - Broadcast Receivers and Foreground Services: When an exact alarm fires while the device is in deep Doze, starting a foreground service from the broadcast receiver requires the
FOREGROUND_SERVICEpermission and must adhere to user-initiated constraints, as detailed in our guide on testing Android foreground services with Claude Code and MCP.
| Android OS Release | Target API Level | Manifest Permission Constant | Default Grant State | User Revocation Vector | Critical API Check |
|---|---|---|---|---|---|
| Android 6.0 - 11 | API 23 - 30 | None required for standard exact alarms | Granted by default | None (Always active) | Build.VERSION.SDK_INT |
| Android 12 - 12L | API 31 - 32 | SCHEDULE_EXACT_ALARM |
Granted on install | Special App Access > Alarms & reminders | alarmManager.canScheduleExactAlarms() |
| Android 13 | API 33 | USE_EXACT_ALARM (Alarms/Calendars) or SCHEDULE_EXACT_ALARM |
USE_EXACT_ALARM: Granted; SCHEDULE_EXACT_ALARM: Granted |
Revocable if using SCHEDULE_EXACT_ALARM |
Policy compliance check |
| Android 14 - 15 | API 34 - 35 | SCHEDULE_EXACT_ALARM |
Denied on install (Target API 34+) | System Settings Toggle | Runtime check + ACTION_REQUEST_SCHEDULE_EXACT_ALARM |
Production Kotlin Implementation: Resilient Exact Alarm Architecture
Below is a robust, production-grade Kotlin implementation demonstrating defensive exact alarm scheduling with runtime capability verification, fallback handling, and broadcast intent registration:
package com.screensync.alarms.precision
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.core.content.ContextCompat
class ExactAlarmScheduler(private val context: Context) {
private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
companion object {
private const val TAG = "ExactAlarmScheduler"
const val ACTION_EXACT_ALARM_TRIGGER = "com.screensync.alarms.ACTION_EXACT_TRIGGER"
const val EXTRA_ALARM_PAYLOAD = "extra_alarm_payload"
const val REQUEST_CODE_EXACT = 4091
}
/**
* Verifies whether the application currently holds permission to schedule exact alarms.
* On Android 12+ (API 31+), queries AlarmManager.canScheduleExactAlarms().
*/
fun hasExactAlarmPermission(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
alarmManager.canScheduleExactAlarms()
} else {
true // Prior to Android 12, exact alarms did not require special app access
}
}
/**
* Schedules a time-critical exact alarm that wakes the CPU even in deep Doze mode.
* Falls back gracefully to windowed alarms if exact scheduling is withheld.
*/
fun schedulePrecisionAlarm(triggerAtMillis: Long, payloadMessage: String): Boolean {
val intent = Intent(context, ExactAlarmReceiver::class.java).apply {
action = ACTION_EXACT_ALARM_TRIGGER
putExtra(EXTRA_ALARM_PAYLOAD, payloadMessage)
}
val pendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE_EXACT,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
return if (hasExactAlarmPermission()) {
try {
// setExactAndAllowWhileIdle guarantees execution during Doze sleep
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
triggerAtMillis,
pendingIntent
)
Log.i(TAG, "Successfully scheduled exact RTC_WAKEUP alarm for timestamp: $triggerAtMillis")
true
} catch (securityEx: SecurityException) {
Log.e(TAG, "SecurityException while scheduling exact alarm despite check: ${securityEx.message}")
false
}
} else {
Log.w(TAG, "Exact alarm permission withheld. Falling back to inexact window or requesting access.")
// Schedule inexact fallback to prevent complete failure
alarmManager.setWindow(
AlarmManager.RTC_WAKEUP,
triggerAtMillis,
15 * 60 * 1000L, // 15-minute tolerance window
pendingIntent
)
false
}
}
/**
* Generates an intent to redirect the user to the system Special App Access settings.
*/
fun createSettingsRedirectionIntent(): Intent? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM).apply {
data = android.net.Uri.parse("package:${context.packageName}")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
} else {
null
}
}
}
class ExactAlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ExactAlarmScheduler.ACTION_EXACT_ALARM_TRIGGER) {
val message = intent.getStringExtra(ExactAlarmScheduler.EXTRA_ALARM_PAYLOAD) ?: "Default Alert"
Log.i("ExactAlarmReceiver", "Exact alarm fired successfully! Payload: $message")
// Handle time-critical task (dispatch notification, sound audio, or process event)
}
}
}
When validating security boundaries, developers should also consult testing Android runtime permissions with Claude Code and MCP to verify how runtime dialogs and permission controllers behave under various OEM distributions.
How ScreenSync MCP Bridges Claude Code to the Android Alarm Subsystem
ScreenSync MCP bridges Claude Code to the Android alarm subsystem by combining decoupled MediaProjection frame mirroring with direct ADB shell telemetry. Claude Code queries dumpsys alarm to verify hardware RTC registrations, executes dumpsys deviceidle to test Doze wakeups, and validates application UI transitions through accessibility trees and screen captures.
The breakthrough of utilizing ScreenSync MCP for exact alarm testing lies in its tripartite architecture, which completely eliminates the constraints of in-process testing:
+-----------------------------------------------------------------------------------+
| LOCAL DESKTOP WORKSTATION |
| |
| +--------------------+ stdio JSON-RPC +------------------------+ |
| | Claude Code | <===========================> | ScreenSync MCP | |
| | (CLI / Cursor) | | Desktop Hub | |
| +--------------------+ | (Port 3000) | |
+-------------------------------------------------------+---------------------------+
|
+------------------------------+
|
Local Wi-Fi / LAN | ADB Daemon (USB / Wireless)
MediaProjection Stream | AppOps, Dumpsys & Touch Inputs
(Sub-100ms Screen Frames) | (control_tap, get_logcat)
v v
+-------------------------------------------------------+
| PHYSICAL ANDROID DEVICE |
| |
| +-----------------------------------------------+ |
| | ScreenSync MCP (com.screensync.mcp) | |
| | MediaProjection Service (No Root/No ADB) | |
| +-----------------------------------------------+ |
| | Target Android Application | |
| | ExactAlarmScheduler -> AlarmManager | |
| +-----------------------------------------------+ |
| | System Server (AlarmManagerService) | |
| +-----------------------------------------------+ |
| | Real-Time Clock (RTC) Hardware / PMIC| |
| +-----------------------------------------------+ |
+-------------------------------------------------------+
1. Direct Alarm System Inspection via dumpsys alarm
When Claude Code tests whether an alarm is scheduled with exact parameters, it does not have to guess. The agent dispatches terminal commands through ADB to inspect the system AlarmManagerService table:
adb shell dumpsys alarm | grep -A 8 "com.screensync.alarms"
The system output returns the exact hardware timer registration:
RTC_WAKEUP #0: Alarm{7d8a9e1 type 0 origWhen 1763212800000 whenElapsed +1m30s500ms com.screensync.alarms}
tag=*walarm*:com.screensync.alarms.ACTION_EXACT_TRIGGER
type=RTC_WAKEUP origWhen=1763212800000 window=0 exact=true
flags=0x5 (FLAG_ALLOW_WHILE_IDLE | FLAG_WAKE_FROM_IDLE)
operation=PendingIntent{4e318a2: PendingIntentRecord{b2a19c4 com.screensync.alarms broadcastIntent}}
Claude Code parses this output to verify three critical parameters:
window=0 exact=true: Confirms that the system accepted the request as an exact alarm rather than batching it into a window.FLAG_ALLOW_WHILE_IDLE: Confirms that the alarm was registered viasetExactAndAllowWhileIdle()orsetAlarmClock(), guaranteeing it will wake the device during Doze sleep.whenElapsed: Confirms the exact expected delivery delta.
2. High-Speed Visual Capture via Native MediaProjection
While system dumps verify backend registration, visual verification confirms whether the user interface displays the correct timer countdown and educational cards. ScreenSync MCP captures display frames using Android's native MediaProjection API (Android 7.0 or higher). Display capture requires zero device rooting and consumes zero ADB bandwidth, maintaining a median latency of approximately 94 milliseconds over a local area network (LAN). To understand how screen capture pipelines operate across various mobile testing configurations, explore our technical breakdown on how screen MCP servers capture Android screen.
3. The 226-Tool Ecosystem Advantage
ScreenSync MCP exposes 226 MCP tools to developer agents:
- 29 Phone & Desktop Tools: Including 12 device control tools (
control_tap,control_swipe,control_type,control_key,control_open_url,control_launch_app), 3 operating system automation tools (os_mouse_click,os_type,os_hotkey), and 14 capture and telemetry tools (get_latest_screenshot,get_ui_hierarchy,get_logcat,record_screen,get_device_status). - 197 Browser Tools: The
web_*suite operates through an authenticated Chrome/Edge browser extension. When alarm events synchronize with cloud push notifications, database records, or web monitoring portals, Claude Code can switch effortlessly between native Android screen validation and web browser checks within a single automated run. For an exhaustive breakdown of every available tool, consult our complete Android MCP tool reference deep dive.
Step-by-Step Setup: Workstation Hub, Physical Device, and Claude Code Registration
Configuring ScreenSync MCP for exact alarm testing requires launching the desktop hub on Node.js 18, registering the stdio MCP server in Claude Code, and connecting an Android 7.0+ device via USB or wireless debugging. Establishing reverse port forwarding guarantees continuous visual verification during automated permission state sweeps.
Engineering teams can deploy this automated testing harness on Windows, macOS, or Linux through five sequential steps:
Step 1: Workstation and Hardware Prerequisites
Ensure your testing workstation meets the following operational baseline:
- Workstation Environment: Windows 10/11, macOS, or Linux running Node.js 18 or later with
adb(Android Platform Tools) installed and accessible in your systemPATH. - Physical Smartphone: An authentic Android device running Android 7.0 (API level 24) or higher connected via USB cable or local Wi-Fi.
- Application Build: Debug build of your application installed with exact alarm capabilities configured.
Step 2: Launch the Desktop Hub
Download the ScreenSync MCP desktop hub distribution from screensyncmcp.tech and extract the archive to a permanent workstation directory. Execute the platform-specific launcher:
# On Windows (PowerShell or Command Prompt)
cd C:\tools\screensync-hub
.\start-hub.bat
# On macOS or Linux (Terminal)
cd ~/tools/screensync-hub
chmod +x start-hub.sh
./start-hub.sh
The desktop hub initializes an HTTP server on port 3000 to ingest local MediaProjection video frames and prepares a JSON-RPC Model Context Protocol server over stdio. The console output displays your unique authentication token (SCREEN_SYNC_TOKEN). For comprehensive documentation, visit the official ScreenSync MCP setup guide.
Step 3: Register ScreenSync MCP with Claude Code
Register the desktop hub with the Claude Code CLI in your terminal:
claude mcp add screensync node "/path/to/screensync-hub/screensync-hub.js"
If you are developing inside Claude Desktop, edit your claude_desktop_config.json file (Settings > Developer > Edit Config):
{
"mcpServers": {
"screensync": {
"command": "node",
"args": ["/path/to/screensync-hub/screensync-hub.js"],
"env": {
"SCREEN_SYNC_TOKEN": "your_authenticated_token_here"
}
}
}
}
(Note: ScreenSync MCP integrates with local stdio MCP clients including Claude Code, Claude Desktop, Cursor, and VS Code agent mode. ChatGPT's web application requires remote HTTPS endpoints and does not support local stdio processes).
Step 4: Install the Android Application and Authorize MediaProjection
- Download the free ScreenSync MCP application (package
com.screensync.mcp) from Google Play. - Open the application. Allow local network mDNS discovery to automatically detect your desktop hub on the local Wi-Fi subnet, or scan the pairing QR code displayed in the hub console.
- Tap Start Projection and confirm Android's native MediaProjection screen capture consent prompt.
- Unlock Developer Options on your smartphone (Settings > About Phone > tap Build Number 7 times) and enable USB Debugging (or Wireless Debugging). If you prefer wireless operation, review our guide on Android wireless debugging for MCP servers.
- Verify ADB connectivity by running
adb devicesin your workstation terminal.
Step 5: Establish USB Reverse Port Forwarding
To ensure uninterrupted visual streaming even when testing network-isolated states or toggling airplane mode, configure USB reverse port forwarding:
adb reverse tcp:3000 tcp:3000
With reverse port forwarding active, MediaProjection frames stream directly over the high-speed physical USB connection, guaranteeing that video frames bypass external network latency.
Practical QA Workflows: Permissions, Doze Mode Wakeups, and Clock Drift
Practical exact alarm QA workflows validate three essential pathways: testing user permission revocations and appops state toggles, forcing the device into deep Doze mode to verify idle wakeups, and triaging clock drift across system wall-clock adjustments. Claude Code automates these multi-step scenarios by coordinating ADB commands with real-time logcat monitoring.
Workflow 1: Validating SCHEDULE_EXACT_ALARM Revocation and Settings Navigation
When testing applications targeting Android 13 or 14, QA teams must verify that the app gracefully handles the absence of exact alarm capabilities without crashing, displaying a clear educational prompt that guides the user to System Settings.
Developer Prompt:
"Claude, launch our app com.screensync.alarms. Revoke SCHEDULE_EXACT_ALARM via ADB appops. Tap 'Schedule Medicine Reminder'. Assert that our educational dialog appears with 'Permission Required' and an 'Enable in Settings' button. Tap 'Enable in Settings', verify that Android System Settings opens to Alarms & Reminders, grant the permission via ADB, return to the app, and verify that the reminder schedules successfully."
Step 1: Revoke Permission via ADB AppOps
Claude Code issues the shell command to strip the special app access privilege:
adb shell cmd appops set com.screensync.alarms SCHEDULE_EXACT_ALARM deny
Step 2: Trigger Alarm Scheduling
Claude Code calls control_launch_app with package com.screensync.alarms. Once the activity renders, it queries get_ui_hierarchy to locate the schedule button and triggers it via control_tap.
Step 3: Assert Educational Fallback Dialog
Claude Code calls get_ui_hierarchy and asserts the presence of the fallback modal:
<node text="Permission Required" resource-id="com.screensync.alarms:id/dialog_title" />
<node text="Exact alarms are required to deliver your medication reminders on time." resource-id="com.screensync.alarms:id/dialog_message" />
<node text="Enable in Settings" resource-id="com.screensync.alarms:id/btn_open_settings" clickable="true" />
Step 4: Tap Button and Verify Settings Transition
Claude Code calls control_tap on btn_open_settings. It then calls get_ui_hierarchy to assert that the foreground window has transitioned into system settings:
<node package="com.android.settings" text="Alarms & reminders" />
<node package="com.android.settings" text="Allow setting alarms" resource-id="android:id/switch_widget" />
Step 5: Grant Permission and Return
Claude Code grants the permission via ADB:
adb shell cmd appops set com.screensync.alarms SCHEDULE_EXACT_ALARM allow
It dispatches control_key with key code 4 (KEYCODE_BACK) to return to the app. The app's onResume() detects the updated capability via canScheduleExactAlarms(), auto-schedules the alarm, and updates the UI status to "Reminder Active". For an end-to-end framework perspective, explore our autonomous mobile app testing Claude Code guide.
Workflow 2: Testing Alarms in Deep Doze Mode (deviceidle force-idle)
The most critical test for any exact alarm implementation is confirming that it fires while the physical device is in deep Doze mode, where CPU execution is frozen and network access is suspended.
Developer Prompt:
"Claude, schedule an exact alarm set to fire in 60 seconds. Then immediately force the phone into deep Doze mode using 'dumpsys deviceidle force-idle'. Monitor logcat for our receiver tag. Verify that the CPU wakes, the broadcast intent fires at the 60-second mark, and the alert notification renders on screen."
Step 1: Schedule 60-Second Exact Alarm
Claude Code launches the app and triggers an exact alarm scheduled for System.currentTimeMillis() + 60000.
Step 2: Verify Registration in System Table
Claude Code runs:
adb shell dumpsys alarm | grep "com.screensync.alarms.ACTION_EXACT_TRIGGER"
The output confirms exact=true and window=0 with FLAG_ALLOW_WHILE_IDLE.
Step 3: Force Device into Deep Doze Mode
Claude Code executes the Doze command sequence:
# Unplug virtual battery charging state
adb shell dumpsys battery unplug
# Step device into deep idle state
adb shell dumpsys deviceidle step deep
adb shell dumpsys deviceidle force-idle
Claude Code confirms Doze state via:
adb shell dumpsys deviceidle get
Output: IDLE.
Step 4: Await Execution and Triage Wakeup via Logcat
Claude Code calls get_logcat with filter ExactAlarmReceiver:
I ExactAlarmReceiver: Exact alarm fired successfully! Payload: Morning Medication Reminder
I PowerManagerService: Waking up from dozing (uid=10214)...
Claude Code then captures get_latest_screenshot to verify that the application successfully posted a heads-up notification alerting the user, proving that the exact alarm broke through deep Doze sleep. To explore how physical devices handle testing across real hardware environments, read can Claude Code test Android apps on real mobile devices.
| Exact Alarm QA Scenario | ScreenSync MCP Tools Used | Primary Assertion Mechanism | Critical Defect Caught |
|---|---|---|---|
| Android 14 Default-Deny State | get_ui_hierarchy, get_logcat |
Node btn_open_settings in dialog |
Application throws unhandled SecurityException on launch |
| Deep Doze Wakeup | get_logcat, get_latest_screenshot |
Logcat Exact alarm fired + HUD frame |
Alarm deferred until device unlocked because developer used setExact() instead of setExactAndAllowWhileIdle() |
| System Wall-Clock Reversal | get_ui_hierarchy, dumpsys alarm |
Timer countdown node integrity | Alarm fires instantly or stalls indefinitely because app used RTC instead of ELAPSED_REALTIME for relative intervals |
| Process Death Cold Relaunch | control_launch_app, get_logcat |
Process PID rebirth in logcat | BroadcastReceiver registered dynamically in Activity rather than statically in AndroidManifest.xml |
| App Standby Bucket Restrictions | get_logcat, dumpsys battery |
Delivery timestamp in logcat | Alarms throttled to 1-per-hour window because app assigned to Restricted standby bucket |
| Exact Alarm Clock Intent | get_latest_screenshot, get_ui_hierarchy |
Lock screen alarm pill visualization | System fails to display upcoming alarm icon in status bar |
Common Pitfalls: SecurityExceptions, RTC vs ELAPSED, and Standby Buckets
Common exact alarm pitfalls include throwing unhandled SecurityExceptions on Android 12+, selecting the wrong clock base between RTC and ELAPSED_REALTIME, and failing to account for App Standby bucket throttling. Claude Code identifies these architectural errors by inspecting system dumpsys logs and analyzing codebase call sites.
1. The Fatal SecurityException: Caller not allowed to schedule exact alarms
The most common crash in modern Android applications occurs when code calls alarmManager.setExact() or alarmManager.setExactAndAllowWhileIdle() on Android 12+ without wrapping the call in a permission check or handling SecurityException:
// DEFECTIVE: Crashes immediately on Android 14 if permission is denied
fun setReminder(timeMs: Long, pendingIntent: PendingIntent) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent)
}
// RESILIENT: Checks capability, catches SecurityException, and provides graceful fallback
fun setReminder(timeMs: Long, pendingIntent: PendingIntent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
showExactAlarmPermissionRationale()
// Fall back to windowed inexact alarm
alarmManager.setWindow(AlarmManager.RTC_WAKEUP, timeMs, 10 * 60 * 1000L, pendingIntent)
return
}
try {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent)
} catch (e: SecurityException) {
Log.e("AlarmError", "Failed to schedule exact alarm", e)
alarmManager.setWindow(AlarmManager.RTC_WAKEUP, timeMs, 10 * 60 * 1000L, pendingIntent)
}
}
Claude Code catches this defect by monitoring get_logcat during automated test runs, highlighting the unhandled SecurityException, and generating the defensive check directly in your IDE.
2. Confusing RTC_WAKEUP with ELAPSED_REALTIME_WAKEUP
Developers often confuse the two primary clock types:
RTC_WAKEUP(Real-Time Clock): Based on wall-clock time (System.currentTimeMillis()). If the user manually changes the time zone, adjusts the clock, or if network time synchronization updates the system clock, RTC alarms can trigger immediately or be delayed indefinitely. RTC should only be used for alarms tied to specific calendar dates and times (e.g. "Alert at 8:00 AM on Monday").ELAPSED_REALTIME_WAKEUP: Based on the time elapsed since device boot (SystemClock.elapsedRealtime()), including deep sleep. It is entirely immune to user time adjustments, time zones, or daylight saving shifts. Relative intervals (e.g. "Alert in 45 minutes") must always useELAPSED_REALTIME_WAKEUP.
Claude Code audits alarm declarations by inspecting whether relative offsets are incorrectly paired with System.currentTimeMillis(), refactoring them to use SystemClock.elapsedRealtime().
3. Registering Broadcast Receivers Dynamically Instead of in Manifest
If an application registers its alarm BroadcastReceiver dynamically inside an Activity via registerReceiver(), the receiver only exists while the Activity is active in memory. If the user backgrounds the application and Android kills the process to reclaim RAM, the alarm fires, but no receiver exists to catch it—resulting in a silent failure. Claude Code verifies that alarm receivers are declared statically in AndroidManifest.xml with android:exported="false", guaranteeing that the system can launch the process when the alarm triggers.
Implementation Checklist for Automated Exact Alarm QA
- [ ] Ensure host development workstation runs Node.js 18+ with Android Platform Tools
adbconfigured in systemPATH. - [ ] Unpack the ScreenSync MCP desktop hub and execute
start-hub.bat(Windows) orstart-hub.sh(macOS/Linux). - [ ] Register ScreenSync MCP with the Claude Code CLI via
claude mcp add screensync node "/path/to/screensync-hub/screensync-hub.js". - [ ] Install the ScreenSync MCP companion application (
com.screensync.mcp) on an authentic physical Android 7.0+ smartphone. - [ ] Pair the smartphone with the desktop hub via mDNS auto-discovery or console QR code, and authorize MediaProjection screen capture.
- [ ] Connect the smartphone via USB or wireless debugging and verify connectivity with
adb devices. - [ ] Configure USB reverse port forwarding with
adb reverse tcp:3000 tcp:3000to ensure resilient frame streaming. - [ ] Implement
canScheduleExactAlarms()checks and defensive fallbacks in your Android codebase before invokingsetExactAndAllowWhileIdle(). - [ ] Execute automated permission state sweeps using
adb shell cmd appops set <package> SCHEDULE_EXACT_ALARM allow|deny. - [ ] Verify exact alarm registration parameters (
window=0 exact=true) viaadb shell dumpsys alarm. - [ ] Validate Doze mode wakeups by executing
adb shell dumpsys deviceidle force-idleand monitoringget_logcatfor receiver execution. - [ ] Validate lock screen and HUD visual alerts using
get_latest_screenshotandget_ui_hierarchythrough Claude Code.
Questions, answered
What is the difference between setExact() and setExactAndAllowWhileIdle() in Android?
While both APIs guarantee delivery at the specified millisecond, setExact() is subject to system Doze mode and App Standby restrictions, deferring execution until the device exits deep sleep. In contrast, setExactAndAllowWhileIdle() is explicitly permitted to wake the device CPU and deliver broadcast intents during Doze maintenance windows.
Why does my Android app crash with SecurityException when calling setExact() on Android 14?
Starting in Android 14 (API 34), the SCHEDULE_EXACT_ALARM permission is denied by default for newly installed applications. Calling setExact() without checking alarmManager.canScheduleExactAlarms() throws a fatal SecurityException. Applications must check this method and direct users to Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM when permission is absent.
How can I simulate deep Doze mode via ADB when testing exact alarms with Claude Code?
To test exact alarm wakeups in deep Doze, first unplug the virtual battery state with adb shell dumpsys battery unplug. Then force the device into deep sleep using adb shell dumpsys deviceidle force-idle. Monitor execution via adb shell dumpsys alarm and get_logcat to verify alarms fire on schedule.
When should an Android application use USE_EXACT_ALARM instead of SCHEDULE_EXACT_ALARM?
The USE_EXACT_ALARM permission is restricted exclusively to dedicated clock, timer, and calendar applications under Google Play policy. It is granted automatically upon installation and cannot be revoked by users. General applications must use SCHEDULE_EXACT_ALARM, which requires user consent and can be toggled in system settings.
How do I check if an exact alarm is currently scheduled in the Android OS queue via ADB?
You can inspect scheduled alarms by running adb shell dumpsys alarm and filtering for your package name. Inspect the output for exact=true, window=0, and flags containing FLAG_ALLOW_WHILE_IDLE. This confirms that the system accepted the request as an exact alarm rather than batching it into inexact windows.
Why should relative alarms use ELAPSED_REALTIME instead of RTC clock types?
RTC_WAKEUP is based on wall-clock time, which can shift unexpectedly if the user changes time zones or if network time synchronization adjusts system time. ELAPSED_REALTIME_WAKEUP measures elapsed time since device boot, making it completely immune to clock adjustments and ideal for relative timers.
Why does Espresso fail to test exact alarms that wake backgrounded or killed applications?
Espresso runs inside the application process sandbox via an instrumentation runner. If the application process is killed to test a cold alarm wakeup, the test runner is terminated immediately. ScreenSync MCP operates from the host workstation, allowing Claude Code to monitor device wakeups independently of application process lifecycles.
Can ScreenSync MCP capture physical Android screens during exact alarm tests without root?
Yes. ScreenSync MCP captures display frames using Android's native MediaProjection API on Android 7.0 or higher. Display capture requires zero root access and consumes zero ADB bandwidth, maintaining a median latency of approximately 94 milliseconds over local Wi-Fi while input commands route deterministically through ADB.




