ScreenSync MCP guide

Testing Android 17 Contact Picker with Claude Code and MCP

Test Android 17 Contact Picker (ACTION_PICK_CONTACTS), Session URIs, and multi-profile switches on real phones with Claude Code and ScreenSync MCP.

Minimalist 3D architectural render of an Android smartphone displaying a frosted-glass contact picker bottom sheet with a glowing purple privacy shield ring linked by fiber-optic light arcs to a developer laptop on a deep navy desk

Validating Android 17's system-mediated Contact Picker (ContactsPickerSessionContract.ACTION_PICK_CONTACTS) on physical mobile hardware exposes out-of-process UI, ContentResolver Session URI, and cross-profile bugs that unit tests and single-process instrumentation suites cannot detect. Released in Android 17 (API level 37), the new picker replaces broad READ_CONTACTS runtime permissions with ephemeral, field-scoped content://com.android.providers.contacts.picker.sessions/... URIs mediated entirely by the operating system. Because the picker renders inside an external system process and enforces strict SQL query restrictions, work-profile boundaries, and session expiration rules, legacy Espresso matchers fail at the window boundary while mocked cursors miss real SecurityException and IllegalArgumentException crashes. Connecting Claude Code to a physical Android device over the Model Context Protocol (MCP) using ScreenSync MCP gives engineering teams a deterministic way to drive the live Contact Picker UI, test Personal and Work profile switching, and audit Session URI queries in real time.

Key Takeaways

  • Out-of-process system picker visibility: ScreenSync MCP exposes the global accessibility hierarchy via get_ui_hierarchy and streams live pixels via get_latest_screenshot, letting Claude Code navigate the Android 17 system Contact Picker sheet and profile tabs that Espresso cannot reach.
  • Zero-root MediaProjection capture with ADB control: The ScreenSync MCP Android app (Android 7.0+, version 2.5.7) captures screen frames via Android's native MediaProjection API with no root and no ADB at roughly 94 ms median LAN latency, while control_tap, control_swipe, and control_type execute over USB or wireless ADB.
  • Session URI & SQL restriction verification: Claude Code automates multi-row cursor parsing, verifies that unrequested MIME types (Email, StructuredPostal) remain inaccessible, and catches crashes caused by unsupported selection or selectionArgs clauses on Session URIs.
  • Process-death & legacy upgrade regression checks: Combining ADB commands with get_logcat, Claude Code tests temporary Session URI expiration after process death and verifies Android 17's automatic Intent.ACTION_PICK upgrade on targetSdk 37 builds.
  • 226 unified MCP tools for end-to-end flows: Alongside 29 phone and desktop tools (12 control_*, 3 os_*, and 14 capture and hub tools), ScreenSync MCP exposes 197 web_* browser tools through a Chrome/Edge MV3 extension for full-stack CRM or invite-portal sync verification.
  • Local-first LAN privacy: Screen frames move strictly between your Android phone and local Node.js 18+ hub on port 3000 over your own network (never touching EpsolDev servers), while screenshots requested by an AI agent are sent to that agent's model provider.

Why Android 17 Contact Picker Breaks Traditional In-Process Tests

Traditional Android instrumentation frameworks fail on the Android 17 Contact Picker because the selection sheet runs inside an isolated system provider process rather than your application's process sandbox. Single-process test runners like Espresso cannot traverse external system windows, while Intent-stubbing mocks hide real ContentResolver Session URI exceptions, cursor grouping bugs, and cross-profile policy failures.

For more than a decade, Android apps needing a recipient's phone number or email address faced an uncomfortable choice: request the sweeping READ_CONTACTS dangerous permission—exposing the user's entire address book—or rely on legacy Intent.ACTION_PICK flows that returned a single opaque contact URI and still required complex secondary queries. Android 17 (API level 37) resolves this privacy gap with a system-mediated Contact Picker modeled after the modern Photo Picker.

However, shifting contact selection into a trusted system process creates four severe QA blind spots for mobile teams:

  1. Cross-Process UI Boundary: When an app launches ContactsPickerSessionContract.ACTION_PICK_CONTACTS, Android suspends the caller activity and displays a system-rendered sheet. Espresso's onView() matchers inspect only the host app's ViewRootImpl tree, throwing immediate NoMatchingViewException errors if a test attempts to tap a contact row or toggle between Personal and Work tabs.
  2. Intent Stubbing Hides Session URI Bugs: Many teams bypass the system UI using Intents.intending() to return a mocked content:// URI. Stubbing completely masks Android 17's strict Session URI constraints—most notably that querying content://com.android.providers.contacts.picker.sessions/... with custom SQL selection or selectionArgs throws an exception, and requesting multiple data fields returns multiple rows per contact rather than a flat single-row record.
  3. Ephemeral Session Expiration Across Process Death: Unlike permanent READ_CONTACTS grants, Contact Picker Session URIs are strictly temporary. If your app stores a Session URI in SavedStateHandle or Room and attempts to re-query it after background process death or session timeout, the ContentResolver query fails unless your code persisted the extracted contact fields immediately.
  4. Automatic Legacy ACTION_PICK Upgrades: Apps targeting API level 37 that still invoke legacy Intent.ACTION_PICK with supported contact MIME types are automatically routed to the new system picker. Legacy cursor adapters written for old ContactsContract schemas frequently break on the new Session URI column layout unless verified on real Android 17 hardware.

If your team already automates system-rendered media flows, our guide on testing Android Embedded Photo Picker with Claude Code details similar cross-process rendering challenges, while our breakdown of testing Android runtime permissions with Claude Code and MCP covers how system dialogs behave when READ_CONTACTS is replaced or revoked.

Testing Approach System Picker UI Interaction Real Session URI Queries Multi-Profile (Work/Personal) Switching Process-Death Expiration Triage Maintenance Overhead
Espresso + Intents.intending() None (mocked away) Mocked cursor; misses SQL selection throws Untested Untested against real provider Low, but high blind-spot risk
Robolectric Unit Tests Unavailable Simulated shadows only Unsupported In-memory only Low, misses system provider behavior
Static UIAutomator Scripts Brittle text/ID selectors across OEM skins Manual shell setup Breaks when profile tab labels localize Requires external ADB harness High maintenance on OS updates
ScreenSync MCP + Claude Code Adaptive get_ui_hierarchy + get_latest_screenshot Executes real ContentResolver queries on device Navigates Personal, Work, and Private Space tabs Automated adb shell am kill + get_logcat check Low; semantic agent reasoning adapts to UI

Android 17 Contact Picker Architecture: Contracts, Session URIs, and Scopes

The Android 17 Contact Picker relies on ContactsPickerSessionContract.ACTION_PICK_CONTACTS to launch a system-owned selection sheet and return a temporary, field-restricted Session URI. Instead of granting READ_CONTACTS, Android binds access to the caller's session lifecycle and enforces exact MIME-type field filtering at the ContentProvider boundary.

Understanding the exact API contract introduced in API level 37 helps developers write resilient Kotlin code and target the right failure modes during automated QA.

Core Intent Contract and Extras

To invoke the modern Contact Picker explicitly, build an Intent with ContactsPickerSessionContract.ACTION_PICK_CONTACTS ("android.provider.action.PICK_CONTACTS"). Declare the exact data fields your feature requires via EXTRA_PICK_CONTACTS_REQUESTED_DATA_FIELDS so the system UI displays only relevant contacts and restricts downstream cursor columns accordingly:

  • ContactsPickerSessionContract.ACTION_PICK_CONTACTS: Primary intent action ("android.provider.action.PICK_CONTACTS") handled exclusively by the trusted system Contact Picker package. Third-party apps cannot register intent filters to intercept this action.
  • EXTRA_PICK_CONTACTS_REQUESTED_DATA_FIELDS: ArrayList<String> containing supported ContactsContract.CommonDataKinds MIME types such as Phone.CONTENT_ITEM_TYPE and Email.CONTENT_ITEM_TYPE.
  • Intent.EXTRA_ALLOW_MULTIPLE: Boolean flag enabling multi-contact selection inside the system sheet.
  • ContactsPickerSessionContract.EXTRA_PICK_CONTACTS_SELECTION_LIMIT: Integer cap restricting the maximum number of contacts a user can select in one session.
  • "android.provider.extra.USE_SYSTEM_CONTACTS_PICKER": Compatibility boolean extra for apps still targeting API 36 or lower that want to force-test the system-mediated picker on Android 17 hardware prior to raising targetSdk.

Production Kotlin & Jetpack Compose Implementation

Below is a defensive Jetpack Compose implementation that launches the Android 17 Contact Picker, requests only phone and email fields, groups multi-row Cursor records by LOOKUP_KEY, and guards against Session URI exceptions without declaring READ_CONTACTS in AndroidManifest.xml:

package com.example.contacts.picker

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import android.provider.ContactsPickerSessionContract
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp

data class PickedContact(
    val lookupKey: String,
    val displayName: String,
    val phones: List<String>,
    val emails: List<String>
)

@Composable
fun ContactInviteScreen() {
    val context = LocalContext.current
    var contacts by remember { mutableStateOf<List<PickedContact>>(emptyList()) }
    var lastSessionUri by remember { mutableStateOf<Uri?>(null) }
    var statusMessage by remember { mutableStateOf("No contacts selected yet.") }

    val pickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode != Activity.RESULT_OK) {
            statusMessage = "Contact selection cancelled."
            return@rememberLauncherForActivityResult
        }

        val sessionUri = result.data?.data
        if (sessionUri == null) {
            statusMessage = "Missing Session URI in picker result."
            return@rememberLauncherForActivityResult
        }

        lastSessionUri = sessionUri
        runCatching {
            querySessionContacts(context, sessionUri)
        }.onSuccess { parsed ->
            contacts = parsed
            statusMessage = "Loaded ${parsed.size} contact(s) from Session URI."
        }.onFailure { err ->
            Log.e("ContactPickerQA", "Session URI query failed", err)
            statusMessage = "Session error: ${err.javaClass.simpleName}: ${err.message}"
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Text(text = statusMessage, style = MaterialTheme.typography.bodyMedium)

        Button(
            onClick = {
                val intent = Intent(ContactsPickerSessionContract.ACTION_PICK_CONTACTS).apply {
                    putStringArrayListExtra(
                        ContactsPickerSessionContract.EXTRA_PICK_CONTACTS_REQUESTED_DATA_FIELDS,
                        arrayListOf(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
                        )
                    )
                    putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                    putExtra(ContactsPickerSessionContract.EXTRA_PICK_CONTACTS_SELECTION_LIMIT, 5)
                }
                pickerLauncher.launch(intent)
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("Select Contacts (No Permission)")
        }

        Button(
            onClick = {
                val uri = lastSessionUri ?: return@Button
                runCatching {
                    querySessionContacts(context, uri)
                }.onSuccess {
                    statusMessage = "Re-queried active Session URI: ${it.size} contact(s)."
                }.onFailure { err ->
                    Log.w("ContactPickerQA", "Session URI expired or revoked", err)
                    statusMessage = "Re-query blocked: ${err.javaClass.simpleName}"
                }
            },
            enabled = lastSessionUri != null,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("Re-Query Cached Session URI")
        }

        LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            items(contacts, key = { it.lookupKey }) { contact ->
                Card(modifier = Modifier.fillMaxWidth()) {
                    Column(modifier = Modifier.padding(12.dp)) {
                        Text(contact.displayName, style = MaterialTheme.typography.titleMedium)
                        if (contact.phones.isNotEmpty()) {
                            Text("Phones: ${contact.phones.joinToString()}")
                        }
                        if (contact.emails.isNotEmpty()) {
                            Text("Emails: ${contact.emails.joinToString()}")
                        }
                    }
                }
            }
        }
    }
}

fun querySessionContacts(context: Context, sessionUri: Uri): List<PickedContact> {
    val projection = arrayOf(
        ContactsContract.Contacts.LOOKUP_KEY,
        ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
        ContactsContract.Data.MIMETYPE,
        ContactsContract.Data.DATA1
    )

    // IMPORTANT: Session URIs reject custom SQL selection / selectionArgs.
    val grouped = linkedMapOf<String, MutableTriple>()

    context.contentResolver.query(sessionUri, projection, null, null, null)?.use { cursor ->
        val lookupIdx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.LOOKUP_KEY)
        val nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)
        val mimeIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE)
        val dataIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA1)

        while (cursor.moveToNext()) {
            val lookupKey = cursor.getString(lookupIdx) ?: continue
            val displayName = cursor.getString(nameIdx).orEmpty()
            val mimeType = cursor.getString(mimeIdx).orEmpty()
            val value = cursor.getString(dataIdx).orEmpty()

            val entry = grouped.getOrPut(lookupKey) { MutableTriple(displayName) }
            when (mimeType) {
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE -> {
                    if (value.isNotBlank()) entry.phones.add(value)
                }
                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE -> {
                    if (value.isNotBlank()) entry.emails.add(value)
                }
            }
        }
    }

    return grouped.map { (key, acc) ->
        PickedContact(
            lookupKey = key,
            displayName = acc.name,
            phones = acc.phones.distinct(),
            emails = acc.emails.distinct()
        )
    }
}

private class MutableTriple(
    val name: String,
    val phones: MutableList<String> = mutableListOf(),
    val emails: MutableList<String> = mutableListOf()
)

Notice two subtle implementation invariants in querySessionContacts() above that frequently trip up developers migrating from READ_CONTACTS:

  1. Passing null for selection and selectionArgs: Contact Picker Session URIs prohibit custom SQL WHERE filters. Passing a non-null selection string throws an exception at runtime.
  2. Row-per-data-field grouping: Because a single contact can possess two phone numbers and one email address, the Session URI cursor yields multiple rows sharing the same LOOKUP_KEY. Apps that assume one cursor row equals one contact silently drop secondary numbers or render duplicate list cards.

Comparing Legacy READ_CONTACTS vs. Android 17 ACTION_PICK_CONTACTS

Architectural Attribute Legacy READ_CONTACTS Permission Legacy Intent.ACTION_PICK (Pre-API 37) Android 17 ACTION_PICK_CONTACTS
Manifest Permission android.permission.READ_CONTACTS (Dangerous) None for basic pick; READ_CONTACTS for extra fields None required
Data Exposure Scope Full address book (all contacts & all fields) Single contact URI (ContactsContract.Contacts) Strictly requested MIME fields for selected contacts only
Multi-Selection Custom in-app UI over full database Not natively standardized Built-in EXTRA_ALLOW_MULTIPLE + EXTRA_PICK_CONTACTS_SELECTION_LIMIT
Returned Handle Direct table access Persistent contact lookup URI Temporary Session URI (content://com.android.providers.contacts.picker.sessions/...)
Custom SQL selection Supported on ContactsContract Supported on ContactsContract Disallowed; throws exception if non-null selection is passed
Work / Personal Switching Restricted by cross-profile policies Limited or single-profile System-mediated Personal, Work, and Private Space switcher

How ScreenSync MCP Connects Claude Code to System Contact Sheets

ScreenSync MCP bridges Claude Code to physical Android 17 hardware using a split local architecture: zero-root MediaProjection streaming delivers live UI frames to your workstation, while an ADB control plane dispatches touch gestures, inspects cross-process accessibility trees, and streams Logcat diagnostics. This separation ensures Claude Code sees and drives system-owned Contact Picker dialogs just as a real user does.

Understanding how ScreenSync MCP routes perception and control explains why it overcomes the isolation walls of standard Android test runners:

  • Zero-Root MediaProjection Screen Capture: The ScreenSync MCP Android app (com.screensync.mcp, Android 7.0 or later, version 2.5.7) uses Android's native MediaProjection API after your interactive consent at the start of each session. Screen capture requires no root and no ADB, streaming display frames across your local Wi-Fi network at roughly 94 ms median latency in EpsolDev tests.
  • ADB Control & Diagnostic Plane: Deterministic interaction tools—such as control_tap, control_swipe, and control_type—and runtime inspection tools such as get_ui_hierarchy, get_logcat, and record_screen run through ADB from the desktop hub over USB or wireless debugging. For deeper architecture details on how node trees prevent coordinate drift, see our overview of why AI agents need the Android UI hierarchy.
  • Cross-Process get_ui_hierarchy Inspection: Unlike Espresso, which stops at your app's DecorView, get_ui_hierarchy dumps the active foreground accessibility window—even when the Android 17 system Contact Picker owns the screen. Claude Code reads exact contact row labels, profile switcher tabs, and selection limit counters before tapping.
  • 226 Unified MCP Tools: ScreenSync MCP exposes 29 phone and desktop tools (12 control_*, 3 os_*, and 14 capture and hub tools including get_latest_screenshot, get_ui_hierarchy, get_logcat, and record_screen) alongside 197 web_* browser tools through a Chrome/Edge Manifest V3 extension with human approval prompts for risky actions. For teams comparing this protocol layer against Appium or Maestro, review our Android MCP servers comparison and ScreenSync MCP server overview.
  • Local Network Privacy: Video frames move directly from the Android device to your desktop hub on port 3000 over your LAN and never pass through EpsolDev servers (Google Drive fallback is optional). Keep in mind for compliance reviews that any screenshot an AI agent requests via get_latest_screenshot is transmitted to that agent's model provider for visual analysis.

Step-by-Step Setup: Pairing Your Android 17 Device with Claude Code

Setting up ScreenSync MCP for Android 17 Contact Picker testing requires launching the Node.js 18+ desktop hub on port 3000, registering the local stdio server in Claude Code, installing the free Android companion app, and enabling USB or wireless ADB debugging. The entire stack—Android app, desktop hub, and browser extension—is free to download and runs locally.

Step 1: Launch the ScreenSync MCP Desktop Hub

Confirm your workstation runs Node.js 18+ on Windows, macOS, or Linux with adb in your system PATH. Download and unpack the hub archive following the ScreenSync MCP setup guide, then launch the hub:

# Windows (PowerShell or Command Prompt)
cd C:\tools\screensync-hub
start-hub.bat

# macOS or Linux
cd ~/tools/screensync-hub
chmod +x start-hub.sh
./start-hub.sh

The hub starts an HTTP ingest server on port 3000, serves the Model Context Protocol (MCP) over stdio, outputs your SCREEN_SYNC_TOKEN, and renders a pairing QR code in the console.

Step 2: Register ScreenSync MCP in Claude Code or Claude Desktop

Add the local stdio server to Claude Code using the path where you unpacked the hub directory:

claude mcp add screensync node "/path/to/hub/screensync-hub.js"

If you are driving tests from Claude Desktop, open Settings > Developer (claude_desktop_config.json) and add the server block with your token:

{
  "mcpServers": {
    "screensync": {
      "command": "node",
      "args": ["/path/to/hub/screensync-hub.js"],
      "env": {
        "SCREEN_SYNC_TOKEN": "your_screen_sync_token"
      }
    }
  }
}

ScreenSync MCP works with local stdio MCP clients including Claude Code, Claude Desktop, Cursor, and VS Code agent mode (consult Cursor or VS Code's MCP documentation for workspace config paths; ChatGPT's web app requires remote HTTPS MCP and is not supported).

Step 3: Pair the Android App and Authorize ADB

  1. Download the free ScreenSync MCP Android app (com.screensync.mcp, version 2.5.7, Android 7.0+) from Google Play onto your Android 17 physical test device.
  2. Open the app, scan the hub's QR code or connect via LAN mDNS auto-discovery, and accept Android's MediaProjection capture consent dialog (no root, no ADB required for capture).
  3. Enable USB Debugging or Wireless Debugging in Developer Options so ADB control tools (control_tap, control_swipe, control_type) can operate, then verify your device appears in adb devices.
  4. If your QA flow also verifies invited contacts inside a web admin dashboard, install the Chrome/Edge MV3 companion described on the ScreenSync MCP browser extension page.

Practical QA Workflows: Automating Contact Picker Scenarios End-to-End

End-to-end Android 17 Contact Picker QA with Claude Code covers five critical test vectors: verifying system intent resolution without READ_CONTACTS, testing multi-selection caps and field scoping, switching across Personal and Work profiles, catching invalid SQL selection crashes, and confirming Session URI expiration after process death.

Workflow 1: Verifying System Intent Resolution and Zero-Permission Launch

Before tapping UI elements, confirm that the device resolves android.provider.action.PICK_CONTACTS strictly to the trusted system Contact Picker and that your APK declares zero READ_CONTACTS permissions.

Developer Prompt to Claude Code:

Verify that com.example.contacts.picker does not request READ_CONTACTS, confirm that android.provider.action.PICK_CONTACTS resolves to the system Contact Picker on the connected Android 17 phone, launch the app, tap "Select Contacts (No Permission)", and capture get_ui_hierarchy and get_latest_screenshot to confirm the system sheet appears without any runtime permission dialog.

Claude Code executes the preflight ADB diagnostics from the terminal:

# 1. Confirm READ_CONTACTS is absent from the installed package's requested permissions
adb shell dumpsys package com.example.contacts.picker | grep -i "READ_CONTACTS"

# 2. Verify ACTION_PICK_CONTACTS resolves strictly to the trusted system picker
adb shell cmd package resolve-activity --brief -a android.provider.action.PICK_CONTACTS

Next, Claude Code launches the app, locates the "Select Contacts (No Permission)" button via get_ui_hierarchy, taps it with control_tap, and inspects the resulting system window. Because no runtime permission modal intercepts the flow, get_ui_hierarchy immediately reveals the system Contact Picker sheet, while get_latest_screenshot confirms the visual layout renders cleanly above your app.

Workflow 2: Testing Field Scoping, Multi-Select Limits, and Cursor Grouping

Applications requesting Phone.CONTENT_ITEM_TYPE and Email.CONTENT_ITEM_TYPE with EXTRA_PICK_CONTACTS_SELECTION_LIMIT = 5 must display only those fields, enforce the 5-contact cap in the UI, and deduplicate multi-row cursors per LOOKUP_KEY.

Developer Prompt to Claude Code:

In the open Android 17 Contact Picker sheet, select 6 different contacts (each having multiple phone numbers and emails) to verify whether the 6th selection is blocked by the selection limit of 5. Then confirm the selection, verify via get_ui_hierarchy that exactly 5 grouped contact cards render in our app without duplicates, and check get_logcat for any cursor column or Session URI errors.

Here is how Claude Code executes and asserts the flow:

  1. Seed Deterministic Test Contacts via ADB (if testing on a clean QA handset):
    # Verify existing contacts count via content provider (from shell) or seed test fixtures beforehand
    adb logcat -c
  2. Drive Multi-Selection via get_ui_hierarchy and control_tap: Claude Code reads the contact rows in the system picker accessibility tree, taps five rows sequentially, and attempts a sixth tap.
  3. Visual Limit Audit: Calling get_latest_screenshot, Claude Code verifies that the sixth row remains unselected or displays the system's selection-limit feedback banner, then taps the picker's Done / Add confirmation button.
  4. Cursor Grouping Verification: Back inside com.example.contacts.picker, get_ui_hierarchy confirms "Loaded 5 contact(s) from Session URI." and verifies that a contact with two phone numbers appears as a single card listing both numbers rather than two duplicate cards.
  5. Logcat Scope Check: Calling get_logcat filtered on ContactPickerQA, Claude Code ensures zero IllegalArgumentException or CursorIndexOutOfBoundsException messages fired.

Workflow 3: Testing Personal vs. Work Profile Switching

Android 17's Contact Picker surfaces an inline profile switcher allowing users to jump between Personal, Work (managed profile), and Private Space contacts. Apps must parse LOOKUP_KEY values and display names cleanly regardless of which profile originates the selection—especially when corporate IT policies restrict cross-profile contact sharing.

Developer Prompt to Claude Code:

Start record_screen, open the Contact Picker in com.example.contacts.picker, switch to the Work profile tab in the picker UI, select a managed work contact, and verify that the Session URI returns the expected phone/email fields (or respects enterprise restriction policies cleanly without crashing).
  1. Claude Code calls record_screen to capture visual evidence of the cross-profile transition.
  2. Inspecting get_ui_hierarchy, Claude Code locates the Work profile tab inside the system picker header and invokes control_tap.
  3. It selects a work contact (or verifies the enterprise-blocked empty state via get_latest_screenshot if cross-profile sharing is disabled by the Device Policy Controller), confirms selection, and inspects get_logcat to ensure the ContentResolver parser handled the cross-profile LOOKUP_KEY without null-pointer exceptions.

Workflow 4: Detecting SQL selection Crashes and Unrequested Field Leakage

A common migration bug happens when developers pass a legacy selection string—such as "mimetype = ?"—to contentResolver.query(sessionUri, projection, selection, selectionArgs, null). Android 17 Session URIs reject custom SQL WHERE clauses. Similarly, apps that try to read StructuredPostal.FORMATTED_ADDRESS when only Phone and Email were requested receive zero rows or empty values for the unrequested MIME type.

Developer Prompt to Claude Code:

Review querySessionContacts in ContactInviteScreen.kt, temporarily add a test case or trigger the query with a non-null SQL selection clause and an unrequested MIME field, run it on the physical Android 17 device, capture get_logcat to observe the exact ContentProvider exception, and verify our runCatching handler surfaces a non-fatal error state instead of crashing the app.

Because Claude Code operates directly inside your repository and on the physical Android device via ScreenSync MCP, it closes the full code-to-device feedback loop: it inspects the stack trace in get_logcat, confirms the UI displays "Session error: ..." rather than crashing with FATAL EXCEPTION: main, and restores or hardens the production query code. For more patterns on validating ContentResolver and IPC boundaries, read our guide on testing Android Content Providers with Claude Code and MCP.

Workflow 5: Testing Session URI Expiration Across Process Death

Session URIs grant temporary access tied to the active session. If an app caches the URI string in SavedStateHandle or local preferences and tries to query it again after process death, Android revokes access.

Developer Prompt to Claude Code:

Pick 2 contacts in com.example.contacts.picker so the Session URI is cached in UI state. Background the app, simulate Android process death via ADB, relaunch the app, tap "Re-Query Cached Session URI", and verify via get_logcat and get_ui_hierarchy that the app catches the security/permission failure gracefully without crashing.

Claude Code runs the standard process-death sequence on the physical phone:

# Send the app to the background first so Android treats it as a killable background process
adb shell input keyevent KEYCODE_HOME
sleep 2

# Terminate the app process to simulate low-memory process death
adb shell am kill com.example.contacts.picker

After relaunching the app via ADB or control_tap, Claude Code taps "Re-Query Cached Session URI", calls get_logcat to inspect the resulting SecurityException or stale-session denial, and confirms the UI renders "Re-query blocked: SecurityException" safely instead of crashing. For full SavedStateHandle and process-death state-restoration patterns, see testing Android process death with Claude Code and MCP.

Workflow 6: Synchronized Mobile + Web CRM Invite Verification

If your app lets users pick contacts on Android and immediately dispatches invites or syncs leads visible in a web admin portal, ScreenSync MCP's 197 web_* browser tools let Claude Code verify both ends in a single session. After completing the Contact Picker flow on your Android 17 phone, Claude Code uses the Chrome/Edge MV3 extension (which pauses with human approval prompts for risky actions) to open your web dashboard, refresh the invited-contacts table, and verify that only the selected phone number or email—and zero unrequested address-book data—was uploaded.

Triaging Common Android 17 Contact Picker Failures with ADB and Logcat

Diagnosing Android 17 Contact Picker defects requires correlating ContentResolver exceptions in get_logcat, package intent resolution via ADB, and visual state captures from get_latest_screenshot. The reference table below maps the most frequent production and migration symptoms to their root causes and verified fixes.

Failure Symptom Likely Root Cause Diagnostic Tool / ADB Command Resolution
Crash when querying sessionUri Non-null SQL selection or selectionArgs passed to contentResolver.query() get_logcat (DatabaseUtils / IllegalArgumentException) Pass null, null, null for selection, selectionArgs, and sortOrder; filter in Kotlin
Duplicate contact cards in UI Multi-row cursor (one row per phone/email) treated as 1-to-1 contact records get_ui_hierarchy + querySessionContacts audit Group cursor rows by ContactsContract.Contacts.LOOKUP_KEY
Unrequested fields return empty/null MIME type omitted from EXTRA_PICK_CONTACTS_REQUESTED_DATA_FIELDS Inspect Intent extras + get_logcat Add needed CommonDataKinds.*.CONTENT_ITEM_TYPE to requested fields list
Legacy ACTION_PICK breaks on API 37 App upgraded to targetSdk 37 triggers automatic system picker routing adb shell logcat -s ActivityManager IntentResolver Migrate parser to LOOKUP_KEY + Session URI cursor schema
Crash after backgrounding or restart Cached Session URI re-queried after session expiration or process death adb shell am kill <pkg> + get_logcat (SecurityException) Extract and persist needed contact strings in memory/DB immediately on RESULT_OK
Missing Work profile contacts Enterprise DPC blocks cross-profile contact sharing or parser fails on work IDs record_screen + get_latest_screenshot during tab switch Handle empty work-profile results gracefully; avoid hardcoding local numeric _IDs
Third-party app cannot intercept action Custom app tried declaring intent filter for ACTION_PICK_CONTACTS adb shell cmd package resolve-activity --brief -a android.provider.action.PICK_CONTACTS Expected Android 17 security behavior; rely solely on system Contact Picker

For backward-compatibility checks on builds still targeting Android 16 or lower, run your test suite on an Android 17 device with the compatibility flag injected so you catch cursor and SQL regressions before bumping targetSdk:

val compatTestIntent = Intent(Intent.ACTION_PICK).apply {
    type = ContactsContract.Contacts.CONTENT_TYPE
    putExtra("android.provider.extra.USE_SYSTEM_CONTACTS_PICKER", true)
}

And use these quick ADB diagnostic commands inside Claude Code whenever triaging intent routing or picker lifecycle issues:

# Monitor ActivityManager and IntentResolver transitions when launching the picker
adb shell logcat -s ActivityManager IntentResolver ContactPickerQA

# Confirm your app manifest no longer requests READ_CONTACTS
adb shell dumpsys package com.example.contacts.picker | grep -A 5 "requested permissions:"

Implementation Checklist for Android 17 Contact Picker QA

  • [ ] Remove android.permission.READ_CONTACTS from AndroidManifest.xml wherever contact selection is purely user-initiated.
  • [ ] Launch ContactsPickerSessionContract.ACTION_PICK_CONTACTS with explicit EXTRA_PICK_CONTACTS_REQUESTED_DATA_FIELDS MIME types and EXTRA_PICK_CONTACTS_SELECTION_LIMIT when multi-select is enabled.
  • [ ] Pass null for selection and selectionArgs in contentResolver.query(sessionUri, ...) and group multi-row cursors by LOOKUP_KEY in Kotlin.
  • [ ] Extract contact fields immediately inside ActivityResultContracts.StartActivityForResult and never rely on re-querying a persisted Session URI across process death.
  • [ ] Test legacy Intent.ACTION_PICK flows with "android.provider.extra.USE_SYSTEM_CONTACTS_PICKER" enabled on Android 17 hardware prior to upgrading targetSdk to 37.
  • [ ] Launch the ScreenSync MCP desktop hub (Node.js 18+, start-hub.bat or start-hub.sh, HTTP port 3000) and register it in Claude Code with claude mcp add screensync node "/path/to/hub/screensync-hub.js".
  • [ ] Pair the free ScreenSync MCP Android app (com.screensync.mcp, Android 7.0+, version 2.5.7), approve MediaProjection capture (zero root, zero ADB for capture), and verify USB or wireless ADB for control_tap, control_swipe, get_ui_hierarchy, and get_logcat.

Conclusion

Testing the Android 17 Contact Picker (ContactsPickerSessionContract.ACTION_PICK_CONTACTS) with Claude Code and ScreenSync MCP ensures your privacy-preserving contact flows work reliably on real hardware before users encounter them. By combining zero-root MediaProjection visual capture (~94 ms median LAN latency) with ADB-driven control and get_ui_hierarchy inspection across system boundaries, engineering teams catch invalid SQL selection queries, multi-row cursor duplication, work-profile edge cases, and Session URI expiration bugs that single-process Espresso suites miss.

Ready to automate real-device Android 17 QA directly from your terminal? Check the ScreenSync MCP Android & browser QA hub to grab the free desktop archive and pair your physical test phone in minutes.

Next steps

FAQ

Questions, answered

What is the Android 17 Contact Picker and why does it replace READ_CONTACTS?

Android 17 introduces a system-mediated Contact Picker launched via ContactsPickerSessionContract.ACTION_PICK_CONTACTS. Instead of granting broad READ_CONTACTS access to a user's entire address book, the OS lets the user pick specific contacts and returns a temporary Session URI restricted strictly to the requested MIME data fields.

Why do Espresso tests fail when automating the Android 17 Contact Picker?

Espresso executes inside your application's local memory process and can only inspect views inside your app's window hierarchy. Because the Android 17 Contact Picker renders in an external system provider process, Espresso throws a NoMatchingViewException when trying to tap contacts or switch Personal and Work profile tabs.

Why does querying a Contact Picker Session URI with a SQL selection clause fail?

Contact Picker Session URIs (content://com.android.providers.contacts.picker.sessions/...) prohibit custom SQL selection or selectionArgs parameters at the system ContentProvider boundary. Passing non-null WHERE clauses to contentResolver.query() throws an exception at runtime, so developers must pass null for selection arguments and filter or group results inside Kotlin.

How long does an Android 17 Contact Picker Session URI remain valid?

Session URIs grant temporary, session-scoped read access rather than permanent database permissions. After process death or session expiration, re-querying the cached Session URI fails with a security or permission exception, so apps should extract and store required contact fields immediately upon Activity.RESULT_OK.

Does ScreenSync MCP require root access or ADB to capture the Contact Picker UI?

No. ScreenSync MCP captures screen frames using Android's native MediaProjection API after user consent each session, requiring zero root access and zero ADB for capture. However, executing control tools like control_tap, control_swipe, and control_type requires ADB over USB or wireless debugging.

How does Claude Code handle Work and Personal profile switching in the Contact Picker?

Claude Code calls ScreenSync MCP's get_ui_hierarchy tool to read the active system window's accessibility nodes, locates the Personal or Work profile tab inside the Contact Picker sheet, switches tabs with control_tap, and inspects get_latest_screenshot and get_logcat to verify policy-compliant results.

How does ScreenSync MCP protect private contact data during automated testing?

Display frames travel directly from the ScreenSync MCP Android app to your local desktop hub on port 3000 over your own LAN without touching EpsolDev servers, and Drive fallback is optional. Screenshots explicitly requested by an AI agent are sent to that agent's configured model provider.

Which AI coding clients can run ScreenSync MCP for Android 17 testing?

ScreenSync MCP integrates with Model Context Protocol clients that run local stdio servers on Windows, macOS, or Linux, including Claude Code, Claude Desktop, Cursor, and VS Code agent mode. ChatGPT's web application requires remote HTTPS MCP endpoints and is not supported.

Written by

ScreenSync MCP team

The ScreenSync MCP team at EpsolDev builds the Android app, the desktop MCP hub and the browser extension that let AI agents see and control a real phone. These guides come out of that work.