DEV Community

HarmonyOS
HarmonyOS

Posted on

Stage Model - HCE Background & Foreground mode

Read the original article:Stage Model - HCE Background & Foreground mode

Problem Description

How to handle background and foreground modes for NFC transactions on Huawei Watch 5 Stage Model using HarmonyOS.

Background Knowledge

Foreground Mode: Requires user interaction to start an app and process NFC transactions.
Background Mode: Transactions occur without user interaction, relying on pre-configured application AIDs for automatic selection.
HCE (Host Card Emulation): Enables the device to act as an NFC card, supporting both modes.

Constraints

  1. NFC functionality only works when the device screen is unlocked and illuminated.
  2. The ohos.permission.NFC_CARD_EMULATION permission must be declared in module.json5.
  3. Foreground apps must register/deregister AIDs explicitly.

Troubleshooting Process

  1. Foreground Mode:
    • Ensure the app is active and properly registered for NFC.
    • Declare required permissions and HCE actions in module.json5.
    • Validate NFC and HCE capabilities on the device.
  2. Background Mode:
    • Configure AIDs for application matching.
    • Ensure the device selects the correct HCE app without user input.
    • Test transactions without launching the app.

Analysis Conclusion

  • Foreground Mode: Transactions require explicit app activation and listener registration.
  • Background Mode: Relies on pre-configured AIDs and automatic app selection.
  • Key Difference: Foreground mode prioritizes active apps, while background mode operates silently.

Solution

HCE Foreground Mode

  1. Declare permissions for NFC and HCE in module.json5.
  2. Import necessary modules for NFC functionality.
  3. Check device support for NFC and HCE.
  4. Subscribe to APDU data to handle incoming NFC commands.
  5. Send and receive APDU data for transaction processing.
  6. Exit HCE mode when the app is closed or the NFC interaction ends.

Please Click for Foreground Mode Example Code

HCE Background Mode

  1. Declare permissions for NFC, HCE, and AIDs.
  2. Import required modules for NFC operations.
  3. Verify device capabilities for NFC and HCE.
  4. Subscribe to APDU data to receive commands.
  5. Handle APDU data for transactions without user interaction.
  6. Cancel subscriptions when the app exits or the transaction completes.

Please Click for Background mode Example Code

Reference Link

HCE Development

Written by Emine INAN

Top comments (0)