On this page
Testing Android Health Connect integrations on physical mobile hardware introduces one of the most intricate verification challenges in modern Android engineering. Starting with Android 14 (API level 34), Health Connect transitioned from a standalone Play Store utility into a core Android operating system framework module (android.health.connect), and Android 15 and Android 16 expanded it further with background read gates (READ_HEALTH_DATA_IN_BACKGROUND), extended historical access (READ_HEALTH_DATA_HISTORY), and Personal Health Record (PHR) medical data permissions. While unit testing libraries such as androidx.health.connect:connect-testing help verify repository logic with FakeHealthConnectClient, they bypass the real system Permission Controller (com.google.android.healthconnect.controller), cross-app DataOrigin attribution, rate-limiting quotas, and OEM-specific background restrictions. By pairing Anthropic's terminal coding agent Claude Code with the Model Context Protocol (MCP) through ScreenSync MCP, developers can automate end-to-end Health Connect workflows on unrooted physical Android smartphones—combining low-latency visual capture, live UI accessibility inspection, ADB system diagnostics, and companion web dashboard verification in a single loop.
Key Takeaways
- Cross-process Health Connect UI automation: ScreenSync MCP exposes
get_ui_hierarchyandcontrol_tapso Claude Code can inspect and navigate the externalcom.google.android.healthconnect.controllerpermission sheets that sandboxed Espresso tests cannot touch. - Decoupled capture and ADB control: Screen capture runs through Android's native
MediaProjectionAPI (Android 7.0 or later, requiring user consent per session, zero root, and zero ADB), achieving roughly 94 ms median latency over a local network, while control tools (control_tap,control_swipe,control_type) execute through ADB over USB or wireless debugging. - Background read and WorkManager verification: Claude Code validates
READ_HEALTH_DATA_IN_BACKGROUNDenforcement, forces App Standby Bucket transitions, and monitorsHealthConnectServiceandSecurityExceptionstack traces in real time usingget_logcat. - Multi-app DataOrigin and rate-limit triage: Real-device runs verify how your app merges or deduplicates records written by external fitness trackers and catch Health Connect background read quota errors before production release.
- 226-tool mobile and browser coverage: ScreenSync MCP pairs 29 phone and desktop tools (12
control_*, 3os_*, and 14 capture/hub tools) with 197web_*browser tools via its Chrome/Edge extension to verify that mobile Health Connect syncs reach web wellness portals accurately. - Local-first developer privacy: Display frames stream from your phone to the desktop hub on your local network without routing through EpsolDev servers (Drive fallback is optional), while any screenshots an AI agent requests are transmitted only to that agent's model provider.
Why Traditional Android Test Suites Break on Health Connect
Traditional Android test suites break on Health Connect because HealthConnectClient permissions execute inside an out-of-process system controller (com.google.android.healthconnect.controller) rather than your application's instrumentation sandbox. In-process Espresso matchers cannot cross process boundaries to toggle granular health data switches, while fake test doubles hide real OS rate limits, background read restrictions, and multi-app attribution conflicts.
To understand why Health Connect regressions regularly slip past continuous integration pipelines, examine the three architectural boundaries enforced by the Android Health Connect framework:
- Out-of-Process System Permission Controller: Unlike standard runtime permissions managed by
com.google.android.permissioncontroller, Health Connect renders a specialized, multi-screen privacy dashboard and granular per-record-type toggle sheet. When your app launchesPermissionController.createRequestPermissionResultContract(), the Android Window Manager transfers focus to the Health Connect system module. StandardAndroidJUnitRunnerand Espresso matchers search strictly inside your app's ownViewor Compose tree and fail immediately withNoMatchingViewException. - Granular Read/Write Matrix and Rationale Mandates: Users can grant
READ_STEPSwhile denyingREAD_HEART_RATE, revokeREAD_SLEEPweeks later from Android Settings, or denyREAD_HEALTH_DATA_IN_BACKGROUNDentirely. Furthermore, your manifest must declare a privacy rationale activity handlingandroidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE(andandroid.intent.action.VIEW_PERMISSION_USAGEwithHEALTH_PERMISSIONScategory on Android 14+). If that rationale intent resolves poorly or crashes, Health Connect blocks your permission sheet silently. - Why
connect-testingFakes Are Necessary but Insufficient: Jetpack'sandroidx.health.connect:connect-testingartifact (FakeHealthConnectClientandFakePermissionController) is valuable for fast JVM/unit verification of ViewModels and use cases. However, fakes do not enforce Android 14+ background read restrictions (SecurityExceptionwhen querying without foreground focus orREAD_HEALTH_DATA_IN_BACKGROUND), do not trigger realHealthConnectExceptionrate-limit throttling, and cannot replicate OEM background killers or cross-appDataOriginfiltering bugs.
| Verification Dimension | JVM Tests (connect-testing Fakes) |
Espresso + UIAutomator Scripts | Headless CI Emulators | ScreenSync MCP + Claude Code (Real Device) |
|---|---|---|---|---|
| System Permission Sheet | Completely stubbed via FakePermissionController |
Fragile regex selectors break on Android 14 vs 15/16 UI changes | Often missing Play Services or outdated Health Connect module | Live accessibility node traversal via get_ui_hierarchy and control_tap |
| Background Read Enforcement | Must be manually simulated in fake state | Cannot survive process backgrounding cleanly | Generic AOSP scheduling without OEM battery policies | Real WorkManager + READ_HEALTH_DATA_IN_BACKGROUND validation via get_logcat |
Multi-App DataOrigin Reads |
Synthetic in-memory records only | Requires pre-installed helper APKs with hardcoded UI steps | Limited sensor and companion app ecosystem | Tests real records written by Health Connect Toolbox or companion apps |
| Privacy Rationale Intent | Unit tests cannot verify system Settings launch | Brittle cross-package backstack assertions | Slow cold-boot inspection cycles | Verifies ACTION_SHOW_PERMISSIONS_RATIONALE and backstack navigation live |
| Visual Frame Verification | Zero visual rendering assertions | High-latency screencap over ADB |
Virtual framebuffer with no physical display quirks | Native MediaProjection stream (~94 ms median LAN latency) via get_latest_screenshot |
| Cross-Surface Web Sync | Unsupported | Android only; cannot inspect web portals | Android only | Unified 226 tools: 29 mobile/desktop + 197 web_* Chrome/Edge extension tools |
Android Health Connect Architecture: Permissions, SDK Contracts, and Android 16 PHR
Android Health Connect centralizes on-device fitness, wellness, and medical data behind scoped android.permission.health.* permissions, HealthConnectClient IPC calls, and strict background read rules. Modern implementations must validate SDK availability across Android versions, handle partial permission grants gracefully, and enforce separate checks for historical data, background sync, and Personal Health Records (PHR).
Before automating QA flows with Claude Code, your Android application must declare the exact manifest entries, permission contracts, and feature availability checks required across Android 7.0 through Android 16 (API level 36). Notice how Health Connect separates fitness record permissions from newer background, history, and medical record gates:
| Health Connect Capability | Manifest Permission / API Constant | Minimum OS / SDK Requirement | Behavioral Constraint Caught on Real Hardware |
|---|---|---|---|
| Basic Fitness Read/Write | android.permission.health.READ_STEPS, WRITE_EXERCISE, READ_HEART_RATE |
Health Connect APK (Android 9–13) or OS Module (Android 14+) | Partial grants allow READ_STEPS while throwing SecurityException on ungranted types |
| Background Data Reads | android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND |
Health Connect SDK 1.1.0+ / Android 15+ enforcement | Background WorkManager calls fail unless granted or executed inside an active foreground state |
| Extended History (>30 Days) | android.permission.health.READ_HEALTH_DATA_HISTORY |
Android 14+ / SDK 1.1.0+ | Queries older than 30 days return empty or throw unless history permission is explicitly granted |
| Personal Health Records (PHR) | READ_MEDICAL_DATA_VACCINES, READ_MEDICAL_DATA_PROCEDURES |
Android 16 (API 36) + connect-client:1.1.0-beta02+ |
Requires HealthConnectFeatures.getFeatureStatus(..., FEATURE_CONSTANT_NAME_PHR) check |
| Privacy Rationale Entry | androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE |
All Health Connect versions | Tapping "Privacy policy" inside system Health Connect fails if activity export/intent filter is misconfigured |
Production Kotlin Setup for HealthConnectClient and Granular Permissions
In production Kotlin code, never assume that an initial grant covers all requested permissions or remains valid across sessions. Below is a defensive HealthConnectRepository pattern that verifies platform availability, checks PHR feature support safely, queries granted permissions before reading records, and handles partial access cleanly:
package com.example.screensync.health
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.health.connect.client.HealthConnectClient
import androidx.health.connect.client.HealthConnectFeatures
import androidx.health.connect.client.permission.HealthPermission
import androidx.health.connect.client.records.HeartRateRecord
import androidx.health.connect.client.records.StepsRecord
import androidx.health.connect.client.request.AggregateRequest
import androidx.health.connect.client.request.ReadRecordsRequest
import androidx.health.connect.client.time.TimeRangeFilter
import java.time.Instant
import java.time.temporal.ChronoUnit
class HealthConnectRepository(private val context: Context) {
companion object {
const val TAG = "ScreenSyncHealthQA"
const val PROVIDER_PACKAGE = "com.google.android.apps.healthdata"
val CORE_PERMISSIONS = setOf(
HealthPermission.getReadPermission(StepsRecord::class),
HealthPermission.getWritePermission(StepsRecord::class),
HealthPermission.getReadPermission(HeartRateRecord::class),
HealthPermission.PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND,
HealthPermission.PERMISSION_READ_HEALTH_DATA_HISTORY
)
}
fun getAvailabilityStatus(): Int {
return HealthConnectClient.getSdkStatus(context, PROVIDER_PACKAGE)
}
fun isMedicalRecordsSupported(): Boolean {
if (getAvailabilityStatus() != HealthConnectClient.SDK_AVAILABLE) return false
return HealthConnectFeatures.getFeatureStatus(
context,
HealthConnectFeatures.FEATURE_CONSTANT_NAME_PHR
) == HealthConnectFeatures.FEATURE_STATUS_AVAILABLE
}
suspend fun getGrantedPermissions(client: HealthConnectClient): Set<String> {
return client.permissionController.getGrantedPermissions()
}
suspend fun readDailySteps(client: HealthConnectClient, hoursBack: Long = 24): Long {
val granted = getGrantedPermissions(client)
val stepsPerm = HealthPermission.getReadPermission(StepsRecord::class)
if (stepsPerm !in granted) {
Log.w(TAG, "READ_STEPS permission not granted; skipping aggregate query")
return 0L
}
val end = Instant.now()
val start = end.minus(hoursBack, ChronoUnit.HOURS)
return try {
val response = client.aggregate(
AggregateRequest(
metrics = setOf(StepsRecord.COUNT_TOTAL),
timeRangeFilter = TimeRangeFilter.between(start, end)
)
)
val total = response[StepsRecord.COUNT_TOTAL] ?: 0L
Log.i(TAG, "Aggregated steps in last ${hoursBack}h: $total")
total
} catch (se: SecurityException) {
Log.e(TAG, "SecurityException reading steps (background or revoked): ${se.message}", se)
throw se
}
}
suspend fun readHeartRateSamples(client: HealthConnectClient, start: Instant, end: Instant): List<HeartRateRecord> {
val granted = getGrantedPermissions(client)
val hrPerm = HealthPermission.getReadPermission(HeartRateRecord::class)
if (hrPerm !in granted) {
Log.w(TAG, "READ_HEART_RATE denied; degrading gracefully without crash")
return emptyList()
}
val request = ReadRecordsRequest(
recordType = HeartRateRecord::class,
timeRangeFilter = TimeRangeFilter.between(start, end)
)
val result = client.readRecords(request)
Log.i(TAG, "Fetched ${result.records.size} HeartRateRecord entries")
return result.records
}
}
And in AndroidManifest.xml, verify both the granular android.permission.health.* permissions and the required rationale activity intent filters (covering both Android 13 and Android 14+ conventions):
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.health.READ_STEPS" />
<uses-permission android:name="android.permission.health.WRITE_STEPS" />
<uses-permission android:name="android.permission.health.READ_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />
<!-- Android 16 (API 36) PHR Medical Record example -->
<uses-permission android:name="android.permission.health.READ_MEDICAL_DATA_VACCINES" />
<queries>
<package android:name="com.google.android.apps.healthdata" />
</queries>
<application>
<activity
android:name=".PermissionsRationaleActivity"
android:exported="true">
<intent-filter>
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
<category android:name="android.intent.category.HEALTH_PERMISSIONS" />
</intent-filter>
</activity>
</application>
</manifest>
For apps that also read raw accelerometer, gyroscope, or heart-rate hardware sensors directly alongside Health Connect, review our companion guide on testing Android hardware sensors with Claude Code and MCP.
How ScreenSync MCP Drives Real-Device Health Connect QA
ScreenSync MCP enables Claude Code to test Health Connect on unrooted Android hardware by separating local display capture from ADB device control and exposing 226 MCP tools across mobile, desktop, and browser surfaces. MediaProjection streams live frames at roughly 94 ms median LAN latency with zero root, while get_ui_hierarchy, control_tap, and get_logcat automate system Health Connect sheets and background telemetry.
Unlike monolithic testing wrappers that force every interaction through slow ADB screencap calls, ScreenSync MCP splits responsibilities across clean, deterministic planes:
| ScreenSync MCP Plane | Underlying Mechanism | Root / ADB Requirement | Role in Health Connect QA |
|---|---|---|---|
| Visual Capture Plane | Android native MediaProjection API (Android 7.0+, user consent per session) |
No root, no ADB | Delivers ~94 ms median LAN frames via get_latest_screenshot and video via record_screen to verify toggle states and rationale screens |
| Structural Accessibility Plane | Android Accessibility / Window hierarchy extraction | Runs through desktop hub / ADB bridge | Inspects com.google.android.healthconnect.controller toggle switches, "Allow all" controls, and snackbar states via get_ui_hierarchy |
| Input & Control Plane | ADB over USB or wireless debugging | ADB required, no root | Executes taps (control_tap), scrolling (control_swipe), and text input (control_type) across app and OS dialogs |
| Telemetry & Diagnostic Plane | logd ring buffer + dumpsys healthconnect |
ADB required, no root | Captures SecurityException, rate-limit quota hits, and ScreenSyncHealthQA logs via get_logcat |
| Browser Verification Plane | Chrome/Edge MV3 extension (web_* tools) |
Local hub port 3000 + human approval gate | Audits synced mobile step counts or workout logs inside web wellness dashboards using 197 web_* tools |
To see why pairing structural node trees with visual frames prevents tap-coordinate mistakes on dynamic OEM screens, read our architectural breakdown of Android UI hierarchy vs computer vision. You can also explore the dedicated Screen MCP architecture overview or compare server architectures on our Android MCP servers comparison page.
Privacy and Local Network Boundaries for Sensitive Health Data
Testing Health Connect means handling personal fitness metrics, sleep windows, and potentially medical record fixtures. ScreenSync MCP keeps raw video frames on your own network: frames stream from the Android phone directly to the local Node.js hub on your workstation, never to EpsolDev servers (Google Drive fallback is optional and disabled by default). Pairing uses mDNS auto-discovery on the LAN or the hub's QR code, and HTTP requests require the SCREEN_SYNC_TOKEN bearer token. Keep one important distinction in mind for compliance audits: whenever your AI agent calls get_latest_screenshot to inspect a screen visually, that screenshot payload is sent to that agent's model provider (for example, Anthropic when using Claude Code). Use synthetic test accounts and synthetic Health Connect Toolbox records rather than real patient data during automated runs.
Step-by-Step Setup: Desktop Hub, Physical Phone, and Claude Code
Setting up ScreenSync MCP for Health Connect testing requires Node.js 18 or later on Windows, macOS, or Linux, the free ScreenSync MCP Android app (com.screensync.mcp) on an Android 7.0+ device, and local stdio registration in Claude Code or Claude Desktop. Once paired over LAN or USB debugging, Claude Code gains immediate access to all 226 MCP tools.
Follow these four steps to prepare a physical Android device for autonomous Health Connect QA. For full parameter details, consult the official ScreenSync MCP setup guide.
Step 1: Launch the ScreenSync MCP Desktop Hub
Download the free ScreenSync MCP desktop hub archive (v1.14.4) onto your workstation (Windows, macOS, or Linux with Node.js 18+ and adb in your PATH), extract it, and run the startup script:
# Windows (PowerShell or Command Prompt)
cd C:\path\to\hub
.\start-hub.bat
# macOS / Linux
cd /path/to/hub
chmod +x start-hub.sh
./start-hub.sh
The hub starts an HTTP listener on port 3000 for local MediaProjection frame ingestion, prints your SCREEN_SYNC_TOKEN bearer token, displays a pairing QR code, and exposes the MCP server over stdio.
Step 2: Register ScreenSync MCP in Claude Code or Claude Desktop
Register the local stdio server directly in Claude Code:
claude mcp add screensync node "/path/to/hub/screensync-hub.js"
If you use Claude Desktop, add the screensync block to claude_desktop_config.json (Settings > Developer) with your token from Step 1:
{
"mcpServers": {
"screensync": {
"command": "node",
"args": ["/path/to/hub/screensync-hub.js"],
"env": {
"SCREEN_SYNC_TOKEN": "your_screen_sync_token_here"
}
}
}
}
ScreenSync MCP works with local stdio MCP clients including Claude Code, Claude Desktop, Cursor, and VS Code agent mode. (ChatGPT's web app requires remote HTTPS MCP and is not supported.)
Step 3: Install the Android App and Authorize Capture and ADB
- Install the free ScreenSync MCP app (v2.5.7,
com.screensync.mcp) on your Android 7.0+ test phone from Google Play. - Open the app, pair with the hub via mDNS LAN discovery or by scanning the hub QR code, and grant Android's
MediaProjectionscreen-capture consent for the session. Capture requires no root and no ADB. - Enable Developer Options and turn on USB debugging or wireless debugging so the hub's ADB control tools (
control_tap,control_swipe,control_type) can interact with Health Connect dialogs. For cable-free setups, follow our guide on pairing Android wireless debugging to MCP without USB. - Verify your device is visible:
adb devices
Step 4: Verify Health Connect Service and Toolbox Availability
Before triggering Claude Code, inspect the Health Connect subsystem state on the physical phone via ADB:
adb shell dumpsys healthconnect | head -n 40
If you want to inject synthetic workouts, sleep sessions, or heart-rate records without waiting for real wearable sensors, install Google's Health Connect Toolbox APK on the test device alongside your app under test. That gives Claude Code a real second DataOrigin writer to test cross-app synchronization.
Automated Health Connect QA Workflows with Claude Code
Automating Health Connect QA with Claude Code covers four high-risk production failure modes: partial granular permission grants, privacy rationale routing, READ_HEALTH_DATA_IN_BACKGROUND enforcement during WorkManager syncs, and multi-app DataOrigin aggregation. Claude Code drives each flow on real hardware by chaining get_ui_hierarchy, control_tap, control_swipe, get_latest_screenshot, get_logcat, and ADB shell diagnostics.
Workflow 1: Partial Permission Grants and Graceful Degradation
Most Health Connect crashes occur when developers test only the "Allow all" button. Real users frequently grant step counts while leaving heart rate or sleep permissions toggled off.
Developer Prompt to Claude Code:
"Reset Health Connect permissions for com.example.screensync.health via ADB, launch the app, tap 'Connect Health Data', inspect the Health Connect permission controller with get_ui_hierarchy, toggle ONLY 'Steps' on while leaving 'Heart rate' off, tap 'Allow', and verify via get_ui_hierarchy and get_logcat that the dashboard renders steps without crashing on missing heart-rate permissions."
Step 1: Reset Permissions via ADB
Claude Code clears any prior permission state so the test starts deterministically:
adb shell pm revoke com.example.screensync.health android.permission.health.READ_STEPS
adb shell pm revoke com.example.screensync.health android.permission.health.READ_HEART_RATE
adb shell pm revoke com.example.screensync.health android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND
Step 2: Inspect the Out-of-Process Health Connect Sheet
After launching the app via adb shell am start -n com.example.screensync.health/.MainActivity and tapping the connect CTA with control_tap, Claude Code invokes get_ui_hierarchy. Instead of crashing like Espresso, ScreenSync MCP returns the system Health Connect window nodes:
<node package="com.google.android.healthconnect.controller" class="android.widget.ScrollView">
<node text="Allow HealthQA to access Health Connect?" class="android.widget.TextView" />
<node text="Allow all" class="android.widget.Switch" checked="false" clickable="true" />
<node text="Steps" class="android.widget.Switch" checked="false" clickable="true" />
<node text="Heart rate" class="android.widget.Switch" checked="false" clickable="true" />
<node text="Allow" class="android.widget.Button" clickable="true" />
<node text="Don't allow" class="android.widget.Button" clickable="true" />
</node>
If the list of permissions extends below the fold (common when requesting 8+ data types or Android 16 PHR medical categories), Claude Code calls control_swipe to scroll the ScrollView and locates the remaining toggles.
Step 3: Toggle Partial Access and Verify App Telemetry
Claude Code calls control_tap on the Steps switch, skips Heart rate, and taps Allow. Back inside the app, Claude Code calls get_latest_screenshot to confirm the UI renders a "Heart Rate Permission Optional — Enable Later" banner instead of a blank card, and runs get_logcat filtered on ScreenSyncHealthQA to confirm READ_HEART_RATE denied; degrading gracefully without crash. For a deeper breakdown of permission denial loops and settings redirects across Android versions, see our guide on testing Android runtime permissions with Claude Code and MCP.
Workflow 2: Validating READ_HEALTH_DATA_IN_BACKGROUND and WorkManager Sync
Without android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND, Android restricts background Health Connect reads once the app leaves the foreground. Even when declared in the manifest, background sync workers must still handle the case where a user denies background access while allowing foreground access.
Developer Prompt to Claude Code:
"Grant READ_STEPS but revoke READ_HEALTH_DATA_IN_BACKGROUND for com.example.screensync.health. Background the app to the home screen, force the HealthSyncWorker via ADB JobScheduler/WorkManager diagnostics, and check get_logcat for SecurityException handling and retry scheduling."
Execution Sequence
- Configure Split Permission State:
adb shell pm grant com.example.screensync.health android.permission.health.READ_STEPS adb shell pm revoke com.example.screensync.health android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND - Send App to Background: Claude Code presses Home via
adb shell input keyevent 3and waits briefly so the app exits the foreground importance state (top-activity->cached/service). - Trigger Background Worker and Inspect Logs: Claude Code forces the pending
WorkManagerjob or steps Doze maintenance, then callsget_logcatfor tagsScreenSyncHealthQA,HealthConnectService, andWM-WorkerWrapper:
W HealthConnectService: Calling app com.example.screensync.health is not in foreground and lacks READ_HEALTH_DATA_IN_BACKGROUND
E ScreenSyncHealthQA: SecurityException reading steps (background or revoked): Reading health data in background requires android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND
I WM-WorkerWrapper: Worker result FAILURE (or handled non-retryable permission state) for WorkSpec {health-sync-01}
- Verify User Recovery Banner on Foreground Return: Claude Code brings the app back to the foreground (
adb shell am start ...) and callsget_ui_hierarchyandget_latest_screenshotto verify that the UI prompts the user with an educational card explaining why background sync needs approval. For complete coverage ofWorkManagerconstraints, Doze stepping, and standby bucket quotas, follow our walkthrough on testing Android WorkManager with Claude Code and MCP, and pair it with testing Android foreground services with Claude Code and MCP if your sync promotes to a foreground notification.
Workflow 3: Cross-App DataOrigin Attribution and Synthetic Record Injection
Real-world users rarely write and read health metrics from a single app. Steps come from a smartwatch companion app, workouts come from a running tracker, and your app aggregates them. Bugs frequently appear when developers call aggregate() without inspecting dataOrigins or double-count overlapping StepsRecord intervals.
- Inject Synthetic Records via Health Connect Toolbox: Claude Code opens Health Connect Toolbox using
control_tapandcontrol_typeto insert a 4,200-stepStepsRecordspanning a 45-minute interval, then switches to your app and inserts an overlapping 1,500-step session. - Verify Aggregation Deduplication: Claude Code taps "Sync Health Connect" in your app and uses
get_ui_hierarchyto assert the displayed step total matches Health Connect's deduplicatedStepsRecord.COUNT_TOTALaggregate rather than a naive sum (5,700). - Inspect
dumpsys healthconnectStorage State: Claude Code runs:
adb shell dumpsys healthconnect | grep -A 20 "AppInfo"
This verifies that DataOrigin package registration and last-read timestamps updated cleanly in the system database. If your app caches synced records locally in SQLite, pair this step with testing Android Room database migrations with Claude Code and MCP to verify schema integrity across upgrades.
Workflow 4: End-to-End Mobile-to-Web Wellness Portal Sync with web_* Tools
Health and fitness platforms commonly sync mobile Health Connect metrics to a web clinician or coach dashboard. Because ScreenSync MCP bundles 197 web_* browser tools alongside its 29 phone and desktop tools, Claude Code can validate the entire pipeline in one session:
- Mobile Side: Claude Code triggers a synthetic workout write in your Android app on the physical phone, captures visual confirmation with
get_latest_screenshot, and confirms the API upload succeeded inget_logcat. - Browser Side: Using the ScreenSync MCP Chrome/Edge MV3 extension, Claude Code inspects your real authenticated web portal tab (requiring human approval before risky actions), refreshes the patient or athlete timeline, and verifies the exact step count and workout duration match the mobile
StepsRecord.
Learn how to install and pair the Manifest V3 browser companion on the ScreenSync MCP browser extension page, or consult the complete Android MCP tool reference for full tool capabilities.
Triage Matrix: Common Health Connect Failures Caught by get_logcat and ADB
Most Health Connect failures emit deterministic exception signatures inside HealthConnectService and Jetpack's HealthConnectClient IPC proxy. Mapping these signatures to ADB inspection commands allows Claude Code to isolate whether a failure stems from missing permissions, rate-limit quotas, or background visibility rules.
| Failure Symptom | Logcat / Exception Signature | Root Cause on Physical Hardware | Claude Code Diagnostic & Fix |
|---|---|---|---|
| Background Read Blocked | SecurityException: Reading health data in background requires READ_HEALTH_DATA_IN_BACKGROUND |
App queried readRecords or aggregate from WorkManager while backgrounded without background permission |
Check getGrantedPermissions() before querying; surface rationale card on next foreground resume |
| Missing Rationale Activity | ActivityNotFoundException or Health Connect sheet immediately closes |
Manifest lacks exported ACTION_SHOW_PERMISSIONS_RATIONALE or Android 14+ VIEW_PERMISSION_USAGE filter |
Verify intent resolution via adb shell cmd package query-activities -a androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE |
| 30-Day History Truncated | readRecords returns empty list for timestamps >30 days ago |
App lacks READ_HEALTH_DATA_HISTORY or user did not grant historical access |
Request HealthPermission.PERMISSION_READ_HEALTH_DATA_HISTORY and assert empty-state copy for 30-day window |
| IPC Rate-Limit Exceeded | HealthConnectException / Rate limit exceeded in HealthConnectService |
Polling loop called readRecords aggressively in foreground or tight WorkManager retry loop |
Switch to getChanges(changesToken) incremental sync instead of full-window readRecords scans |
| Health Connect Unavailable | getSdkStatus() returns SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED |
Device running Android 9–13 lacks Health Connect APK or has an outdated provider | Prompt Play Store update intent and verify fallback UI with get_latest_screenshot |
| PHR Check Crash on API < 36 | UnsupportedOperationException or feature unavailable |
Code called readMedicalResources without checking FEATURE_CONSTANT_NAME_PHR |
Gate PHR calls behind HealthConnectFeatures.getFeatureStatus() check |
Verifying Incremental Sync with getChangesToken and record_screen
When auditing apps for rate-limit compliance, instruct Claude Code to use record_screen during a multi-screen navigation and pull-to-refresh stress test, while filtering get_logcat for HealthConnectClient calls. If the app re-fetches 30 days of StepsRecord entries on every screen recomposition instead of storing a changesToken, Claude Code flags the redundant IPC calls immediately in the trace and refactors the repository to use incremental getChanges().
Production QA Checklist for Android Health Connect
A repeatable Android Health Connect release gate validates manifest intent resolution, partial permission degradation, background read enforcement, incremental getChangesToken sync, and physical-device UI traversal before shipping to Google Play. Running this checklist with Claude Code and ScreenSync MCP ensures consistent verification across Android 7.0 through Android 16 hardware.
- [ ] Workstation & Hub Ready: Node.js 18+ installed,
adbinPATH, and ScreenSync MCP desktop hub (v1.14.4+) running on port 3000 viastart-hub.batorstart-hub.sh. - [ ] MCP Client Registered:
claude mcp add screensync node "/path/to/hub/screensync-hub.js"configured and verified in Claude Code (orclaude_desktop_config.jsonin Claude Desktop). - [ ] Physical Device Paired: Free ScreenSync MCP Android app (
com.screensync.mcp, v2.5.7+) installed on Android 7.0+ hardware,MediaProjectionconsent granted (no root, no ADB needed for capture), and USB or wireless ADB authorized for control tools. - [ ] Privacy Rationale Intent Verified:
ACTION_SHOW_PERMISSIONS_RATIONALEandVIEW_PERMISSION_USAGE(HEALTH_PERMISSIONScategory) open a real privacy screen without crashing when tapped from Android Settings. - [ ] Partial Grant Matrix Tested: App handles granting
READ_STEPSwhile denyingREAD_HEART_RATE,READ_SLEEP, orREAD_HEALTH_DATA_HISTORYwithout crashes or infinite permission loops. - [ ] Background Read Gate Tested: Revoking
READ_HEALTH_DATA_IN_BACKGROUNDduring a backgroundWorkManagersync produces cleanSecurityExceptionhandling and a user-recoverable UI prompt. - [ ] Incremental Sync Verified: Repository persists
getChangesTokenandgetChangesrather than polling full date ranges on every foreground resume. - [ ] PHR Feature Gate Verified: Any Android 16 Personal Health Records code checks
HealthConnectFeatures.getFeatureStatus(..., FEATURE_CONSTANT_NAME_PHR)before calling medical APIs. - [ ] Clean Synthetic Fixtures: All automated runs use Health Connect Toolbox synthetic records rather than real user or patient health data.
Ready to Automate Real-Device Health Connect QA?
Testing Android Health Connect requires crossing OS process boundaries, navigating real system permission sheets, and validating background read quotas on physical hardware. Download the free ScreenSync MCP app from Google Play, explore the ScreenSync MCP homepage to download the Node.js desktop hub, and let Claude Code verify every Health Connect permission state and background sync flow end to end.
Next steps
Questions, answered
Why cannot Espresso test Android Health Connect permission dialogs directly?
Espresso executes strictly inside the target application's instrumentation sandbox and cannot cross process boundaries into com.google.android.healthconnect.controller. When Health Connect opens its system permission sheet, Espresso throws NoMatchingViewException. ScreenSync MCP exposes system accessibility trees via get_ui_hierarchy so Claude Code can inspect and tap toggles directly.
Does ScreenSync MCP require root access to test Health Connect on Android?
No, ScreenSync MCP requires zero root privileges on Android 7.0 or later devices. Visual screen capture uses Android's native MediaProjection API after user consent each session with no root and no ADB. Control tools like control_tap and diagnostic commands run through standard ADB over USB or wireless debugging.
How does ScreenSync MCP separate screen capture from device control?
ScreenSync MCP routes live display frames over your local network using Android's MediaProjection API at roughly 94 ms median latency without consuming ADB bandwidth. Device actions such as control_tap, control_swipe, control_type, and ADB shell diagnostics run separately through the desktop hub over USB or wireless debugging.
How can Claude Code test READ_HEALTH_DATA_IN_BACKGROUND without waiting hours?
Claude Code revokes android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND via ADB while leaving READ_STEPS granted, backgrounds the app, and triggers WorkManager or JobScheduler execution from the terminal. Using get_logcat, Claude Code verifies that HealthConnectService blocks the background read and confirms your app catches the SecurityException cleanly.
Should teams still use androidx.health.connect:connect-testing alongside ScreenSync MCP?
Yes, androidx.health.connect:connect-testing provides FakeHealthConnectClient and FakePermissionController for fast JVM unit tests of ViewModels and data mappers. However, fakes cannot test real OS rate limits, privacy rationale intents, OEM battery restrictions, or system permission sheets, so pairing unit fakes with ScreenSync MCP real-device verification catches production regressions.
How do developers verify Android 16 Personal Health Records safely on older phones?
Before calling any Android 16 medical record APIs, your app should query HealthConnectFeatures.getFeatureStatus with FEATURE_CONSTANT_NAME_PHR. Claude Code can run your build across both Android 16 and older physical Android devices via ScreenSync MCP to verify graceful fallback UIs when PHR is unavailable.
Is health data sent to EpsolDev servers when testing with ScreenSync MCP?
No, ScreenSync MCP streams display frames from your Android device directly to the desktop hub on your local network and never routes frames through EpsolDev servers (Drive fallback is optional). However, any screenshots requested by your AI agent are sent to that agent's model provider, so always test with synthetic fixtures.
Which AI coding clients work with ScreenSync MCP for mobile QA?
ScreenSync MCP supports any Model Context Protocol client capable of running local stdio servers, including Claude Code, Claude Desktop, Cursor, and VS Code agent mode across Windows, macOS, and Linux. ChatGPT's web application requires remote HTTPS MCP endpoints and is not supported.




