On this page
Testing Android Near Field Communication (NFC) and Host Card Emulation (HCE) on physical devices represents one of the most stubborn friction points in mobile engineering. Unlike visual layouts or network queries that can be readily synthesized in virtual environments, contactless mobile architectures operate at the physical interface of electromagnetic radio frequency (RF) induction, hardware secure elements, and low-latency smart card protocols. Standard Android Virtual Devices (AVD) running in continuous integration pipelines do not emulate physical NFC controllers or ISO/IEC 7816-4 Application Protocol Data Unit (APDU) exchanges. Consequently, engineering teams building mobile payment wallets, digital identity passes, transit ticketing systems, and smart IoT provisioning clients frequently resort to manual hardware testing—physically tapping phones against retail point-of-sale (POS) terminals or desktop NFC readers. This manual bottleneck slows release cadences, prevents regression testing across edge-case payment states, and leaves critical failure modes undetected until production. By orchestrating terminal-based AI coding agents like Claude Code with the Model Context Protocol (MCP) through ScreenSync MCP, developers can automate end-to-end NFC tag dispatch handling, simulate HCE contactless transactions, verify on-screen payment receipts via high-speed visual perception, and audit low-level APDU telemetry on authentic physical Android hardware.
Key Takeaways
- Decoupled physical hardware testing: ScreenSync MCP empowers Claude Code to automate NFC tag dispatch, Host Card Emulation (HCE), and wallet role handovers directly on authentic Android hardware without requiring physical tag tapping.
- Synthetic NDEF intent injection: Claude Code programmatically generates and broadcasts complex
ACTION_NDEF_DISCOVEREDandACTION_TECH_DISCOVEREDintents with raw MIME payloads via ADB shell dispatchers to validate tag processing state machines. - Deterministic HCE APDU logging and triage: Stream real-time NFC controller and card emulation telemetry through
get_logcatto audit ISO/IEC 7816-4 APDU command-response timings and detect fatal reader deactivation timeouts. - Continuous local MediaProjection visual verification: Real-time display frames stream from physical devices to the desktop workstation at approximately 94 milliseconds median latency, allowing agents to verify checkout animations, receipt dialogs, and biometric prompts without ADB bandwidth contention.
- Full Android 14 and 15 payment architecture coverage: Validate dynamic Application Identifier (AID) registration, default contactless payment app role transitions via
RoleManager.ROLE_WALLET, and reader mode polling loops. - Unified 226-tool automation ecosystem: ScreenSync MCP pairs 29 mobile and desktop tools (12
control_*, 3os_*, and 14 capture tools) with 197 browser tools to verify cross-surface payment lifecycles and merchant gateway configurations in a single run.
Why Emulators and Unit Tests Fail at Contactless Hardware Boundaries
In-process unit tests and Android emulators fail at contactless hardware boundaries because Android Virtual Devices do not expose physical NFC controllers, while mock frameworks bypass the operating system's native NFC service daemon and HAL. Synthetic tests cannot reproduce real RF link loss, APDU response timeouts, or OEM-specific secure element routing.
To understand why automated NFC and Host Card Emulation testing has historically been intractable in mobile continuous integration, one must examine the execution layers of the Android contactless architecture. When an Android smartphone approaches an active point-of-sale terminal or smart poster, physical communication occurs over the 13.56 MHz High Frequency radio band governed by ISO/IEC 14443 and ISO/IEC 7816 standards. The phone's internal NFC controller hardware communicates with the Android kernel through dedicated hardware abstraction layer (HAL) drivers (android.hardware.nfc). Above the kernel, the native nfc_service daemon manages the radio frequency discovery loop, Application Identifier (AID) routing tables, and dispatch channels.
Standard Android Virtual Devices (AVDs) running in headless CI containers on Linux workstations or cloud runners (such as GitHub Actions or AWS EC2) possess no physical NFC radio controllers. While the Android Open Source Project provides dummy HAL stubs, emulators cannot simulate RF modulation, field detection, or the asynchronous arrival of APDU packets from an external reader. When developers attempt to execute instrumentation tests on emulators, NfcAdapter.getDefaultAdapter(context) routinely returns null, forcing teams to either mock the adapter or disable NFC test suites entirely.
// Brittle Mocking in Unit Tests: Bypasses the entire Android OS NFC stack
val mockNfcAdapter = mockk<NfcAdapter>()
every { mockNfcAdapter.isEnabled } returns true
// This unit test validates Kotlin view-model logic, but completely misses:
// 1. AndroidManifest.xml AID registration conflicts
// 2. HostApduService process lifecycle kills
// 3. APDU command chunking and SW1-SW2 status word parsing
// 4. POS terminal 250ms deactivation timeouts
Furthermore, in-process mock runners like Mockito or Robolectric isolate test execution to the Java Virtual Machine. They verify whether an activity registers an intent filter, but they cannot evaluate how the Android operating system actually dispatches intents when the screen is locked, when another payment app holds default wallet privileges, or when the user has disabled NFC in system settings.
| NFC Testing Dimension | Mockito / Robolectric Unit Tests | Android Emulator (AVD) | Cloud Device Farms (SauceLabs / BrowserStack) | ScreenSync MCP + Claude Code (Physical Device) |
|---|---|---|---|---|
| Physical Radio & HAL Emulation | Impossible; mocks Java class interfaces only | Unavailable; virtual controllers lack RF simulation | Limited; remote cloud devices block physical RF field access | Authentic; runs directly on physical Android 7.0+ hardware |
| NDEF Tag Dispatch Simulation | Fails; cannot invoke native OS nfc_service dispatch |
Unreliable; requires brittle custom socket hacks | Difficult; cloud network latency prevents timely intent injection | Deterministic; injects raw NDEF records and MIME intents via ADB |
| Host Card Emulation (HCE) APDUs | Impossible; cannot test HostApduService IPC |
Unsupported; emulators cannot emulate smart card readers | Infeasible; unable to simulate external POS terminal polling | Full audit; tracks ISO 7816-4 APDU exchanges and timings in logcat |
| Default Wallet Role Verification | Bypassed; cannot interact with RoleManager modals |
Flaky; cannot assert OEM-specific system wallet sheets | Brittle; cloud screen capture suffers high lag on modals | Native; inspects and navigates system dialogs via get_ui_hierarchy |
| Visual Confirmation of Payment UX | None; view assertions do not verify frame rendering | Static screenshots only; lacks real hardware GPU rendering | WebRTC video streams with high latency (>500 ms) | High-speed MediaProjection stream (~94 ms median latency) |
| RF Deactivation and Link Loss | Mocked; cannot test sudden field loss during transfer | Completely unsupported | Inaccessible; cannot simulate physical phone withdrawal | Precise; triggers onDeactivated() transitions and audits UI recovery |
ScreenSync MCP resolves this architectural gap by executing directly against authentic physical Android smartphones. Operating from a local workstation over high-speed USB or local Wi-Fi, Claude Code leverages ScreenSync MCP's tripartite architecture: injecting synthetic NDEF intents and shell commands over ADB, verifying on-screen checkout states through sub-100ms MediaProjection video frames, and auditing low-level NFC HAL telemetry via real-time logcat inspection.
Android NFC Architecture: Tag Dispatch, NDEF Payloads, and Host Card Emulation (HCE)
Android's contactless architecture splits into two primary operating modes: Reader/Writer mode (governed by the Tag Dispatch System) and Card Emulation mode (governed by Host Card Emulation). Reader mode parses structured NDEF records from external tags, while HCE routes contactless ISO/IEC 7816-4 smart card commands directly to user-space Android services without requiring a hardware Secure Element.
Mastering automated testing requires a precise grasp of how the Android operating system processes contactless communications across its two distinct pathways:
1. The Tag Dispatch System (Reader/Writer Mode)
When an Android device reads a contactless NFC tag (such as an NTAG213, NTAG215, or MIFARE Classic chip), the operating system's nfc_service parses the tag's raw memory blocks for NFC Data Exchange Format (NDEF) messages. An NDEF message consists of one or more NDEF Records containing a 3-bit Type Name Format (TNF) header and a payload (such as a URI, plain text, or an Android Application Record).
The Android operating system evaluates active applications using a strict three-tier priority dispatch hierarchy:
ACTION_NDEF_DISCOVERED: The highest-priority intent. Triggered when the tag contains an NDEF payload and an installed application declares an<intent-filter>matching the specific MIME type or URI scheme.ACTION_TECH_DISCOVERED: The secondary intent. Triggered if no application claimed the specific NDEF record, but an application registered support for the underlying RF technology family (such asNfcA,NfcB,IsoDep, orMifareUltralight) in an XML resource file.ACTION_TAG_DISCOVERED: The fallback intent. Dispatched as a generic broadcast if no installed application claimed the NDEF or tech-specific intents.
2. Host Card Emulation (HCE) and the APDU Protocol
Introduced in Android 4.4 (KitKat) and expanded in Android 14 and 15, Host Card Emulation allows an Android application to emulate an ISO/IEC 14443-4 Type A or Type B smart card. Prior to HCE, card emulation required a tamper-resistant hardware chip called a Secure Element (SE) owned by mobile network operators or device OEMs. With HCE, smart card commands from an external point-of-sale terminal bypass the SIM card or embedded Secure Element and route directly to a software service extending HostApduService.
Communication between the POS terminal reader and the Android application follows the ISO/IEC 7816-4 smart card standard using Application Protocol Data Units (APDUs). An APDU command consists of a 4-byte header and an optional payload:
- CLA (Class Byte): Specifies the instruction class (e.g.,
00for standard ISO commands). - INS (Instruction Byte): Specifies the operation (e.g.,
A4forSELECT AID,B0forREAD BINARY). - P1 - P2 (Parameter Bytes): Provide qualifiers for the instruction.
- Lc (Length of Command Data): Specifies the byte count of the incoming data block.
- Data Field: The command payload (e.g., the Application Identifier byte array).
- Le (Length of Expected Response): Specifies the maximum number of response bytes expected.
The Android HostApduService processes incoming command APDUs in its processCommandApdu(commandApdu: ByteArray, extras: Bundle?) callback and returns a response APDU terminating in a two-byte Status Word (SW1-SW2), such as 90 00 (Success) or 6A 82 (File/Application Not Found).
Production Kotlin Implementation: Resilient Host Card Emulation Service
Here is a production-ready Kotlin implementation of an HCE service configured to process contactless payments, validate Application Identifiers, handle transaction APDUs, and notify foreground activities:
package com.example.screensync.nfc
import android.nfc.cardemulation.HostApduService
import android.os.Bundle
import android.util.Log
class NfcPaymentApduService : HostApduService() {
companion object {
private const val TAG = "NfcPaymentHCE"
// Registered Application Identifier (AID) for Loyalty/Payment Demo
private const val SAMPLE_LOYALTY_AID = "F0010203040506"
// ISO 7816-4 Command Definitions
private val SELECT_APDU_HEADER = byteArrayOf(
0x00.toByte(), // CLA: Standard ISO
0xA4.toByte(), // INS: SELECT FILE / AID
0x04.toByte(), // P1: Select by direct DF name (AID)
0x00.toByte() // P2: First or only occurrence
)
// Status Words (SW1-SW2)
private val STATUS_SUCCESS = byteArrayOf(0x90.toByte(), 0x00.toByte())
private val STATUS_FAILED = byteArrayOf(0x6F.toByte(), 0x00.toByte())
private val STATUS_FILE_NOT_FOUND = byteArrayOf(0x6A.toByte(), 0x82.toByte())
private val STATUS_UNKNOWN_COMMAND = byteArrayOf(0x6D.toByte(), 0x00.toByte())
}
override fun processCommandApdu(commandApdu: ByteArray, extras: Bundle?): ByteArray {
val hexCommand = commandApdu.toHexString()
Log.i(TAG, "Received APDU: $hexCommand (Length: ${commandApdu.size})")
// Validate minimum APDU header length
if (commandApdu.size < 4) {
Log.e(TAG, "Malformed APDU: Header length under 4 bytes")
return STATUS_FAILED
}
// Check if this is a SELECT AID command
if (isSelectAidCommand(commandApdu)) {
val aidBytes = commandApdu.copyOfRange(5, 5 + commandApdu[4].toInt())
val targetAid = aidBytes.toHexString()
Log.i(TAG, "SELECT AID command received for AID: $targetAid")
return if (targetAid.equals(SAMPLE_LOYALTY_AID, ignoreCase = true)) {
Log.i(TAG, "AID match confirmed. Returning application confirmation payload.")
val responsePayload = "PAYMENT_CLIENT_V1_READY".toByteArray(Charsets.UTF_8)
responsePayload + STATUS_SUCCESS
} else {
Log.w(TAG, "Unrecognized AID requested: $targetAid")
STATUS_FILE_NOT_FOUND
}
}
// Process Custom Transaction Execution Command (e.g., INS = 0xC0)
if (commandApdu[1] == 0xC0.toByte()) {
Log.i(TAG, "Executing contactless payment token exchange...")
val transactionReceiptToken = "TX_SECURE_TOKEN_9847120".toByteArray(Charsets.UTF_8)
return transactionReceiptToken + STATUS_SUCCESS
}
Log.w(TAG, "Unknown APDU instruction: ${commandApdu[1]}")
return STATUS_UNKNOWN_COMMAND
}
override fun onDeactivated(reason: Int) {
val reasonStr = when (reason) {
DEACTIVATION_LINK_LOSS -> "DEACTIVATION_LINK_LOSS (Device moved away from RF field)"
DEACTIVATION_DESELECTED -> "DEACTIVATION_DESELECTED (Another AID selected)"
else -> "UNKNOWN ($reason)"
}
Log.i(TAG, "HCE Service Deactivated: $reasonStr")
}
private fun isSelectAidCommand(apdu: ByteArray): Boolean {
return apdu.size >= 4 &&
apdu[0] == SELECT_APDU_HEADER[0] &&
apdu[1] == SELECT_APDU_HEADER[1] &&
apdu[2] == SELECT_APDU_HEADER[2] &&
apdu[3] == SELECT_APDU_HEADER[3]
}
private fun ByteArray.toHexString(): String {
return joinToString("") { "%02X".format(it) }
}
}
The APDU Service Declaration (apduservice.xml)
For the Android operating system to route incoming contactless requests to your service, you must declare an XML configuration file inside res/xml/apduservice.xml specifying whether the service handles payment or other categories:
<?xml version="1.0" encoding="utf-8"?>
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/nfc_payment_service_desc"
android:requireDeviceUnlock="true">
<aid-group android:description="@string/loyalty_payment_group"
android:category="payment">
<aid-filter android:name="F0010203040506"/>
</aid-group>
</host-apdu-service>
When building security-critical applications, developers should combine NFC tests with testing Android Keystore security with Claude Code and MCP to guarantee that cryptographic payment tokens are generated and signed inside the device's hardware-backed Trusted Execution Environment (TEE) or StrongBox keymaster.
| APDU Instruction / Field | Hex Value | Standard / Specification | Architectural Purpose | Android HCE Handling Mechanism |
|---|---|---|---|---|
| SELECT FILE / AID | 00 A4 04 00 |
ISO/IEC 7816-4 | Dispatched by POS terminal to locate and activate specific card applet | Android OS evaluates apduservice.xml filters and routes to HostApduService |
| GET PROCESSING OPTIONS | 80 A8 00 00 |
EMV Contactless Book 3 | Initiates payment transaction flow and transmits terminal capabilities | App verifies transaction limits and returns Application Interchange Profile |
| READ RECORD | 00 B2 <Rec> <SFI> |
ISO/IEC 7816-4 | Retrieves public cardholder metadata or non-sensitive certificates | Service reads structured EMV records and appends 90 00 status word |
| GENERATE AC (Cryptogram) | 80 AE <P1> 00 |
EMV Contactless Book 3 | Requests cryptographically signed payment token (ARQC or TC) | App signs transaction payload using KeyStore asymmetric private key |
| SW1-SW2: SUCCESS | 90 00 |
ISO/IEC 7816-4 | Confirms command completed successfully | App returns requested data bytes concatenated with 0x90 0x00 |
| SW1-SW2: FILE NOT FOUND | 6A 82 |
ISO/IEC 7816-4 | Indicates requested AID is not registered or supported | Returns 6A 82; POS terminal attempts fallback AID or aborts transaction |
| SW1-SW2: CONDITIONS NOT MET | 69 85 |
ISO/IEC 7816-4 | Security conditions not satisfied (e.g. device locked) | Returned when user authentication or biometric verification is incomplete |
How ScreenSync MCP Connects Claude Code to Physical NFC Workflows
ScreenSync MCP connects Claude Code to physical Android NFC workflows through decoupled MediaProjection visual streams and ADB intent execution pipelines. Claude Code dispatches synthetic NDEF intents, triggers simulated APDU exchanges, captures real-time logcat telemetry via get_logcat, and confirms on-screen payment receipts through sub-100ms video frames.
The breakthrough of utilizing ScreenSync MCP for contactless testing lies in its tripartite architecture, which completely bypasses the limitations of emulators and manual lab testing:
| Architectural Plane | Underlying Channel | Latency & Transport | Function During NFC & HCE Testing |
|---|---|---|---|
| Cognitive Agent Plane | Local stdio Process Pipe | Sub-millisecond JSON-RPC | Claude Code parses technical test requirements, generates synthetic NDEF payloads, coordinates multi-step state machines, and asserts UI node attributes |
| Visual Verification Plane | Local Wi-Fi / LAN / USB Reverse Socket | Native MediaProjection (~94 ms median) | Streams live video frames (Android 7.0+, zero root, zero ADB overhead) to verify transaction animations, card brand sheets, and payment receipt dialogs |
| Hardware & OS Control Plane | Physical USB or Wireless Debugging | ADB Daemon Socket | Injects synthetic tag discovery intents (am start -a), dumps package AID routing tables, triggers biometric approvals, and captures low-level logcat buffers |
1. Programmatic Tag Dispatch Simulation via ADB Intent Injection
While physical tags cannot be physically moved by software commands, the Android operating system allows test runners to simulate tag arrivals by broadcasting explicit ACTION_NDEF_DISCOVERED intents containing raw parcelable NDEF byte structures. Claude Code leverages ScreenSync MCP's host execution environment to dispatch high-fidelity NDEF intents directly into the Android framework:
# Simulating an NDEF Tag Tap with a Web URI Payload via ADB
adb shell am start -a android.nfc.action.NDEF_DISCOVERED \
-d "https://www.screensyncmcp.tech/setup.html" \
-t "text/plain" \
-n com.example.screensync.nfc/.NfcTagHandlerActivity
When this intent fires, Android's Window Manager directs focus to your tag handler activity. Claude Code immediately calls get_ui_hierarchy to assert that the activity successfully parsed the URI, extracted parameters, and updated the view hierarchy without throwing intent unmarshalling exceptions.
2. High-Speed Visual Perception via Native MediaProjection
Contactless payment workflows demand immediate visual feedback: POS terminals require visual confirmation within seconds to avoid customer confusion. Traditional ADB screencap commands introduce 1.5 to 3.0 seconds of latency per frame, creating severe lag that disrupts timing-sensitive payment flows.
ScreenSync MCP streams continuous display frames directly from the smartphone using Android's native MediaProjection API. Because screen capture operates without device root and consumes zero ADB bandwidth, it maintains a median latency of approximately 94 milliseconds over a local area network (LAN) or USB reverse socket. When Claude Code executes a contactless transaction, it invokes get_latest_screenshot to confirm that the app displays the green payment checkmark, the masked card number, and the transaction total. For apps implementing biometric-gated payments, review our guide on testing Android biometrics with Claude Code and MCP.
3. The 226-Tool Ecosystem Advantage
ScreenSync MCP exposes 226 MCP tools to developer agents:
- 29 Phone & Desktop Tools: 12 device control tools (
control_tap,control_swipe,control_type,control_key,control_open_url,control_launch_app), 3 desktop automation tools (os_mouse_click,os_type,os_hotkey), and 14 capture and telemetry tools (get_latest_screenshot,get_ui_hierarchy,get_logcat,record_screen,get_device_status). - 197 Browser Tools: The
web_*suite operates through an authenticated Chrome/Edge extension. In omnichannel retail systems where an NFC tap on an Android phone updates an administrative inventory dashboard or merchant payment gateway, Claude Code can simultaneously verify the mobile device's on-screen receipt and inspect the web management portal in a single automated test run. For an exhaustive breakdown of every capability, consult our complete Android MCP tool reference deep dive.
Step-by-Step Setup: Workstation Hub, Physical Device, and Claude Code Registration
Configuring ScreenSync MCP for NFC and HCE testing requires launching the desktop hub on Node.js 18, registering the stdio server in Claude Code, and connecting an authentic Android 7.0+ device via USB or wireless debugging. Establishing reverse port forwarding guarantees continuous visual verification during automated contactless state sweeps.
Follow these five sequential steps to deploy the automated testing environment on Windows, macOS, or Linux:
Step 1: Workstation and Hardware Prerequisites
Ensure your development environment meets the following baseline:
- Host Workstation: Windows 10/11, macOS, or Linux running Node.js 18+ with Android Platform Tools
adbconfigured in your systemPATH. - Physical Android Device: An authentic smartphone running Android 7.0 (API level 24) or higher equipped with hardware NFC support. Ensure NFC is toggled ON under Settings > Connected devices > Connection preferences > NFC.
- Application Build: Debug build of your application with declared NFC intent filters and
HostApduServiceconfigurations installed on the device.
Step 2: Launch the Desktop Hub
Download the ScreenSync MCP desktop hub distribution from screensyncmcp.tech and extract the archive to a permanent directory. Execute the platform launcher:
# On Windows (PowerShell or Command Prompt)
cd C:\tools\screensync-hub
.\start-hub.bat
# On macOS or Linux (Terminal)
cd ~/tools/screensync-hub
chmod +x start-hub.sh
./start-hub.sh
The desktop hub initializes an HTTP ingestion server on port 3000 to process local MediaProjection video frames and prepares a JSON-RPC Model Context Protocol server over stdio. The console output displays your unique authentication token (SCREEN_SYNC_TOKEN). For detailed instructions, review the official ScreenSync MCP setup guide.
Step 3: Register ScreenSync MCP with Claude Code
Register the desktop hub with the Claude Code CLI in your terminal:
claude mcp add screensync node "/path/to/screensync-hub/screensync-hub.js"
If developing within Claude Desktop, update your claude_desktop_config.json file (Settings > Developer > Edit Config):
{
"mcpServers": {
"screensync": {
"command": "node",
"args": ["/path/to/screensync-hub/screensync-hub.js"],
"env": {
"SCREEN_SYNC_TOKEN": "your_authenticated_token_here"
}
}
}
}
(Note: ScreenSync MCP integrates with local stdio MCP clients including Claude Code, Claude Desktop, Cursor, and VS Code agent mode. Cloud-hosted web agents requiring remote HTTPS endpoints, such as ChatGPT's web interface, are not supported).
Step 4: Install the Android App and Authorize Screen Capture
- Download the free ScreenSync MCP mobile application (package
com.screensync.mcp) from Google Play. - Launch the application. Allow local network mDNS discovery to automatically locate the desktop hub on your local Wi-Fi subnet, or scan the pairing QR code displayed in the hub console.
- Tap Start Projection and approve Android's native MediaProjection screen capture consent prompt.
- Unlock Developer Options on your smartphone (Settings > About Phone > tap Build Number 7 times) and enable USB Debugging (or Wireless Debugging). For wireless setups, consult our guide on pairing Android wireless debugging to an MCP server without USB.
- Confirm device connection by executing
adb devicesin your workstation terminal.
Step 5: Establish USB Reverse Socket Forwarding
To ensure uninterrupted visual streaming even when toggling cellular radios, enabling airplane mode, or isolating Wi-Fi subnets during security audits, establish reverse port forwarding:
adb reverse tcp:3000 tcp:3000
With this reverse socket established, the ScreenSync MCP mobile application delivers MediaProjection video frames directly across the physical USB cable to the hub on port 3000, ensuring sub-100ms visual latency even with all device radios disabled.
Practical QA Workflows: Tag Dispatch, HCE APDUs, and Wallet Role Triage
Practical NFC QA workflows evaluate four critical paths: dispatching synthetic NDEF tag intents, verifying Host Card Emulation APDU exchanges, managing default wallet role transitions, and triaging disabled radio states. Claude Code coordinates these multi-step sequences by synthesizing ADB commands, asserting UI hierarchy nodes, and auditing logcat telemetry.
Workflow 1: Validating NDEF Tag Dispatch and Payload Parsing
This workflow asserts that incoming NDEF tags trigger the appropriate activity, parse payload records, and populate on-screen form fields.
Developer Prompt:
"Claude, launch our app com.example.screensync.nfc. First, verify NFC is enabled on the device. Then broadcast a synthetic NDEF_DISCOVERED intent containing a smart poster URI 'https://example.com/promo?id=84920'. Assert via get_ui_hierarchy that PromoDetailActivity opens, displays promo code '84920', and renders the discount banner."
Step 1: Verify Hardware NFC Status via ADB
Claude Code verifies that the device's NFC adapter is powered on:
adb shell dumpsys nfc | grep "mState="
Expected output: mState=on. If disabled, Claude Code prompts to toggle NFC or uses ADB commands to enable it.
Step 2: Inject Synthetic NDEF Intent
Claude Code triggers the component activity with an explicit URI intent:
adb shell am start -a android.nfc.action.NDEF_DISCOVERED \
-d "https://example.com/promo?id=84920" \
-n com.example.screensync.nfc/.ui.PromoDetailActivity
Step 3: Assert UI State via get_ui_hierarchy
Claude Code calls get_ui_hierarchy and validates that the promotion activity parsed the query parameter and rendered the promotion details:
<node package="com.example.screensync.nfc" class="android.widget.FrameLayout">
<node text="Special Promotion Activated!" resource-id="com.example.screensync.nfc:id/text_promo_title" />
<node text="Promo Code: 84920 (20% Off)" resource-id="com.example.screensync.nfc:id/text_promo_code" />
<node text="Claim Discount" resource-id="com.example.screensync.nfc:id/btn_claim" clickable="true" />
</node>
Step 4: Visual Confirmation
Claude Code calls get_latest_screenshot to confirm that the promotional banner graphic and checkout CTA rendered cleanly without text truncation or clipping.
Workflow 2: Verifying Host Card Emulation (HCE) Transaction Processing and APDU Telemetry
This workflow validates that an external contactless reader can select the app's registered Application Identifier, exchange transaction APDUs, and trigger an on-screen payment confirmation.
Developer Prompt:
"Claude, launch our payment app and verify its HCE service registration. Check dumpsys nfc to ensure our AID F0010203040506 is bound to NfcPaymentApduService. Then stream get_logcat with tag NfcPaymentHCE while we simulate a contactless POS poll. Assert that the service returns status 90 00 and that the UI renders the payment receipt."
Step 1: Audit System AID Routing Tables
Claude Code audits the operating system's active card emulation table using ADB:
adb shell dumpsys nfc | grep -A 15 "Registered HCE Services for current user:"
Claude Code confirms that com.example.screensync.nfc/.NfcPaymentApduService is listed with category payment and AID F0010203040506.
Step 2: Stream APDU Telemetry via get_logcat
Claude Code initiates logcat capture filtering for the service tag:
I NfcPaymentHCE: Received APDU: 00A4040007F001020304050600 (Length: 13)
I NfcPaymentHCE: SELECT AID command received for AID: F0010203040506
I NfcPaymentHCE: AID match confirmed. Returning application confirmation payload.
I NfcPaymentHCE: Executing contactless payment token exchange...
I NfcPaymentHCE: HCE Service Deactivated: DEACTIVATION_LINK_LOSS (Device moved away from RF field)
Claude Code parses the logcat output, confirming that the APDU completed within 65 milliseconds—well beneath the 250ms POS terminal disconnect threshold.
Step 3: Assert Visual Payment Receipt
Claude Code calls get_ui_hierarchy to assert that the activity transition completed:
<node text="Payment Successful" resource-id="com.example.screensync.nfc:id/text_receipt_status" />
<node text="$42.50" resource-id="com.example.screensync.nfc:id/text_receipt_amount" />
<node text="Auth Code: TX_SECURE_TOKEN_9847120" resource-id="com.example.screensync.nfc:id/text_auth_code" />
It then calls get_latest_screenshot to confirm that the transaction receipt matches the required visual design specifications.
Workflow 3: Testing Default Contactless Payment App Handover & Android Role Manager
Under Android 10+ and Android 14/15, the operating system manages contactless payment privileges through the RoleManager framework (RoleManager.ROLE_WALLET). If your application is not the default payment app, contactless taps may trigger an OS selection sheet or route to Google Wallet instead.
Developer Prompt:
"Claude, test our app's role transition flow. If the app is not set as the default wallet, assert that tapping 'Set Default Payment App' displays the system RoleManager selection dialog. Use control_tap to select our app in the system dialog, confirm the handover, and assert that the app UI reflects 'Default Payment Service Active'."
Step 1: Detect Active Default Wallet Service
Claude Code queries the system settings provider:
adb shell settings get secure nfc_payment_default_component
If the value does not equal com.example.screensync.nfc/.NfcPaymentApduService, the app must initiate a role request.
Step 2: Trigger Role Manager Request in App
Claude Code triggers the role request button via control_tap. It calls get_ui_hierarchy to detect the system modal window managed by com.google.android.permissioncontroller or com.android.settings:
<node package="com.android.settings" class="android.widget.TextView" text="Default payment app" />
<node text="ScreenSync NFC Wallet" resource-id="android:id/title" clickable="true" />
Step 3: Select App and Assert Handover
Claude Code invokes control_tap on the radio button corresponding to the application under test, followed by control_tap on the confirmation button ("Set as default"). Once the dialog dismisses, Claude Code validates via get_ui_hierarchy that the app displays Default Payment Service Active. For similar system permission flows, see our guide on testing Android runtime permissions with Claude Code and MCP.
| NFC QA Test Scenario | ScreenSync MCP Tools Used | Primary Assertion Mechanism | Critical Defect Caught |
|---|---|---|---|
| NDEF URI Tag Dispatch | get_ui_hierarchy, get_latest_screenshot |
Activity launches; parses query params into UI | App crashes on unexpected URI scheme or malformed TNF header |
| HCE SELECT AID Handling | get_logcat, get_ui_hierarchy |
APDU log reflects matching AID and 90 00 status |
Missing AID filter in apduservice.xml; reader disconnects |
| Transaction Processing Speed | get_logcat |
Logcat timestamp delta between command & response | Main-thread blocking causing APDU latency > 250ms |
| RF Field Deactivation Recovery | get_logcat, get_ui_hierarchy |
onDeactivated(DEACTIVATION_LINK_LOSS) logged |
UI freezes on partial transfer when phone is removed too fast |
| Default Wallet Role Request | get_ui_hierarchy, control_tap |
System RoleManager modal selection confirmed |
App crashes on Android 14+ by invoking deprecated APIs |
| NFC Disabled Prompt Triage | get_ui_hierarchy, control_tap |
System settings redirect dialog rendered | App fails silently when user has NFC disabled in settings |
Common Android NFC/HCE Implementation Pitfalls and Logcat Diagnostics
Common Android NFC and HCE defects include blocking the main looper during APDU processing, unhandled AID conflicts, and failing to manage reader mode polling loops. Claude Code uncovers these issues by parsing real-time logcat buffers and auditing system package dumps directly via ADB.
1. The Main-Thread APDU Processing Bottleneck
Point-of-sale retail terminals maintain an aggressive physical timeout: if an emulated card does not return a response APDU within 250 to 300 milliseconds of command dispatch, the terminal immediately aborts the transaction, emits an error beep, and displays "Card Read Error".
Because Android executes processCommandApdu() on the application's main looper thread, performing database queries, synchronous cryptographic signing, or network calls inside this method will block the main thread and trigger an immediate POS timeout:
// Defective Implementation: Synchronous blocking call causes POS timeout
override fun processCommandApdu(commandApdu: ByteArray, extras: Bundle?): ByteArray {
val result = networkClient.verifyTransaction(commandApdu) // CRASH/TIMEOUT: Blocks main thread!
return result + STATUS_SUCCESS
}
// Resilient Implementation: Immediate status response or asynchronous completion
override fun processCommandApdu(commandApdu: ByteArray, extras: Bundle?): ByteArray {
// Process local cryptographic token immediately (< 50ms)
val fastToken = localKeystoreManager.signQuickToken(commandApdu)
return fastToken + STATUS_SUCCESS
}
Claude Code inspects get_logcat for time deltas between command reception and response delivery:
W NfcService: HostApduService took 312ms to respond to APDU! Reader disconnected.
When Claude Code detects this warning, it flags the bottleneck and refactors the APDU handler to use pre-computed cryptographic tokens or local caching. For optimizing database read speeds during transaction processing, explore our guide on testing Android Room database migrations with Claude Code and MCP.
2. Application Identifier (AID) Collisions in Shared Environments
When multiple applications declare the same Application Identifier (such as general transit or loyalty standards) under category other, the Android operating system cannot determine which service should receive the contactless tap. The OS inflates an interactive disambiguation dialog, requiring the user to manually select an application before the transaction proceeds. If the user does not respond within the reader's RF timeout window, the transaction fails.
Claude Code audits active AID registrations using ADB package dumps:
adb shell dumpsys nfc | grep -A 20 "AID routing table:"
Output:
AID routing table:
[F0010203040506]: Route to HOST (com.example.screensync.nfc)
[A0000000041010]: Route to SECURE_ELEMENT (eSE1)
Claude Code confirms that your app's AIDs are bound directly to HOST routing without unresolved multi-service conflicts. When testing background synchronization tasks that follow contactless transactions, consult our guide on testing Android WorkManager with Claude Code and MCP.
3. Missing NFC Runtime Check and Hardware Absence Crash
Attempting to invoke NFC APIs on devices lacking NFC hardware (or when NFC is toggled off) throws an immediate NullPointerException or leaves the user on a dead-end screen:
// Defective Implementation: Assumes NFC adapter is always present
val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
nfcAdapter.enableReaderMode(...) // CRASH: Throws NPE if nfcAdapter is null!
// Resilient Implementation: Defensive hardware verification
val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
if (nfcAdapter == null) {
showNfcUnsupportedDialog()
} else if (!nfcAdapter.isEnabled) {
showNfcDisabledWarning { startActivity(Intent(Settings.ACTION_NFC_SETTINGS)) }
}
Claude Code validates both paths by inspecting get_ui_hierarchy when NFC is toggled off via ADB, ensuring that the application gracefully directs users to system settings.
Implementation Checklist for Automated Android NFC and HCE Testing
- [ ] Ensure host workstation runs Node.js 18+ with Android Platform Tools
adbin systemPATH. - [ ] Unpack the ScreenSync MCP desktop hub distribution and execute
start-hub.bat(Windows) orstart-hub.sh(macOS/Linux). - [ ] Register ScreenSync MCP with the Claude Code CLI via
claude mcp add screensync node "/path/to/screensync-hub.js". - [ ] Install the ScreenSync MCP client on an authentic physical Android 7.0+ device from Google Play.
- [ ] Pair the device via mDNS or QR code, start projection, and approve the native MediaProjection screen capture consent prompt.
- [ ] Establish USB reverse port forwarding via
adb reverse tcp:3000 tcp:3000to ensure uninterrupted visual verification. - [ ] Declare
HostApduServicewith appropriate<aid-filter>definitions inres/xml/apduservice.xml. - [ ] Implement synthetic NDEF intent injection scripts using
adb shell am start -a android.nfc.action.NDEF_DISCOVERED. - [ ] Stream real-time APDU command telemetry using ScreenSync MCP's
get_logcattool to confirm response latency remains under 250ms. - [ ] Verify on-screen payment receipts, checkout state transitions, and biometric modals using
get_ui_hierarchyandget_latest_screenshot. - [ ] Validate default wallet role handovers on Android 14+ using
RoleManager.ROLE_WALLETsystem dialog assertions. - [ ] Audit logcat buffers for unhandled
DEACTIVATION_LINK_LOSSevents to verify graceful UI recovery upon premature physical tag removal.
Questions, answered
Can Claude Code test Android NFC applications on standard Android Virtual Device emulators?
Android Virtual Device emulators lack physical Near Field Communication controllers and radio frequency hardware abstraction layers. Consequently, emulators cannot simulate contactless APDU exchanges or physical tag induction. Testing NFC tag dispatch and Host Card Emulation requires authentic physical Android hardware connected via ScreenSync MCP and ADB.
What is the difference between Android NFC tag dispatch and Host Card Emulation?
Android NFC tag dispatch operates in Reader mode, scanning external passive smart tags and broadcasting NDEF or tech-specific intents to foreground applications. Host Card Emulation operates in Card Emulation mode, routing external contactless point-of-sale reader commands directly to an Android service implementing the ISO/IEC 7816-4 APDU protocol without a hardware Secure Element.
How does ScreenSync MCP verify contactless checkout screens without slowing down test execution?
ScreenSync MCP streams display frames directly from the physical Android device to the workstation desktop hub using Android's native MediaProjection API. This local pipeline maintains an average latency of approximately 94 milliseconds over USB or Wi-Fi, allowing Claude Code to verify payment receipts without introducing ADB screencap lag.
How can developers simulate an NFC tag tap programmatically without physical smart cards?
Developers simulate contactless tag taps by broadcasting synthetic ACTION_NDEF_DISCOVERED or ACTION_TECH_DISCOVERED intents through ADB shell commands. Claude Code constructs explicit component intents with raw URI or MIME data payloads, allowing the target Android activity to execute intent unmarshalling and view rendering logic deterministically.
Why do contactless POS terminals fail with card read errors during automated HCE testing?
Point-of-sale retail terminals enforce strict radio frequency response timeouts, typically aborting transactions if an emulated card takes longer than 250 milliseconds to return an APDU response. Blocking the Android main looper thread inside processCommandApdu with synchronous database or network operations triggers fatal POS terminal deactivations.
Does ScreenSync MCP require rooting the Android device to test Host Card Emulation?
ScreenSync MCP requires zero device rooting and zero ADB permissions for display capture, operating through Android's standard user-consented MediaProjection API. Device control actions, package inspections, and synthetic intent broadcasts execute through standard Android Debug Bridge daemon sockets over physical USB cables or local wireless debugging.
How does Android handle multiple applications registered to the same Application Identifier?
When multiple installed applications declare identical Application Identifiers in their apduservice.xml files under category other, the Android framework displays an interactive disambiguation dialog. For payment category services, the operating system routes contactless taps strictly to the active default payment application configured via RoleManager.ROLE_WALLET.
How does Claude Code detect when a physical phone is removed prematurely from an NFC reader?
When an Android phone exits an active RF induction field mid-transaction, the operating system triggers the onDeactivated callback with reason code DEACTIVATION_LINK_LOSS. Claude Code monitors logcat telemetry through ScreenSync MCP's get_logcat tool to confirm that the application cleanly aborts the transaction without UI freezing.




