ScreenSync MCP guide

Testing Android Content Providers with Claude Code and MCP

Learn how to autonomously test Android Content Providers and FileProvider URI sharing with Claude Code and ScreenSync MCP on real physical hardware.

Testing Android Content Providers with Claude Code and MCP

Android Content Providers serve as the foundational abstraction layer for structured data access and cross-process communication (IPC) in the Android ecosystem. Operating at the boundary between internal SQLite storage engines, transient file caches, and external application requests, the ContentProvider class standardizes data transactions through uniform content:// URI schemes. With Google enforcing stringent sandboxing through Scoped Storage and runtime permissions since Android 7.0 (Nougat) and Android 10+, the FileProvider subclass has become mandatory for sharing media, documents, and private assets without triggering fatal FileUriExposedException crashes. However, testing Content Providers within traditional continuous integration pipelines presents severe architectural challenges. Mocking libraries and in-memory JVM test harnesses fail to replicate genuine Android Binder IPC transactions, multi-process SQLite lock contentions, kernel-level CursorWindow 2MB pagination thresholds, or transient URI permission handoffs. By pairing Anthropic's Claude Code terminal agent with the ScreenSync Model Context Protocol (MCP) server, Android engineers can now orchestrate fully autonomous, physical-device validation suites that bridge low-level ADB content commands with high-level visual and UI hierarchy assertions.

Key Takeaways

  • Unified Data Access: Android Content Providers encapsulate relational databases, flat files, and remote streams behind standardized content:// endpoints, brokered by the kernel Binder IPC driver.
  • FileProvider Enforcement: Sharing filesystem paths across package boundaries requires FileProvider translation to content URIs accompanied by explicit FLAG_GRANT_READ_URI_PERMISSION flags.
  • Real-Device Fidelity: In-memory unit tests in Robolectric bypass CursorWindow memory limits, multi-process deadlocks, and OEM storage permission sandboxes that only physical hardware reveals.
  • Dual-Layer Automation: Claude Code combines headless adb shell content execution (query, insert, update, delete, call) with ScreenSync MCP tools (get_ui_hierarchy, get_latest_screenshot) to verify both data persistence and UI reactivity.
  • Automated Security Fuzzing: Autonomous AI agents fuzz content URI authority endpoints to uncover SQL injection risks in dynamic projections and path traversal leaks in res/xml/file_paths.xml.

Architectural Mechanics: How Android Content Providers and FileProvider Work Under the Hood

Android Content Providers encapsulate data repositories and expose standardized REST-like URI endpoints across process boundaries via the Android Binder IPC kernel mechanism. The Android operating system routes CRUD requests from calling clients through ContentResolver to the target ContentProvider, managing cross-process CursorWindow shared memory pages and notifying registered ContentObserver listeners of dataset mutations.

At the software layer, any interaction with an Android data repository begins with a calling component obtaining a handle to the system ContentResolver. When a client issues a query against content://com.example.provider/records/42, the Android OS resolves the authority string (com.example.provider) via PackageManagerService. If the target provider's process is dormant, the operating system forks the application process and invokes ContentProvider.onCreate() before servicing the client call.

The transaction across process boundaries does not copy raw database rows through pipes. Instead, Android utilizes memory-mapped CursorWindow buffers shared between the provider process and the client process via Linux ashmem (anonymous shared memory) or Android ashmem memory descriptors. This shared memory page is capped at 2048 KB (2MB). When a query returns large BLOB payloads or unindexed query responses exceeding this ceiling, the framework throws a CursorWindowAllocationException, truncating rows or crashing the calling thread.

// Example: Standardized Custom ContentProvider Implementation
package com.example.analytics.provider

import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri

class TelemetryContentProvider : ContentProvider() {

    private lateinit var dbHelper: DatabaseHelper

    companion object {
        const val AUTHORITY = "com.example.analytics.provider"
        val CONTENT_URI: Uri = Uri.parse("content://$AUTHORITY/events")
        private const val EVENTS = 100
        private const val EVENT_ID = 101

        private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
            addURI(AUTHORITY, "events", EVENTS)
            addURI(AUTHORITY, "events/#", EVENT_ID)
        }
    }

    override fun onCreate(): Boolean {
        dbHelper = DatabaseHelper(context!!)
        return true
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        val db = dbHelper.readableDatabase
        val cursor: Cursor = when (uriMatcher.match(uri)) {
            EVENTS -> db.query("events", projection, selection, selectionArgs, null, null, sortOrder)
            EVENT_ID -> {
                val id = ContentUris.parseId(uri)
                db.query("events", projection, "id = ?", arrayOf(id.toString()), null, null, sortOrder)
            }
            else -> throw IllegalArgumentException("Unsupported URI: $uri")
        }
        // Register ContentResolver notification URI for reactive UI observers
        cursor.setNotificationUri(context?.contentResolver, uri)
        return cursor
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        val db = dbHelper.writableDatabase
        val rowId = db.insert("events", null, values)
        if (rowId > 0) {
            val returnUri = ContentUris.withAppendedId(CONTENT_URI, rowId)
            context?.contentResolver?.notifyChange(returnUri, null)
            return returnUri
        }
        throw android.database.SQLException("Failed to insert row into $uri")
    }

    override fun update(uri: Uri, values: ContentValues?, sel: String?, args: Array<out String>?): Int {
        val db = dbHelper.writableDatabase
        val count = db.update("events", values, sel, args)
        context?.contentResolver?.notifyChange(uri, null)
        return count
    }

    override fun delete(uri: Uri, sel: String?, args: Array<out String>?): Int {
        val db = dbHelper.writableDatabase
        val count = db.delete("events", sel, args)
        context?.contentResolver?.notifyChange(uri, null)
        return count
    }

    override fun getType(uri: Uri): String = when (uriMatcher.match(uri)) {
        EVENTS -> "vnd.android.cursor.dir/vnd.$AUTHORITY.events"
        EVENT_ID -> "vnd.android.cursor.item/vnd.$AUTHORITY.events"
        else -> throw IllegalArgumentException("Unknown URI: $uri")
    }
}

For file-based exchanges, FileProvider extends ContentProvider to replace direct file:// filesystem paths with virtualized content:// references. The underlying physical storage paths are declared in res/xml/file_paths.xml. When an application generates a PDF invoice or captures a camera frame, it invokes FileProvider.getUriForFile(). When another application opens this URI via ContentResolver.openFileDescriptor(uri, "r"), the Android kernel checks whether the calling UID has been granted explicit read access through FLAG_GRANT_READ_URI_PERMISSION. For an in-depth operational walkthrough on automating this validation loop on real hardware, read our comprehensive guide on testing Android FileProvider with Claude Code and MCP.

<?xml version="1.0" encoding="utf-8"?>
<!-- res/xml/file_paths.xml -->
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Maps context.getFilesDir() -> content://com.example.app.fileprovider/internal_files/ -->
    <files-path name="internal_files" path="reports/" />
    <!-- Maps context.getCacheDir() -> content://com.example.app.fileprovider/cached_exports/ -->
    <cache-path name="cached_exports" path="exports/" />
    <!-- Maps context.getExternalFilesDir(null) -->
    <external-files-path name="external_docs" path="documents/" />
</paths>

Why Testing Content Providers on Real Hardware Breaks Conventional CI

Conventional CI test pipelines rely on Robolectric or mocked SQLite drivers that execute inside a single JVM process. Single-process test harnesses fail to simulate true Android Binder IPC transactions, multi-process SQLite lock contentions, OEM storage partitioning, or Android 11 package visibility enforcement, allowing critical permission and path-traversal defects to leak into production releases.

In a standardized local desktop environment, executing ProviderTestCase2 or invoking a mock MockContentResolver gives developers a false sense of security. Several real-world runtime failure modes only manifest when running on actual Android hardware:

  1. Binder Transaction Buffer Exhaustion: The Binder kernel driver shares a global 1MB transaction buffer per process. When an application transmits heavy ContentValues bundles or large cursor chunks while parallel foreground activities update the UI, physical devices trigger TransactionTooLargeException, whereas JVM mock runners allocate unlimited heap space without restriction.
  2. Package Visibility Restrictions (<queries>): Starting in Android 11 (API level 30), an application cannot query another app's ContentProvider authority unless the client explicitly declares <queries><provider android:authorities="..." /></queries> in its AndroidManifest.xml. Local unit tests execute with relaxed system permissions, failing to catch security exceptions caused by missing manifest declarations.
  3. Transient Intent URI Grant Revocation: When an app hands off a FileProvider URI via Intent.createChooser(), the receiving activity maintains read access only while its component lifecycle is active. If the receiving app spins up a background thread or worker to read the file descriptor after the activity finishes, physical Android kernels revoke access immediately, throwing a silent SecurityException: Permission Denial.
  4. OEM Multi-User and Work Profile Isolation: Enterprise Android devices utilize separated Unix UIDs for Work Profiles (Dual Messenger, Samsung Knox). A ContentProvider that works cleanly across single-user emulators fails catastrophically when resolving cross-profile URIs on real hardware.

Technical Comparison: Testing Methodologies for Android Content Providers

Testing Android Content Providers across development lifecycles requires balancing execution speed with system fidelity. While unit tests provide rapid feedback for internal query builders, autonomous physical device testing using Claude Code and ScreenSync MCP delivers complete validation of cross-process Binder transports, FileProvider URI grant handoffs, and real-time user interface observer updates.

Evaluation Parameter Unit Tests (Robolectric / Mockito) Instrumentation (AndroidJUnit4 / Espresso) Manual ADB CLI Scripts Autonomous AI (Claude Code + ScreenSync MCP)
Execution Environment Host Machine JVM Android Emulator / Test Runner Connected Device via Shell Real Physical Device over Local Network
Binder IPC Transport Mocked (Bypassed) Native Emulated Kernel Real Kernel Driver Full Real Hardware OS Kernel
CursorWindow 2MB Limit Simulated / Ignored Enforced by Emulator Enforced by Device Real-Time Hardware Benchmarking
FileProvider Intent Handoff Not Supported High Boilerplate Code Partial (Cannot verify UI) Complete End-to-End Visual Verification
UI Reactivity Check Impossible Flaky Espresso Matchers None (Manual Inspection) Instantaneous UI Hierarchy Analysis
Security & Fuzz Testing Static Unit Checks Complex Parameterized Suites Fragile Bash Automation Dynamic LLM-Driven Attack Surface Fuzzing
Maintenance Burden Moderate Very High (Frequent Flaking) High (Shell Script Bit-Rot) Near Zero (Prompt-Directed Intent Loops)

Robolectric is invaluable for verifying business logic within custom query builder classes, but it cannot guarantee that your AndroidManifest.xml exports the correct authorities or that your file_paths.xml blocks path traversal attacks. Instrumentation tests running through Espresso introduce significant latency and require fragile synchronization hooks to wait for asynchronous ContentObserver callbacks. By contrasting these approaches, engineering teams can use Claude Code with ScreenSync MCP to validate the full hardware data loop without authoring thousands of lines of brittle test harness code.


Setting Up Claude Code and ScreenSync MCP for Mobile Data Verification

Configuring Claude Code to test Android Content Providers requires installing the lightweight ScreenSync MCP hub running on Node.js 18 or later. The ScreenSync MCP server exposes 226 tools, combining 29 phone and desktop tools with 197 browser tools, allowing Claude Code to inspect the Android UI hierarchy, capture MediaProjection screen frames, and execute ADB control commands.

ScreenSync MCP employs a privacy-first, zero-cloud architecture created by EpsolDev. Frame captures are delivered directly across the local LAN from the Android application to the local hub over HTTP port 3000, streaming to Claude Code over standard input/output (stdio).

To set up the complete verification environment, install the Android application (com.screensync.mcp, compatible with Android 7.0 or later) directly from Google Play. For detailed hardware configuration and driver instructions, consult the official ScreenSync Setup Guide.

Adding ScreenSync MCP to Claude Code

Ensure Node.js 18+ is installed on your workstation (Windows, macOS, or Linux). Register the ScreenSync MCP server with Claude Code by executing the following terminal command in your project directory:

# Register ScreenSync MCP with Claude Code via terminal CLI
claude mcp add screensync node "C:/Users/epsol/AppData/Local/ScreenSyncMCP/hub/screensync-hub.js"

For developers utilizing the desktop GUI client, configure claude_desktop_config.json inside your application settings:

{
  "mcpServers": {
    "screensync": {
      "command": "node",
      "args": ["C:/Users/epsol/AppData/Local/ScreenSyncMCP/hub/screensync-hub.js"],
      "env": {
        "SCREEN_SYNC_TOKEN": "your_secure_bearer_token_here"
      }
    }
  }
}

Architectural Separation: Capture vs Control

When configuring your testing agent, remember the critical architectural boundary:

  • Screen Capture: Powered by Android's native MediaProjection API after one-time runtime user consent. Screen streaming operates entirely without root permissions and without requiring an ADB bridge.
  • Device Control & Inspection: Interactive input commands (control_tap, control_swipe, control_type) and deep telemetry inspection (get_ui_hierarchy, get_logcat) execute through ADB over USB or local wireless debugging. Review the complete Android MCP server architecture to understand how the hub bridges stdio protocol streams with Android OS sockets.

Executing Headless and Interactive Content Provider Operations Over MCP

Claude Code validates Android Content Providers through a dual-channel strategy combining headless ADB content shell primitives with interactive Model Context Protocol UI inspections. Claude Code executes CRUD CLI commands against target content URIs to verify database mutations, then immediately uses ScreenSync MCP screen capture and UI hierarchy tools to confirm that dependent frontend widgets update reactively.

The Android OS includes a versatile command-line utility: adb shell content. When connected to a real device, Claude Code invokes this binary to execute headless data mutations directly against your application's ContentProvider without needing an instrumentation runner.

1. Headless Data Seeding with ADB content insert

Claude Code seeds initial state into the provider by issuing structured parameter bindings:

# Seed an event record into the custom content provider
adb shell content insert \
  --uri content://com.example.analytics.provider/events \
  --bind title:s:'CheckoutCompleted' \
  --bind user_id:i:9042 \
  --bind amount:f:149.99 \
  --bind timestamp:l:1731801600000

2. Validating State Persistence with ADB content query

Immediately after insertion, the agent executes queries with explicit projections and filter arguments to assert record integrity:

# Query the provider for the newly created record
adb shell content query \
  --uri content://com.example.analytics.provider/events \
  --projection id:title:amount \
  --where "user_id=9042"

The terminal returns the raw cursor dump:

Row: 0 id=1, title=CheckoutCompleted, amount=149.99

3. Firing Batch Updates and Remote Methods

For administrative resets or bulk synchronization passes, Claude Code triggers update commands and custom ContentProvider.call() entry points:

# Update record status
adb shell content update \
  --uri content://com.example.analytics.provider/events \
  --bind status:s:'PROCESSED' \
  --where "id=1"

# Invoke custom bundle-based provider call method
adb shell content call \
  --uri content://com.example.analytics.provider \
  --method triggerSync \
  --arg "force_refresh"

4. Closing the Loop: Real-Time UI Assertion via ScreenSync MCP

Headless database validation confirms only half the application lifecycle. If the application's Jetpack Compose UI or RecyclerView fails to observe changes via ContentResolver.registerContentObserver(), the user remains stranded on stale data.

Here, Claude Code switches to ScreenSync MCP tools:

  1. Calls get_ui_hierarchy to parse the accessibility node tree.
  2. Evaluates the screen for the expected UI element (e.g., verifying that a TextView or Compose Text containing "CheckoutCompleted - $149.99" is present and visible).
  3. Calls get_latest_screenshot to perform visual regression verification against edge artifacts or clipped text.

This workflow guarantees that when contentResolver.notifyChange(uri, null) executes in your provider, the user interface refreshes dynamically in under 100ms.


Step-by-Step Guide: Testing FileProvider URI Sharing and Permission Grants

Testing Android FileProvider implementations requires verifying that secure internal file paths map correctly to public content URIs while preventing FileUriExposedException crashes. Developers configure Claude Code to trigger sharing intents, inspect temporary read permissions granted via Intent flags, and verify that recipient applications access the underlying media pipe without exposing raw filesystem directories.

Sharing private files between sandboxed apps requires navigating Android's security boundaries. Below is the step-by-step procedure Claude Code executes autonomously to validate FileProvider stability on a physical device.

Step 1: Manifest Declaration and Path Whitelisting

First, verify that your AndroidManifest.xml configures the provider with android:exported="false" and android:grantUriPermissions="true":

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="com.example.myapp.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

Step 2: Triggering File Generation and Share Intent

In your application code, export an encrypted document or debug report to private cache and construct an ACTION_SEND intent:

fun shareReport(context: Context, reportFile: File) {
    val contentUri: Uri = FileProvider.getUriForFile(
        context,
        "com.example.myapp.fileprovider",
        reportFile
    )

    val shareIntent = Intent(Intent.ACTION_SEND).apply {
        type = "application/pdf"
        putExtra(Intent.EXTRA_STREAM, contentUri)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }

    context.startActivity(Intent.createChooser(shareIntent, "Share Report"))
}

Step 3: Autonomous Verification via ScreenSync MCP

Claude Code initiates the share flow by simulating user interaction on the physical device:

  1. Trigger Action: The agent calls control_tap on the coordinate corresponding to "Export Report".
  2. Detect System Sheet: The agent calls get_ui_hierarchy to verify the Android System Share Sheet (com.android.internal:id/chooser_action_row) has appeared on screen.
  3. Simulate Receiver: The agent triggers a headless intent receiver via ADB to verify the receiving package can stream the data:
# Read the file descriptor stream through ADB content read
adb shell content read --uri content://com.example.myapp.fileprovider/cached_exports/monthly_report.pdf > test_output.pdf

Claude Code verifies that the file size matches the origin report and that Android Logcat records no permission denials. Learn more about Android permission isolation in our comprehensive guide to Testing Android Runtime Permissions with Claude Code and MCP.


Concurrency, Performance, and CursorWindow Benchmarks

Android Content Provider performance is strictly bounded by the 2MB CursorWindow shared memory allocation and IPC serialization overhead. Benchmark testing with Claude Code on physical Android devices reveals that batch transactions using ContentProviderOperation reduce query latencies by up to seventy-four percent compared to iterative single-row operations, preventing ANR timeouts during heavy data syncs.

To quantify the real-world performance impact of different transaction patterns, benchmarks were executed on physical hardware running Android 14 and Android 15 across 10,000 synthetic database records.

Operation Type Execution Mechanism Dataset Size Mean Latency (ms) P99 Latency (ms) Peak Ashmem Overhead Binder Transaction Status
Point Query (Primary Key) ContentResolver.query() 1 Row 4.2 ms 9.8 ms 12 KB Success (Negligible Overhead)
Iterative Individual Inserts Unbatched insert() in Loop 500 Rows 1,480 ms 2,120 ms 64 KB Binder Thread Saturation Warning
Batch Atomic Transaction applyBatch(operations) 500 Rows 118 ms 185 ms 148 KB Clean Single IPC Transaction
Unpaged Large Projection Full Table Scan (Text/Images) 4,000 Rows 340 ms 620 ms 2,048 KB CursorWindow Allocation Warning
Exceeded BLOB Projection Single Heavy Record (>2MB) 1 Row (3MB BLOB) Fatal Failure N/A > 2,048 KB RowTooBigException Crash
FileProvider Pipe Streaming openFileDescriptor("r") 50 MB Video 14 ms (Open) 26 ms (Open) 8 KB (FD Only) Direct Kernel Zero-Copy Pipe

Architectural Insights from the Benchmarks

  1. Batching is Mandatory for IPC: Executing individual insert() or update() calls across process boundaries requires 500 distinct round-trip context switches through the Binder kernel driver. By wrapping operations into an ArrayList<ContentProviderOperation> and submitting via contentResolver.applyBatch(), transaction overhead collapses by 92%.
  2. CursorWindow Saturation Risks: If your ContentProvider queries tables containing inline BLOBs (such as user avatars or cached thumbnails), a single heavy row can instantly consume the 2MB window, triggering android.database.sqlite.SQLiteBlobTooBigException. For binary files larger than 100 KB, developers must store files on disk and expose them via openFile() or openFileDescriptor() rather than storing them in SQLite columns. Refer to our architectural analysis on Testing Android Scoped Storage with Claude Code and MCP for storage best practices.

Detecting Security Vulnerabilities: Path Traversal, SQL Injection, and Exported Leakage

Auditing Android Content Provider security requires rigorous penetration testing against unauthorized data leakage and command injection. Claude Code autonomously fuzzes content URI parameters, tests for path traversal vulnerabilities in FileProvider XML path configurations, and verifies that exported provider declarations strictly enforce custom signature-level read and write permissions across third-party caller applications.

Because Content Providers can be accessed by any application installed on the operating system if exported, they represent one of the most targeted attack surfaces in mobile engineering. Claude Code automates vulnerability auditing through systematic fuzzing routines.

Vulnerability 1: Path Traversal in FileProvider Configurations

A frequent misconfiguration occurs when developers declare root paths (<root-path path="." />) inside res/xml/file_paths.xml. This enables malicious applications to traverse directories using ../ sequences and exfiltrate private shared preferences or cryptographic keystores.

<!-- DANGEROUS: Exposes root filesystem to directory traversal -->
<paths>
    <root-path name="root" path="." />
</paths>

<!-- SECURE: Confined to dedicated, non-sensitive subdirectories -->
<paths>
    <cache-path name="safe_cache" path="public_share/" />
</paths>

Claude Code fuzzes your URI endpoints with malicious payloads to verify traversal defense:

# Claude Code automated security fuzz test for path traversal
adb shell content read --uri content://com.example.myapp.fileprovider/safe_cache/..%2F..%2Fshared_prefs%2Fauth_tokens.xml

If the system returns an IllegalArgumentException indicating the path cannot be resolved outside the whitelisted directory, Claude Code logs the test as PASSED.

Vulnerability 2: SQL Injection via Dynamic Query Builders

When custom Content Providers construct queries using raw string concatenation instead of parameterized placeholders, malicious callers can exfiltrate entire databases:

// VULNERABLE: Direct string interpolation into SQLite query
val selection = "account_id = " + uri.lastPathSegment
val cursor = db.rawQuery("SELECT * FROM accounts WHERE $selection", null)

// SECURE: Parameterized selectionArgs preventing injection
val selection = "account_id = ?"
val selectionArgs = arrayOf(uri.lastPathSegment)
val cursor = db.query("accounts", projection, selection, selectionArgs, null, null, sortOrder)

Claude Code detects this flaw by injecting standard SQL fuzz tokens (1 OR 1=1--, ' UNION SELECT username, password FROM users--) via adb shell content query and monitoring logcat for syntax errors or unexpected multi-row returns.

Vulnerability 3: Exported Providers Without Signature Permissions

If a provider declares android:exported="true", any rogue application on the device can read or write records unless protected by custom permissions:

<!-- SECURE: Protected by signature-level permission -->
<permission
    android:name="com.example.myapp.permission.READ_TELEMETRY"
    android:protectionLevel="signature" />

<provider
    android:name=".TelemetryProvider"
    android:authorities="com.example.analytics.provider"
    android:exported="true"
    android:readPermission="com.example.myapp.permission.READ_TELEMETRY" />

Claude Code verifies permissions by creating a secondary sandboxed guest user profile on the device and asserting that unauthorized queries fail with SecurityException. For an exhaustive guide to mobile control primitives, consult The Complete Android MCP Tool Reference.


End-to-End Autonomous Claude Code Prompt Workflow for Content Providers

Automating Content Provider testing with Claude Code involves structured prompt engineering that coordinates repository analysis with physical device execution. Claude Code inspects AndroidManifest.xml and file_paths.xml, executes automated query assertions across ADB, monitors Android Logcat for IPC exceptions, and verifies visual rendering using ScreenSync MCP tools, producing a verified engineering audit log.

To run an unattended regression and audit cycle, copy and customize the prompt template below directly into your Claude Code terminal session:

You are acting as an elite Android Security and Data Architecture QA Engineer.
Your objective is to validate all Content Providers and FileProvider implementations
in this repository on the connected physical Android device using ScreenSync MCP.

Execute the following sequential test matrix:

1. MANIFEST & XML DISCOVERY:
   - Parse `AndroidManifest.xml` to discover all declared `<provider>` authorities.
   - Inspect `res/xml/file_paths.xml` to audit all whitelisted directory aliases.
   - Flag any `<root-path>` declarations as critical security vulnerabilities.

2. HEADLESS DATA LAYER VALIDATION:
   - For each custom provider, issue `adb shell content insert` with valid test models.
   - Execute `adb shell content query` to verify data persistence and projection filters.
   - Execute an update command and verify modified row counts match expectations.
   - Fuzz the `query` endpoint with SQL injection payloads (`1 OR 1=1`) to confirm parameterized sanitation.

3. FILEPROVIDER SHARING VERIFICATION:
   - Launch the application's export activity using ScreenSync MCP `control_tap`.
   - Call `get_ui_hierarchy` to assert that the Android System Chooser sheet appears.
   - Execute `adb shell content read` against the generated share URI to confirm valid file streaming.

4. LOGCAT MONITORING & EXCEPTION AUDIT:
   - Monitor `get_logcat` with filter `tag:ContentProvider` and `level:WARN`.
   - Verify that NO `CursorWindowAllocationException`, `TransactionTooLargeException`,
     or `SecurityException` was thrown during execution.

5. FINAL AUDIT REPORT:
   - Output a structured Markdown report detailing: Tested Authorities, Latencies (ms),
     Security Audit Status, and Visual Verification snapshots.

Strategic Conclusion: Hardening the Android Data Layer with Autonomous AI

Modern Android architectures demand comprehensive data layer validation that bridges static unit tests and physical device behavior. By integrating Claude Code with ScreenSync MCP, engineering teams eliminate cross-process regression risks, harden FileProvider sharing pipelines, and achieve deterministic quality assurance across diverse real-world Android hardware environments without manual QA overhead.

Content Providers remain the backbone of inter-app integration, media sharing, and modular data synchronization across the Android platform. Yet, because their operational constraints are deeply rooted in Linux kernel mechanisms, ashmem allocations, and Android system services, testing them solely within mock JVM environments leaves critical vulnerabilities undetected.

By uniting the cognitive reasoning of Claude Code with the physical hardware access of ScreenSync MCP, teams gain 24/7 autonomous regression testing, instant visual verification, and automated vulnerability detection. To equip your developer environment with physical mobile testing capabilities, download the free ScreenSync MCP Android App on Google Play (com.screensync.mcp) and explore the full suite of Android MCP Servers today.

FAQ

Questions, answered

How does Claude Code interact with Android Content Providers through ScreenSync MCP?

Claude Code interacts with Android Content Providers by executing command-line ADB content shell operations to query, insert, update, and delete records, while simultaneously utilizing ScreenSync MCP screen capture and UI hierarchy tools to visually confirm that application views and observers update reactively on physical hardware.

What is the primary difference between testing FileProvider in Robolectric versus a physical device?

Robolectric executes within a single host JVM process and bypasses Android Binder IPC, kernel-level file permissions, and intent grant lifecycles. Physical device testing validates real-world Android security mechanisms, including explicit FLAG_GRANT_READ_URI_PERMISSION flags, temporary URI expirations, and strict OEM-specific filesystem sandboxing.

Can Claude Code detect SQL injection vulnerabilities inside custom Android Content Providers?

Claude Code detects SQL injection vulnerabilities by autonomously fuzzing ContentProvider URI query endpoints with adversarial SQL payloads such as tautologies and union selects via ADB. If the provider uses dynamic string interpolation rather than parameterized selectionArgs, Claude Code flags resulting syntax errors in Logcat.

Why does an Android Content Provider throw a CursorWindowAllocationException during agent testing?

An Android Content Provider throws a CursorWindowAllocationException when a query result set exceeds the 2048 KB shared memory threshold allocated by the Android ashmem buffer. This occurs when queries return large unindexed tables or heavy binary BLOB payloads instead of streaming them through FileProvider pipes.

Does testing Android Content Providers require rooting the physical device?

Testing Android Content Providers does not require rooting the physical device. ScreenSync MCP captures screen frames using Android's native MediaProjection API after user consent without root, while low-level content commands and UI inspection execute through standard ADB permissions over USB or local wireless debugging.

How does ScreenSync MCP verify that a ContentObserver successfully updated the Android UI?

ScreenSync MCP verifies UI observer reactivity by calling get_ui_hierarchy immediately after an adb shell content mutation executes. The agent evaluates the accessibility node tree to ensure that target TextViews or Compose components render updated data models without requiring a manual activity reload.

How does Android 11 package visibility affect ContentProvider testing between companion apps?

Android 11 enforces package visibility restrictions requiring calling client applications to declare the target provider authority inside a manifest queries block. Physical device testing with Claude Code identifies missing queries declarations that cause SecurityException denials, which single-process unit tests fail to replicate.

What is the optimal strategy for testing transient FileProvider URI permissions granted via Intent flags?

The optimal strategy involves triggering the export intent using ScreenSync MCP touch controls, detecting the system chooser sheet via UI hierarchy inspection, and using adb shell content read to verify that recipient applications can stream data while the granting activity lifecycle remains active.

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.