On this page
Continuity across personal Android hardware has historically required engineering teams to construct fragile cloud synchronization pipelines, custom Firebase Realtime Database listeners, or proprietary deep-link QR handoffs just to let a user move an active workflow from a smartphone to a tablet. Android 17 (API level 37) replaces these ad-hoc workarounds with the native Handoff API, a system-level cross-device continuity framework built atop Android's Better Together architecture and CompanionDeviceManager. By allowing any foreground Activity to opt into cross-device state transfer through setHandoffEnabled(), serialize lightweight UI context inside HandoffActivityData, and specify a browser fallback with setFallbackUri(), Android 17 lets users resume reading articles, editing drafts, or inspecting media on nearby tablets and foldables with a single system prompt.
For mobile engineering and quality assurance teams, however, the Android 17 Handoff API introduces severe end-to-end testing blind spots that conventional single-device automation frameworks cannot reach. Local unit tests and Robolectric runners cannot verify how Android's system continuity daemon caches background handoff payloads, nor can in-process Espresso or Jetpack Compose UI tests follow an execution flow when it hops across physical device boundaries or opens a Chrome tab via setFallbackUri(). By connecting Anthropic's Claude Code to physical Android hardware and a live desktop browser through the Model Context Protocol (MCP) using ScreenSync MCP, developers establish a unified verification harness. ScreenSync MCP streams real-time device screens over local Wi-Fi using Android's MediaProjection API with zero root and zero ADB overhead, while dispatching ADB-backed control tools and 197 Chrome/Edge browser tools so Claude Code can trigger handoffs, inspect HandoffActivityData intents, validate the 50 KB PersistableBundle ceiling, and verify web fallbacks autonomously.
Key Takeaways
- Native API 37 Continuity Primitives: Android 17 introduces
Activity.setHandoffEnabled(),HandoffActivityParams,onHandoffActivityDataRequested(), andHandoffActivityData.Builderto transfer active task state across user-owned Android phones, tablets, and large-screen devices. - Strict 50 KB Payload & Zero-PII Guardrails:
HandoffActivityDatatransports state via aPersistableBundlecapped strictly under 50 KB and must exclude credentials or personally identifiable information (PII), relying instead on opaque session or document identifiers. - Web Fallback Verification via
setFallbackUri(): WhensetAllowHandoffWithoutPackageInstalled(true)is configured inHandoffActivityParams, Android 17 routes users to a web URL if the native app is absent on the receiving device. - Decoupled Capture vs. ADB Control Architecture: ScreenSync MCP captures real-time Android frames via Android's native
MediaProjectionAPI (Android 7.0+, no root, no ADB, approximately 94 ms median LAN latency) while executing deterministic taps, text input, and intent audits through ADB over USB or wireless debugging. - 226 Unified MCP Tools Across Mobile & Browser: ScreenSync MCP pairs 29 phone and desktop tools (
12 control_*,3 os_*,14capture and inspection tools includingget_latest_screenshot,get_ui_hierarchy,get_logcat, andrecord_screen) with 197web_*Chrome/Edge extension tools over local stdio transport. - Closed-Loop Source Repair in Claude Code: Claude Code runs locally via
claude mcp add screensync node "/path/to/hub/screensync-hub.js", readslogcatexceptions when aPersistableBundleexceeds 50 KB or omits an activity restart handler, patches the Kotlin source, and re-tests the APK immediately.
How the Android 17 Handoff API Works Under the Hood
The Android 17 Handoff API enables an active foreground Activity on one Android device to transfer its current task state to a nearby user-owned Android phone, tablet, or desktop browser. Applications opt in through setHandoffEnabled(), respond to onHandoffActivityDataRequested(), and return a HandoffActivityData payload under 50 KB containing PersistableBundle extras and an optional web fallback URI.
Before automating cross-device continuity tests with Claude Code, engineers must understand the exact lifecycle contract enforced by API level 37. Unlike legacy Android Beam (NFC) or custom Deep Link dispatchers, Android 17's Handoff API integrates directly into the Activity lifecycle and background task snapshotter:
1. Opting In with setHandoffEnabled() and HandoffActivityParams
An Activity signals eligibility for cross-device continuity by calling setHandoffEnabled(true, params)—typically inside onResume() or whenever the user enters a resumable screen such as a document editor, checkout summary, or media reader. Calling setHandoffEnabled(false, null) revokes eligibility immediately when the user navigates to an ephemeral screen like an authentication challenge or payment confirmation dialog.
HandoffActivityParams configures system behavior around the handoff:
- Web Fallback Allowance: Calling
HandoffActivityParams.Builder().setAllowHandoffWithoutPackageInstalled(true).build()tells the OS continuity router that the target device does not need the native APK installed, providedHandoffActivityDataincludes a valid fallback URI. - Foreground Invariant: Android 17 only surfaces a handoff suggestion for the topmost resumed
Activityin the active task stack. Backgrounded fragments or nested child services cannot independently advertise handoff state. - Status Query: Developers can audit runtime state programmatically via
isHandoffEnabled(), which returns a boolean reflecting whether the current activity instance is actively registered with the platform continuity manager.
2. Synchronous Serialization via onHandoffActivityDataRequested()
Whenever the user triggers a handoff—or when the system moves the Activity into the background and proactively caches continuity state—Android 17 invokes onHandoffActivityDataRequested(requestInfo: HandoffActivityDataRequestInfo). There is no default OS implementation; every activity calling setHandoffEnabled(true, ...) must override this callback and return a non-null HandoffActivityData instance.
The HandoffActivityDataRequestInfo parameter exposes isActiveRequest, allowing Kotlin code to distinguish between two distinct triggers:
isActiveRequest == true: The user explicitly tapped the continuity prompt on a receiving device to pull the session right now.isActiveRequest == false: The OS is opportunistically caching the handoff bundle as the activity leaves the foreground so continuity remains available even after the source screen turns off.
3. Packaging HandoffActivityData, PersistableBundle, and setFallbackUri()
Inside onHandoffActivityDataRequested(), developers construct a HandoffActivityData object using HandoffActivityData.Builder(componentName):
- Target
ComponentName: Identifies theActivityclass on the receiving Android device that will handle the incomingIntentextras. This can be the sameActivity(this.componentName) or a dedicated continuation entry point. - Lightweight State (
setExtras(PersistableBundle)): Carries primitive keys, strings, arrays, or nestedPersistableBundlemaps. The serialized bundle must stay strictly under 50 KB; oversized payloads trigger serialization failures or dropped handoff events. - Web Fallback (
setFallbackUri(Uri)): Supplies an HTTPS URL opened in the receiving device's browser whensetAllowHandoffWithoutPackageInstalled(true)is enabled and the native package is absent.
| Handoff API Symbol | Role in Android 17 (API 37) | Key Constraint or Invariant | Common QA Failure Mode |
|---|---|---|---|
Activity.setHandoffEnabled() |
Opts the topmost resumed Activity into continuity |
Requires Activity to be top of task stack |
Left true on sensitive auth/OTP screens |
HandoffActivityParams |
Configures handoff policy (setAllowHandoffWithoutPackageInstalled) |
Must match setFallbackUri() availability |
Enabled package-free handoff with null fallback URI |
onHandoffActivityDataRequested() |
Callback invoked on active transfer or background caching | Mandatory override; must return non-null payload | Blocks main thread doing synchronous disk/DB I/O |
HandoffActivityDataRequestInfo |
Reports isActiveRequest boolean trigger context |
Distinguishes live pull vs. background snapshot | Triggers expensive analytics on background cache |
HandoffActivityData.Builder |
Assembles target ComponentName, extras, and fallback URI |
Uses PersistableBundle, not standard Bundle |
Passing Parcelable objects instead of persistable primitives |
PersistableBundle Extras |
Transports opaque document IDs and scroll indices | Strictly under 50 KB; zero PII or tokens allowed | Exceeding 50 KB with base64 blobs or leaking JWTs |
setFallbackUri(Uri) |
Defines browser URL when native app is missing | Must use valid HTTPS web deep-link route | Missing query params causing generic homepage redirect |
Why Traditional Mobile Testing Frameworks Break on Cross-Device Handoff
Traditional Android testing tools such as Espresso, Jetpack Compose UI Test, and single-device Appium scripts fail on Android 17 Handoff workflows because they operate inside an isolated single-device process sandbox. Traditional frameworks cannot verify system continuity prompts, measure PersistableBundle size regressions under live background transitions, or inspect web fallback tabs across browser boundaries.
When mobile engineering teams attempt to validate cross-device continuity using legacy instrumentation tests, four structural failure modes emerge:
1. In-Process Instrumentation Blindness
Espresso and createComposeRule() run inside the target app's instrumentation process (androidx.test.runner.AndroidJUnitRunner). They can assert that a Compose Text node exists or invoke a Java method on the Activity, but they have zero visibility into system-level continuity prompts, nearby-device discovery overlays, or incoming Intent launches initiated externally by the OS on a receiving tablet or foldable. For related large-screen posture testing strategies, see our guide on testing Android foldables and adaptive layouts with Claude Code.
2. Missing Dual-Surface Verification (setFallbackUri() Web Handoff)
When setAllowHandoffWithoutPackageInstalled(true) triggers setFallbackUri(), the receiving endpoint is no longer an Android Activity—it is a web browser rendering the continuation URL. Standard Android UI Automator tests terminate at the Chrome address bar or fail to correlate mobile state (document_id, scroll_offset) with the resulting web DOM state.
3. Background Cache & Process Death Desynchronization
Because Android 17 calls onHandoffActivityDataRequested() both during live handoff (isActiveRequest == true) and background caching (isActiveRequest == false), bugs frequently surface only when the source app is backgrounded, killed by the Low Memory Killer, and resumed via the incoming handoff Intent. If your receiving Activity relies on warm in-memory singletons rather than reading intent.extras on cold launch, handoff continuity silently drops the user back to the home screen. Review testing Android process death with Claude Code and MCP for complementary state-restoration checks.
4. Serialization Panics and Latency on Remote Device Farms
Uploading debug APKs and testing cross-device continuity over public cloud device farms introduces multi-second video stream lag and forbids LAN-local peer discovery because cloud phones sit behind isolated NAT virtual switches. Testing Android 17 Handoff reliably requires physical hardware or local virtual targets on the same network segment, paired with low-latency visual inspection and direct ADB intent replay.
| Verification Dimension | Manual Two-Device QA | Espresso / Compose UI Test | Cloud Device Farms | ScreenSync MCP + Claude Code |
|---|---|---|---|---|
| System Continuity & Intent Replay | High manual effort per build | Blind to out-of-process system continuity | High video lag; isolated cloud NAT | Deterministic ADB intent simulation + get_ui_hierarchy |
50 KB PersistableBundle Audit |
Invisible unless app crashes | Requires mocked unit harness | Manual log download after run | Live get_logcat monitoring + automated source patch |
Web Fallback (setFallbackUri()) |
Manual copy-paste into desktop browser | Cannot inspect browser DOM | Disconnected from desktop browser | Unified 197 web_* Chrome/Edge extension tools |
| Visual Frame Feedback Latency | Human eyes | Headless / post-run screenshots | 800–1200+ ms cloud relay lag | ~94 ms median LAN stream via MediaProjection |
| Large-Screen Adaptive Verification | Requires physical tablet on desk | Static configuration qualifiers | Slow farm queue per device | Instant ADB display resize + get_latest_screenshot |
| Data & Screen Privacy | Devices stay on desk | Local test runner | Frames & APKs routed via cloud | Local LAN phone-to-hub stream; zero EpsolDev relay |
Production Kotlin & Jetpack Compose Implementation for Android 17 Handoff
A production-ready Android 17 Handoff implementation encapsulates state serialization inside a dedicated continuity helper, binds setHandoffEnabled() to Jetpack Compose screen state via lifecycle observers, validates the PersistableBundle byte size before returning HandoffActivityData, and strips sensitive fields before constructing the web fallback URI.
Below is a complete Kotlin implementation targeting Android 17 (compileSdk = 37, targetSdk = 37) that demonstrates both sending and receiving handoff state cleanly inside a Jetpack Compose ComponentActivity.
package com.example.screensync.handoff
import android.app.HandoffActivityData
import android.app.HandoffActivityDataRequestInfo
import android.app.HandoffActivityParams
import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcel
import android.os.PersistableBundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
data class ReaderHandoffState(
val documentId: String,
val sectionIndex: Int,
val scrollOffsetPx: Int,
val isSensitiveAuthScreen: Boolean = false
)
class HandoffReaderActivity : ComponentActivity() {
companion object {
private const val TAG = "HandoffReaderActivity"
private const val MAX_HANDOFF_BYTES = 48 * 1024 // Stay safely under Android 17's 50 KB cap
const val EXTRA_DOCUMENT_ID = "extra_document_id"
const val EXTRA_SECTION_INDEX = "extra_section_index"
const val EXTRA_SCROLL_OFFSET_PX = "extra_scroll_offset_px"
}
private var currentState by mutableStateOf(
ReaderHandoffState(
documentId = "doc_arch_042",
sectionIndex = 0,
scrollOffsetPx = 0,
isSensitiveAuthScreen = false
)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
applyHandoffIntent(intent)
setContent {
MaterialTheme {
HandoffReaderScreen(
state = currentState,
onUpdateSection = { newSection, newScroll ->
currentState = currentState.copy(
sectionIndex = newSection,
scrollOffsetPx = newScroll
)
syncHandoffRegistration()
},
onToggleSensitiveMode = { sensitive ->
currentState = currentState.copy(isSensitiveAuthScreen = sensitive)
syncHandoffRegistration()
}
)
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
applyHandoffIntent(intent)
}
override fun onResume() {
super.onResume()
syncHandoffRegistration()
}
override fun onPause() {
// Leave handoff enabled only when state is valid so background caching works
if (currentState.isSensitiveAuthScreen && Build.VERSION.SDK_INT >= 37) {
setHandoffEnabled(false, null)
}
super.onPause()
}
private fun syncHandoffRegistration() {
if (Build.VERSION.SDK_INT < 37) return
val shouldEnable = !currentState.isSensitiveAuthScreen
val params = HandoffActivityParams.Builder()
.setAllowHandoffWithoutPackageInstalled(true)
.build()
setHandoffEnabled(shouldEnable, params)
Log.d(TAG, "Handoff enabled=$isHandoffEnabled for doc=${currentState.documentId}")
}
private fun applyHandoffIntent(incoming: Intent?) {
if (incoming == null) return
// Handle incoming Extras from HandoffActivityData or HTTPS fallback deep link
val dataUri = incoming.data
val docId = incoming.getStringExtra(EXTRA_DOCUMENT_ID)
?: dataUri?.getQueryParameter("doc")
?: currentState.documentId
val section = incoming.getIntExtra(
EXTRA_SECTION_INDEX,
dataUri?.getQueryParameter("section")?.toIntOrNull() ?: currentState.sectionIndex
)
val scroll = incoming.getIntExtra(
EXTRA_SCROLL_OFFSET_PX,
dataUri?.getQueryParameter("scroll")?.toIntOrNull() ?: currentState.scrollOffsetPx
)
currentState = currentState.copy(
documentId = docId,
sectionIndex = section,
scrollOffsetPx = scroll
)
Log.i(TAG, "Restored handoff state: doc=$docId section=$section scroll=$scroll")
}
@RequiresApi(37)
override fun onHandoffActivityDataRequested(
requestInfo: HandoffActivityDataRequestInfo
): HandoffActivityData {
val triggerType = if (requestInfo.isActiveRequest) "ACTIVE_TRANSFER" else "BACKGROUND_CACHE"
Log.d(TAG, "onHandoffActivityDataRequested trigger=$triggerType")
val extras = PersistableBundle().apply {
putString(EXTRA_DOCUMENT_ID, currentState.documentId)
putInt(EXTRA_SECTION_INDEX, currentState.sectionIndex)
putInt(EXTRA_SCROLL_OFFSET_PX, currentState.scrollOffsetPx)
}
// Guard against exceeding Android 17's 50 KB PersistableBundle ceiling
val parcel = Parcel.obtain()
val byteSize = try {
extras.writeToParcel(parcel, 0)
parcel.dataSize()
} finally {
parcel.recycle()
}
val safeExtras = if (byteSize <= MAX_HANDOFF_BYTES) {
extras
} else {
Log.w(TAG, "Handoff PersistableBundle ($byteSize bytes) exceeded budget; trimming extras")
PersistableBundle().apply {
putString(EXTRA_DOCUMENT_ID, currentState.documentId)
putInt(EXTRA_SECTION_INDEX, currentState.sectionIndex)
}
}
val fallbackUri = Uri.Builder()
.scheme("https")
.authority("app.example.com")
.path("/reader")
.appendQueryParameter("doc", currentState.documentId)
.appendQueryParameter("section", currentState.sectionIndex.toString())
.appendQueryParameter("scroll", currentState.scrollOffsetPx.toString())
.build()
return HandoffActivityData.Builder(ComponentName(this, HandoffReaderActivity::class.java))
.setExtras(safeExtras)
.setFallbackUri(fallbackUri)
.build()
}
}
@Composable
fun HandoffReaderScreen(
state: ReaderHandoffState,
onUpdateSection: (Int, Int) -> Unit,
onToggleSensitiveMode: (Boolean) -> Unit
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
text = "Document: ${state.documentId}",
style = MaterialTheme.typography.headlineSmall
)
Text(
text = "Section ${state.sectionIndex} • Scroll ${state.scrollOffsetPx}px",
style = MaterialTheme.typography.bodyLarge
)
Button(
onClick = { onUpdateSection(state.sectionIndex + 1, state.scrollOffsetPx + 420) },
modifier = Modifier.fillMaxWidth()
) {
Text("Advance Section & Update Handoff State")
}
OutlinedButton(
onClick = { onToggleSensitiveMode(!state.isSensitiveAuthScreen) },
modifier = Modifier.fillMaxWidth()
) {
Text(
if (state.isSensitiveAuthScreen) "Exit Sensitive Mode (Re-enable Handoff)"
else "Enter Sensitive Mode (Disable Handoff)"
)
}
}
}
Notice three critical engineering details in this implementation:
singleToporonNewIntentHandling: If the receiving tablet already hasHandoffReaderActivityin its back stack, incoming handoff extras may arrive viaonNewIntent()rather thanonCreate(). Always route both entry points throughapplyHandoffIntent().- Parcel Byte-Budget Guard: Measuring
Parcel.dataSize()before returningHandoffActivityDataprevents silent drops when developers accidentally serialize large JSON strings or rich draft arrays intoPersistableBundle. - Dynamic Sensitive-Screen Toggle: Calling
setHandoffEnabled(false, null)insidesyncHandoffRegistration()ensures authentication prompts or PII views never leak continuity state to nearby devices.
Setting Up ScreenSync MCP with Claude Code for Physical Device & Browser QA
ScreenSync MCP connects Claude Code to physical Android hardware and Chrome/Edge tabs over local Model Context Protocol (MCP) stdio transport. Screen capture uses Android's native MediaProjection API with zero root and zero ADB, while control commands route through ADB over USB or wireless debugging alongside 197 browser automation tools.
To test Android 17 Handoff end-to-end—covering both native Activity resumption and setFallbackUri() web handoff—developers wire up ScreenSync MCP's three lightweight components (all free):
- Android Client (
com.screensync.mcp, version 2.5.7): Install the free app from ScreenSync MCP on Google Play on any Android 7.0+ test device. When launched, the app requests user consent once per session to capture the display via Android's nativeMediaProjectionAPI—no root access and no ADB daemon are required for screen streaming. - Desktop Hub (Node.js 18+, version 1.14.4): Unpack the desktop hub on Windows, macOS, or Linux and start it via
start-hub.batorstart-hub.sh. The hub listens on HTTP port3000, exposes MCP over stdio, and discovers paired phones via QR code scan or LAN mDNS auto-discovery authenticated withSCREEN_SYNC_TOKEN. Follow the ScreenSync MCP desktop hub setup guide for initial pairing. - Chrome/Edge MV3 Extension (version 1.14.4): Install the ScreenSync MCP browser extension to expose 197
web_*tools to Claude Code. BecausesetFallbackUri()opens a real browser session when the native package is absent, the extension lets Claude Code verify your web continuation page in a live browser tab while prompting for human approval before risky actions.
Register ScreenSync MCP in Claude Code with a single terminal command:
claude mcp add screensync node "/path/to/hub/screensync-hub.js"
If you use Claude Desktop alongside Claude Code for architectural review, configure claude_desktop_config.json (Settings -> Developer) using the same local hub entrypoint:
{
"mcpServers": {
"screensync": {
"command": "node",
"args": ["/path/to/hub/screensync-hub.js"],
"env": {
"SCREEN_SYNC_TOKEN": "your-local-pairing-token"
}
}
}
}
In total, the desktop hub exposes 226 MCP tools: 29 phone and desktop tools (12 control_*, 3 os_*, and 14 capture and inspection tools such as get_latest_screenshot, get_ui_hierarchy, get_logcat, and record_screen) plus *197 `web_` browser tools, 17 prompts, and 3 resources**. For a deeper breakdown of the decoupled transport model, explore the ScreenSync MCP server architecture overview and compare capabilities across the Android MCP servers guide.
Privacy and Security Boundary: Live screen frames travel directly from your Android phone to the local hub on your LAN (at roughly 94 ms median latency in EpsolDev's tests) and never pass through EpsolDev servers (Drive fallback is strictly optional). Keep in mind that any screenshot an AI agent explicitly requests via get_latest_screenshot is transmitted to that agent's configured model provider for multimodal reasoning—never leave production PII or live credentials on test handsets during automated runs.
Autonomous Android 17 Handoff Testing Workflow with Claude Code
An autonomous Android 17 Handoff test workflow pairs Claude Code's source-code awareness with ScreenSync MCP's real-time visual, structural, and logcat telemetry. Claude Code drives UI state transitions on the phone, verifies setHandoffEnabled() registration in logcat, simulates incoming handoff intents and desktop windowing layouts, and tests web fallback URLs inside Chrome.
You can orchestrate a complete multi-stage Android 17 Handoff verification pipeline from Claude Code using a structured prompt and ADB-assisted test commands:
Stage 1: Verify setHandoffEnabled() Lifecycle & Sensitive Screen Guardrails
Prompt Claude Code to launch your debug build and step through both normal and sensitive UI states:
claude "Use ScreenSync MCP to open com.example.screensync, advance two sections in the reader, capture the UI hierarchy and logcat to verify Handoff enabled=true, then toggle Sensitive Mode and confirm Handoff enabled=false."
Under the hood, Claude Code executes a deterministic loop:
- Inspects the live screen via
get_ui_hierarchyto locate"Advance Section & Update Handoff State"without brittle pixel guessing. See why AI agents need the Android UI hierarchy for node-tree parsing internals. - Dispatches
control_tap(backed by ADB) twice to incrementsectionIndexto2andscrollOffsetPxto840. - Calls
get_logcatfiltered forHandoffReaderActivityto verifyHandoff enabled=true for doc=doc_arch_042. - Taps
"Enter Sensitive Mode (Disable Handoff)"and inspectsget_logcatagain to confirmHandoff enabled=false.
Stage 2: Audit Background Caching & PersistableBundle Byte Budget
Android 17 invokes onHandoffActivityDataRequested() with isActiveRequest=false when the activity moves to the background. Claude Code can trigger this transition via ADB keyevents (KEYCODE_HOME) or control_tap and inspect logcat telemetry:
# Send activity to background to trigger OS background handoff caching
adb shell input keyevent KEYCODE_HOME
# Inspect HandoffReaderActivity logs for ACTIVE_TRANSFER / BACKGROUND_CACHE and bundle warnings
adb logcat -d -s HandoffReaderActivity:D AndroidRuntime:E
If an engineering change accidentally inflates PersistableBundle beyond 50 KB—or triggers a BadParcelableException or NetworkOnMainThreadException inside onHandoffActivityDataRequested()—get_logcat surfaces the exact stack trace to Claude Code. Claude Code immediately locates onHandoffActivityDataRequested in your Kotlin repository, fixes the serialization bug, rebuilds with ./gradlew installDebug, and re-runs the verification cycle.
Stage 3: Simulate Receiving Handoff Intent & Adaptive Tablet Windowing
To validate the receiving side of the handoff on a physical phone, foldable, or tablet, Claude Code replays the exact ComponentName and PersistableBundle extras generated by HandoffActivityData, then verifies layout rendering under large-screen constraints:
# Force-stop app to simulate cold-start handoff arrival on the receiving device
adb shell am force-stop com.example.screensync
# Launch receiving Activity with Handoff extras simulating cross-device resumption
adb shell am start -n com.example.screensync/.handoff.HandoffReaderActivity \
--es extra_document_id "doc_arch_042" \
--ei extra_section_index 2 \
--ei extra_scroll_offset_px 840
Claude Code immediately calls get_ui_hierarchy and get_latest_screenshot (captured via MediaProjection) to confirm the UI renders "Document: doc_arch_042" and "Section 2 • Scroll 840px" cleanly. If testing on a large display or resized window—critical because Android 17 ignores screenOrientation locks on displays >= 600dp—pair this check with testing Android desktop windowing with Claude Code and MCP and testing Android deep links and App Links with Claude Code.
Stage 4: Validate setFallbackUri() in a Real Chrome Tab
When setAllowHandoffWithoutPackageInstalled(true) routes a handoff to a target device without your APK, Android opens the fallbackUri in the user's browser. Because ScreenSync MCP unites mobile inspection with 197 web_* browser tools via its Chrome/Edge extension, Claude Code can test the exact fallback URL end-to-end:
# Verify fallback URL directly on Android Chrome OR hand off URL to desktop Chrome extension
adb shell am start -a android.intent.action.VIEW -d "https://app.example.com/reader?doc=doc_arch_042§ion=2&scroll=840"
Using the ScreenSync MCP browser extension tools, Claude Code opens https://app.example.com/reader?doc=doc_arch_042§ion=2&scroll=840 in your real Chrome tab, verifies that the web reader restores section 2 at scroll offset 840, and confirms zero console errors or auth-redirect loops drop query parameters. Explore how the Browser MCP extension lets AI use your real Chrome tab and building cross-platform AI workflows unifying mobile and browser MCP for multi-surface test patterns.
Hardening Android 17 Handoff Edge Cases Before Production Release
Hardening Android 17 Handoff integrations requires testing security boundaries, PII exclusion, cold-start intent collisions, and multi-window configuration changes across real hardware. By automating adversarial checks with Claude Code, teams catch silent PersistableBundle truncation, stale deep-link query parsing, and unexpected onNewIntent state overwrites before shipping API 37 builds.
Before marking a Target SDK 37 release ready for Google Play, instruct Claude Code to audit these five high-risk Handoff edge cases:
| Edge Case Scenario | Root Cause in Android 17 Codebase | Automated Detection with Claude Code + ScreenSync MCP | Recommended Production Fix |
|---|---|---|---|
| PII or Auth Token Leak in Extras | Developer packs email, JWT, or session cookie into PersistableBundle |
Static Kotlin scan + adb logcat inspection of HandoffActivityData keys |
Pass only opaque resource IDs; re-authenticate on receiving device |
Dropped State on Warm onNewIntent |
Activity uses singleTop launchMode and reads intent only in onCreate() |
Send second ADB am start while Activity is foregrounded; check get_ui_hierarchy |
Override onNewIntent(intent) and invoke setIntent(intent) + state sync |
| Fallback URI Query Stripping on Auth | Web reader redirects unauthenticated user to /login, dropping ?doc=§ion= |
Drive fallback URL via ScreenSync web_* tools; assert final DOM section matches |
Persist redirect_to query params across OAuth/login handshake |
| Main-Thread ANR During Background Cache | onHandoffActivityDataRequested() queries Room DB synchronously on main thread |
Enable StrictMode (ThreadPolicy) and capture violations via get_logcat |
Maintain synchronous in-memory snapshot in ViewModel; never block callback |
| Handoff Left Active During Biometric/OTP | setHandoffEnabled(true) called in onResume() without checking active modal state |
Toggle sensitive flow and inspect isHandoffEnabled() logs + UI tree state |
Explicitly call setHandoffEnabled(false, null) when sensitive UI mounts |
When pairing Handoff testing with other Android 17 privacy and system-picker updates—such as session-scoped contacts—review testing Android 17 Contact Picker with Claude Code and MCP to ensure your app handles partial grants and cross-device handoffs consistently without requesting unnecessary permissions.
Automated Regression Checklist for CI & Local Pre-Merge Gates
Developers can save a reusable verification script or Claude Code slash prompt in their project repository so every PR touching Activity lifecycles or AndroidManifest.xml runs through the same physical-device checks:
- Confirm
record_screencaptures a clean video artifact if any UI state assertion fails during handoff resumption. - Verify
get_logcatcontains zeroStrictModedisk/network violations insideonHandoffActivityDataRequested(). - Assert
PersistableBundlebyte size stays strictly below51,200bytes across maximum-length drafts. - Validate both cold-start (
am force-stopfollowed byam start) and warm-resume (onNewIntent) handoff payloads. - Confirm
setFallbackUri()resolves cleanly in Chrome with query parameters preserved across navigation.
Conclusion and Next Steps
Testing the Android 17 Handoff API with Claude Code and ScreenSync MCP turns fragile multi-device continuity guesswork into a deterministic, automated verification loop. By pairing zero-root MediaProjection screen streaming with ADB control, logcat telemetry, and real Chrome tab inspection, mobile engineering teams ship resilient API 37 handoff experiences without slow cloud farms or brittle UI scripts.
As Android 17 enforces large-screen adaptivity and cross-device continuity across phones, foldables, and tablets, verifying setHandoffEnabled(), HandoffActivityData, and setFallbackUri() on real hardware is essential for production quality. With ScreenSync MCP's 226 local tools running directly alongside your Kotlin codebase in Claude Code, Cursor, or VS Code, you can catch serialization overflows, onNewIntent drops, and web fallback regressions in minutes.
Get started on your own Android 17 devices today:
- Install the free Android client (
com.screensync.mcp) directly from Google Play (linked in the setup CTA below) on any Android 7.0+ handset. - Download the free desktop hub via the ScreenSync MCP official site to pair your phone via QR code or LAN mDNS.
- Add the server with
claude mcp add screensync node "/path/to/hub/screensync-hub.js"and ask Claude Code to verify your first Android 17 Handoff workflow.
Next steps
Questions, answered
What does the Android 17 Handoff API do and how do activities opt in?
The Android 17 Handoff API (API level 37) lets users continue an active task from one Android device to another nearby device or browser. An Activity opts in by calling setHandoffEnabled(true, params) while resumed at the top of its task stack and overriding onHandoffActivityDataRequested() to return a HandoffActivityData payload.
Why does HandoffActivityData enforce a 50 KB PersistableBundle limit?
Android 17 caps the PersistableBundle inside HandoffActivityData under 50 KB because the system caches and transfers handoff metadata across devices over local continuity channels. Keeping payloads small ensures rapid transfer without stalling background caching, and forces apps to send lightweight identifiers rather than large binary blobs or sensitive PII.
Does ScreenSync MCP require root or ADB to capture Android Handoff screens?
ScreenSync MCP requires zero root access and zero ADB commands for screen capture. The free Android app (Android 7.0+) streams display frames using Android's native MediaProjection API after user consent each session. Control tools such as control_tap, control_type, launch_app, and get_logcat run through ADB over USB or wireless debugging.
How can Claude Code test Android 17 setFallbackUri() web handoff links?
When setAllowHandoffWithoutPackageInstalled(true) is enabled in HandoffActivityParams, Android 17 opens the fallback HTTPS URI in a browser if the app is missing on the target device. ScreenSync MCP provides 197 web_* tools through its Chrome/Edge extension, letting Claude Code open the exact fallback URL and verify DOM state restoration.
How does onHandoffActivityDataRequested() behave when an app moves to the background?
Android 17 invokes onHandoffActivityDataRequested(requestInfo) both when a user actively triggers a handoff (isActiveRequest is true) and when the Activity moves to the background so the OS can cache continuity state (isActiveRequest is false). Developers must keep this callback fast and non-blocking to avoid StrictMode violations or ANRs.
Can ScreenSync MCP test Android 17 Handoff on iOS or iPadOS devices?
No. ScreenSync MCP is built strictly for Android devices (Android 7.0 or later), a Windows/macOS/Linux Node.js 18+ desktop hub, and a Chrome/Edge MV3 browser extension. It does not support iOS or iPadOS hardware, and Android 17 Handoff itself is a native Android cross-device continuity API.
What is the screen streaming latency and privacy model of ScreenSync MCP?
ScreenSync MCP streams live Android frames directly from the phone to the local desktop hub on your Wi-Fi network at approximately 94 milliseconds median latency in EpsolDev tests, never passing through EpsolDev servers. However, any screenshot explicitly requested by an AI agent is sent to that agent's configured model provider.
How do I connect ScreenSync MCP to Claude Code for Android 17 testing?
Install the free com.screensync.mcp app from Google Play, start the Node.js 18+ desktop hub (start-hub.bat or start-hub.sh on port 3000), pair via QR code or LAN mDNS, and run claude mcp add screensync node "/path/to/hub/screensync-hub.js" to expose all 226 phone and browser MCP tools.




