Skip to content

About

Android NFC Data Transfer between apps as full working app or to be used in application as library with error correction and disconnecting fallbacks

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

NFCDataLink Hero Banner

NFCDataLink

Universal, High-Speed & Large-Scale Android NFC Data Transfer Framework
Transfer payloads of any size—from instant text/JSON messages to multi-gigabyte (1 GB+) binary files—purely over NFC between any two Android devices across all Android versions (minSdk 19 through targetSdk 35+).

Android API Build Status Security FEC Play Store


📱 App Showcase & Interactive Diagnostics

The repository includes both the zero-UI reusable library module (:nfc-datalink) and a production-ready Google Play Store utility application (:app) built with Jetpack Compose (Material 3).

🚀 High-Speed 1 GB Transfer 🛡️ Expectations & Intent Filters 🧪 Virtual Fault-Injection Lab
Active NFC Transfer Screen Receiver Expectation & Filters Screen Virtual NFC Simulation & Diagnostics Screen
Real-time telemetry, 64 KB Extended APDU streaming, AES-256-GCM, and Reed-Solomon in-place byte error repair. Strict filtering: format whitelist, exact byte bounds, max size ceilings, application ID, and intent action validation. On-device link diagnostics: simulate byte noise, burst frame drops, and TagLostException mid-transfer reconnects.

⚡ Why NFCDataLink?

Historically, transferring data over NFC between Android devices relied on Android Beam (P2P / LLCP / SNEP). However:

  1. Android Beam was deprecated in Android 10 (API 29) and completely removed in Android 14 (API 34).
  2. Standard NDEF Tags have hardware limits of only a few kilobytes and lack encryption, flow control, and streaming capabilities.
  3. Applications requiring offline, high-security, physical-tap data exchange had no modern, universal solution.

NFCDataLink solves this permanently across all Android versions (minSdk 19 to targetSdk 35+) by pairing:

  • ISO-DEP Reader Mode (NfcAdapter.enableReaderMode + IsoDep) on the Sender device.
  • Host Card Emulation (HostApduService) on the Receiver device.
  • Dynamic Extended Length APDU Negotiation (up to 64 KB) with seamless step-down to ISO 7816-4 Command Chaining (240-byte fragments) on legacy controllers.
  • Disk-Backed Random-Access Chunk Streaming (RandomAccessFile), allowing a 1 GB+ transfer to execute with a flat, bounded in-memory buffer ($O(1)$ RAM usage) without heap exhaustion (OutOfMemoryError).

🌟 Core Architecture & Technical Highlights

flowchart TD
    subgraph SENDER["Sender Device (ISO-DEP Reader Mode)"]
        A[Payload: Text / JSON / Binary / 1 GB File] --> B[TransferPayload: RandomAccessChunkSource]
        B --> C[Adaptive Compressor: Deflate / GZIP / Auto]
        C --> D[Ephemeral ECDH P-256 + AES-256-GCM Encryptor]
        D --> E[Reed-Solomon GF-256 Parity Encoder + CRC-32C]
        E --> F[ISO 7816-4 APDU Chaining / Extended Length Transmitter]
    end

    subgraph RF["NFC Air Interface (13.56 MHz ISO 14443-4)"]
        F <== "APDU Command Frames (Up to 64 KB MTU)" ==> G
        G <== "Status Words (0x9000, 0x6A80 Retransmit, ACKs)" ==> F
    end

    subgraph RECEIVER["Receiver Device (Host Card Emulation / HCE)"]
        G[HostApduService / ApduCommandProcessor] --> H[ReceiveExpectation & Filter Validator]
        H --> I[Reed-Solomon In-Place Byte Error Repair]
        I --> J[CRC-32C & AES-256-GCM Authenticated Decryptor]
        J --> K[Safe Decompressor with Zip-Bomb Ceiling]
        K --> L[ReceiverSessionStore: RandomAccessFile Assembly + .nfcjournal]
        L --> M[Streaming Full-Payload SHA-256 Verification]
    end
Loading

1. Universal API Compatibility (minSdk 19 to targetSdk 35)

  • Fully supports all Android releases from Android 4.4 KitKat through Android 15.
  • Uses standard ISO-DEP / HCE transport supported natively by all NFC chips (NXP, Broadcom, STMicroelectronics, etc.).

2. Gigabyte-Scale Streaming Without Memory Spikes

  • Incoming and outgoing transfers are streamed in bounded chunks directly through RandomAccessFile.
  • A 1 GB file transfer uses the exact same ~4 MB JVM heap footprint as a 10 KB transfer.

3. 100% Secure by Default

  • Ephemeral Key Agreement: Fresh secp256r1 ECDH key pair per session.
  • HKDF-SHA256: Derives 256-bit AES keys and IV salts, cryptographically binding session IDs, public keys, and optional pre-shared passphrases/PINs to prevent Man-in-the-Middle (MITM) attacks.
  • AES-256-GCM: Every chunk carries a 128-bit authentication tag and deterministic non-repeating 96-bit nonce (sessionSalt xor (chunkIndex || attempt)).
  • Streaming SHA-256: Bit-for-bit full-file cryptographic digest verification before marking any transfer completed.

4. Multi-Layer Error Correction & Resilience

  • Layer 1 (CRC-32C): High-speed hardware-friendly Castagnoli polynomial detection on all frame headers.
  • Layer 2 (Reed-Solomon $\text{GF}(2^8)$ FEC): Cross-block interleaved parity symbols repair up to 16 corrupted bytes per codeword in-place without requiring an NFC round-trip retransmission.
  • Layer 3 (Selective-Repeat ARQ): Corrupted or dropped frames exceeding FEC capacity trigger immediate 0x6A80 retransmission with adaptive chunk step-down.

5. Resumable Sessions & Reconnect Anytime

  • Moving phones apart (TagLostException, IOException, or HostApduService.onDeactivated) never aborts an active transfer.
  • Progress and cryptographic state are checkpointed to a .nfcjournal disk file. Re-tapping phones at any time executes an HMAC-authenticated INS_RESUME_SESSION handshake and resumes from the exact missing chunk index.

🚀 Quick Start: Using :nfc-datalink in Your App

1. Add the Library Dependency

Add :nfc-datalink to your project:

// settings.gradle.kts
include(":nfc-datalink")

// app/build.gradle.kts
dependencies {
    implementation(project(":nfc-datalink"))
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}

2. Declare the Host Card Emulation Service

In your app's AndroidManifest.xml:

<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<uses-feature android:name="android.hardware.nfc.hce" android:required="true" />

<application ...>
    <service
        android:name="de.hartz.software.nfcdatalink.core.NfcDataLinkApduService"
        android:exported="true"
        android:permission="android.permission.BIND_NFC_SERVICE">
        <intent-filter>
            <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <meta-data
            android:name="android.nfc.cardemulation.host_apdu_service"
            android:resource="@xml/apdu_service_config" />
    </service>
</application>

Add res/xml/apdu_service_config.xml:

<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/aid_description"
    android:requireDeviceUnlock="false">
    <aid-group
        android:category="other"
        android:description="@string/aid_description">
        <aid-filter android:name="F0010203040506" />
        <aid-filter android:name="F0394148148100" />
    </aid-group>
</host-apdu-service>

3. Initialize NfcDataLink & Observe State

import de.hartz.software.nfcdatalink.core.NfcDataLink
import de.hartz.software.nfcdatalink.core.model.*

val nfcDataLink = NfcDataLink(
    storageDirectory = File(context.filesDir, "nfc_transfers"),
    config = TransferConfig(
        applicationId = context.packageName,
        compressionMode = CompressionMode.AUTO,
        fecLevel = FecLevel.MEDIUM,
        securityConfig = SecurityConfig(
            encryptionEnabled = true,
            sharedPassphrase = "optional-pairing-pin"
        )
    )
)

// Collect state updates via Kotlin StateFlow:
lifecycleScope.launch {
    nfcDataLink.state.collect { state ->
        when (state) {
            is TransferState.WaitingForPeer -> {
                Log.d("NFC", "Waiting for another NFC device to touch...")
            }
            is TransferState.Transferring -> {
                Log.d("NFC", "Progress: ${state.telemetry.progressPercent}% at ${state.telemetry.throughputBytesPerSec} B/s")
            }
            is TransferState.PausedWaitingReconnect -> {
                Log.w("NFC", "Phones separated at ${state.telemetry.progressPercent}% — touch devices again to resume!")
            }
            is TransferState.Completed -> {
                val result = state.result
                Log.i("NFC", "Transfer Verified! Saved to: ${result.payloadFile.absolutePath}")
            }
            is TransferState.RejectedByFilter -> {
                Log.e("NFC", "Transfer rejected (${state.reason}): ${state.message}")
            }
            is TransferState.Failed -> {
                Log.e("NFC", "Transfer failed: ${state.error.message}")
            }
            else -> Unit
        }
    }
}

4. Sending Payloads of Any Size

Option A: Plain Text or JSON

// Send plain text with an optional intent route:
nfcDataLink.prepareSendText(
    text = "Encrypted NFC message",
    intentAction = "com.example.myapp.ACTION_CHAT_MESSAGE"
)

// Or send structured UTF-8 JSON:
nfcDataLink.prepareSendJson(
    json = """{"userId": 1042, "role": "admin"}""",
    intentAction = "com.example.myapp.ACTION_SYNC_USER"
)

Option B: Multi-Gigabyte (1 GB+) Disk File

// Streams directly from disk via RandomAccessFile with O(1) RAM usage:
val largeVideo = File("/sdcard/Movies/4k_recording_1gb.mp4")
nfcDataLink.prepareSendFile(
    file = largeVideo,
    mimeType = "video/mp4",
    intentAction = "com.example.myapp.ACTION_IMPORT_VIDEO"
)

Option C: Arbitrary Binary Stream

val contentStream = contentResolver.openInputStream(contentUri)!!
nfcDataLink.prepareSendStream(
    inputStream = contentStream,
    fileName = "document.pdf",
    mimeType = "application/pdf"
)

Activate Reader Mode in your Activity's onResume():

override fun onResume() {
    super.onResume()
    nfcDataLink.syncActivityNfcMode(this)
}

override fun onPause() {
    super.onPause()
    nfcDataLink.onActivityPaused(this)
}

5. Receiving Payloads with Exact Expectations & Filters

Receivers enforce strict contracts before accepting any data bytes:

val expectation = ReceiveExpectation(
    // 1. Data format filter:
    allowedFormats = setOf(DataFormat.FILE, DataFormat.BINARY),
    // 2. MIME type wildcard filter:
    allowedMimeTypes = setOf("video/*", "application/octet-stream"),
    // 3. Sender package whitelist:
    allowedApplicationIds = setOf("com.example.authorized_sender"),
    // 4. Intent action filter:
    requiredIntentAction = "com.example.myapp.ACTION_IMPORT_VIDEO",
    // 5. Size boundaries:
    minExpectedBytes = 1024L,
    maxExpectedBytes = 2L * 1024L * 1024L * 1024L, // Up to 2 GiB accepted
    expectedExactBytes = null // Or specify exact size if known in advance
)

nfcDataLink.prepareReceive(expectation)
nfcDataLink.syncActivityNfcMode(this)

☕ Java Interoperability Example

NFCDataLink is 100% interoperable with Java:

import de.hartz.software.nfcdatalink.core.NfcDataLink;
import de.hartz.software.nfcdatalink.core.model.DataFormat;
import de.hartz.software.nfcdatalink.core.model.ReceiveExpectation;
import de.hartz.software.nfcdatalink.core.model.TransferState;

// Initialize:
NfcDataLink dataLink = new NfcDataLink(new File(getFilesDir(), "nfc_transfers"));

// Register listener:
dataLink.addStateListener(state -> {
    if (state instanceof TransferState.Transferring) {
        TransferState.Transferring transferring = (TransferState.Transferring) state;
        System.out.println("Progress: " + transferring.getTelemetry().getProgressPercent() + "%");
    } else if (state instanceof TransferState.Completed) {
        TransferState.Completed completed = (TransferState.Completed) state;
        System.out.println("Received file: " + completed.getResult().getPayloadFile());
    }
});

// Send file:
dataLink.prepareSendFile(new File("/sdcard/data.bin"));

🧪 Virtual NFC Simulator & Edge-Case Testing

Because physical testing requires holding two devices together, :nfc-datalink provides a deterministic in-memory VirtualApduLink with configurable fault injection:

val simulatedFaults = LinkFaultConfig(
    corruptBytesPerFrame = 6,          // Corrupts 6 bytes per frame -> verifies Reed-Solomon in-place repair
    unrecoverableBurstEveryNthFrame = 8, // Wipes out frame -> verifies CRC-32C + Selective ARQ retransmit
    disconnectAtFrameCounts = setOf(5, 12) // Drops link twice -> verifies TagLostException session resume
)

val report = nfcDataLink.runSimulatedTransfer(
    payload = TransferPayload.fromFile(File("1gb_file.bin")),
    expectation = ReceiveExpectation.forBinaryOrFile(),
    faultConfig = simulatedFaults
)

println("Simulated ${report.totalApduFramesExchanged} APDUs in ${report.elapsedMs} ms")

🛠️ Verification & Build Commands

Run the full verification pipeline via Gradle wrapper:

# Run all unit & protocol simulation tests:
.\gradlew.bat test

# Run library unit tests only:
.\gradlew.bat :nfc-datalink:testDebugUnitTest

# Run Android Lint across all modules:
.\gradlew.bat lintDebug

# Build Library AAR & App Release APK (with full R8 minification):
.\gradlew.bat :nfc-datalink:assembleRelease :app:assembleRelease

# Build Google Play Store Android App Bundle (.aab):
.\gradlew.bat :app:bundleRelease

# Run the complete automated verification skill:
powershell -ExecutionPolicy Bypass -File .agents\skills\verify-workspace\scripts\verify.ps1

🚀 CI/CD & Google Play Store Deployment

The repository includes a production-grade GitHub Actions CI/CD pipeline located in .github/workflows/:

1. Continuous Integration (ci.yml)

  • Trigger: Every push or pull request to main, and manual dispatch.
  • Jobs:
    • Runs the full unit & protocol simulation test suite (./gradlew test).
    • Runs Android Lint analysis (./gradlew lintDebug).
    • Builds all production artifacts: Library AAR, Debug APK, R8 Minified Release APK, and Google Play Store App Bundle (app-release.aab).
    • Uploads test results, lint reports, and build binaries as downloadable GitHub Actions artifacts.

2. Automated Release Pipeline (release.yml)

  • Trigger: Pushing a version tag (e.g. git tag v2.0.0 && git push origin v2.0.0) or manual trigger via the GitHub Actions Run workflow button.
  • Features:
    • Automatically decodes and signs artifacts using production keystore secrets when configured.
    • Automatically generates SHA256SUMS.txt integrity digests.
    • Creates a GitHub Release with changelog notes and attaches the release assets:
      • 📦 app-release.aab (Google Play Store App Bundle)
      • 📱 app-release.apk (Signed Release APK for sideloading)
      • 📚 nfc-datalink-release.aar (Reusable Library AAR)
      • 🔒 SHA256SUMS.txt (Cryptographic verification checksums)

3. Google Play Store Signing Secrets (Optional)

To sign release builds with your custom production upload keystore in GitHub Actions, configure the following secrets in your GitHub repository (Settings > Secrets and variables > Actions):

Secret Name Description
KEYSTORE_BASE64 Base64-encoded release .jks or .keystore file (base64 -w 0 my-release-key.jks)
KEYSTORE_PASSWORD Password of the release keystore
KEY_ALIAS Alias name of the signing key
KEY_PASSWORD Password of the signing key

Note: If these secrets are not configured, the pipeline automatically falls back to debug signing so that CI builds, pull request checks, and developer forks always build and pass cleanly without setup friction.


📚 Deep Dive Documentation


📄 License

This project is licensed under the Apache 2.0 License.

About

Android NFC Data Transfer between apps as full working app or to be used in application as library with error correction and disconnecting fallbacks

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages