Near Field Communication (NFC) is a short-range, high-frequency radio technology that operates at a frequency of 13.56 MHz, with a typical communication range of within 10 centimeters. Host Card Emulation (HCE) provides card emulation that does not depend on a secure element. It allows an application to emulate a card and communicate with an NFC card reader through the NFC service.
An application emulates an NFC card and communicates with an NFC card reader through the NFC service. The device can communicate with an NFC card reader by using a started application (foreground mode) or without starting an application (background mode).
The user starts a specific application to communicate with the NFC card reader. Specifically, the user starts the application, opens the application page, and taps the device on the NFC card reader. In this case, the transaction data is distributed only to the foreground application.
The user taps the device on an NFC card reader without starting any HCE application. Then, the device selects an HCE application based on the application ID (AID) provided by the NFC card reader, and completes the card swiping transaction. If multiple HCE applications are matched, an application selector will be displayed, listing all the available applications for the user to choose.
No matter whether the foreground mode or background mode is used, the NFC service can be implemented only when the device screen is unlocked and illuminated.
For details about the complete API description and sample code of NFC card emulation, see @ohos.nfc.cardEmulation (Standard NFC Card Emulation).
The following table describes the APIs for implementing HCE.
| Name | Description |
|---|---|
| start(elementName: ElementName, aidList: string[]): void | Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list. |
| stop(elementName: ElementName): void | Stops HCE, including canceling the subscription of APDU data, exiting this application from the foreground, and releasing the dynamically registered AID list. |
| on(type: 'hceCmd', callback: AsyncCallback<number[]>): void | Subscription callback, which is used to receive the APDU data sent by the peer card reader. |
| transmit(response: number[]): Promise<void> | Transmits APDU data to the peer card reader. |
Declare the permission required for NFC card emulation and HCE action in the module.json5 file.
Import the cardEmunication module and other related modules.
Check whether the device supports the NFC and HCE capabilities.
Enable the foreground HCE application to preferentially process NFC card swiping.
Exit the HCE foreground mode when the application exits the NFC card swiping page.
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home",
// Add the nfc card emulation action to filter out for this application.
"ohos.nfc.cardemulation.action.HOST_APDU_SERVICE"
]
}
]
}
],
"requestPermissions": [
{
// Add the permission for nfc card emulation.
"name": "ohos.permission.NFC_CARD_EMULATION",
"reason": "$string:app_name",
}
] import { cardEmulation } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { AbilityConstant, UIAbility, Want, bundleManager } from '@kit.AbilityKit';
let hceElementName: bundleManager.ElementName;
let hceService: cardEmulation.HceService;
async function hceCommandCb(error : BusinessError, hceCommand : number[]) {
if (!error) {
if (hceCommand == null || hceCommand == undefined) {
hilog.error(0x0000, 'testTag', 'hceCommandCb has invalid hceCommand.');
return;
}
// check the command, then transmit the response.
hilog.info(0x0000, 'testTag', 'hceCommand = %{public}s', JSON.stringify(hceCommand));
let responseData = [0x90, 0x00]; // change the response depend on different received command.
hceService.transmit(responseData).then(() => {
hilog.info(0x0000, 'testTag', 'hceService transmit Promise success.');
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', 'hceService transmit Promise errCode: ' + err.code + ', errMessage: ' + err.message);
});
} else {
hilog.error(0x0000, 'testTag', 'hceCommandCb errCode: ' + error.code + ', errMessage: ' + error.message);
}
}
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// Check whether the device supports the NFC and HCE capabilities.
if (!canIUse("SystemCapability.Communication.NFC.Core")) {
hilog.error(0x0000, 'testTag', 'nfc unavailable.');
return;
}
if (!cardEmulation.hasHceCapability()) {
hilog.error(0x0000, 'testTag', 'hce unavailable.');
return;
}
hceElementName = {
bundleName: want.bundleName = '',
abilityName: want.abilityName = '',
moduleName: want.moduleName,
}
hceService = new cardEmulation.HceService();
}
onForeground() {
// Ability has brought to foreground
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
if (hceElementName != undefined) {
try {
// Enable the foreground HCE application to preferentially process NFC card swiping.
let aidList = ["A0000000031010", "A0000000031011"]; // change aid tobe correct.
hceService.start(hceElementName, aidList);
// Subscribe to the HCE APDU receiving events.
hceService.on('hceCmd', hceCommandCb);
} catch (error) {
hilog.error(0x0000, 'testTag', 'hceService.start errCode: ' + error.code + ', errMessage: ' + error.message);
}
}
}
onBackground() {
// Ability has back to background
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
// When exiting the NFC tag page, call the tag.off API to exit the foreground dispatch mode.
if (hceElementName != undefined) {
try {
hceService.stop(hceElementName);
} catch (error) {
hilog.error(0x0000, 'testTag', 'hceService.stop errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
}
}
}
} Declare the permission required for NFC card emulation, HCE action, and AIDs for application matching in the module.json5 file.
Import the cardEmunication module and other related modules.
Check whether the device supports the NFC and HCE capabilities.
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home",
// Add the nfc card emulation action to filter out for this application.
"ohos.nfc.cardemulation.action.HOST_APDU_SERVICE"
]
}
],
"metadata": [
{
"name": "payment-aid",
"value": "A0000000031010" // change it tobe correct
},
{
"name": "other-aid",
"value": "A0000000031011" // change it tobe correct
}
]
}
],
"requestPermissions": [
{
// Add the permission for nfc card emulation.
"name": "ohos.permission.NFC_CARD_EMULATION",
"reason": "$string:app_name",
}
] import { cardEmulation } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { AbilityConstant, UIAbility, Want, bundleManager } from '@kit.AbilityKit'
let hceElementName : bundleManager.ElementName;
let hceService: cardEmulation.HceService;
async function hceCommandCb(error : BusinessError, hceCommand : number[]) {
if (!error) {
if (hceCommand == null || hceCommand == undefined) {
hilog.error(0x0000, 'testTag', 'hceCommandCb has invalid hceCommand.');
return;
}
// check the command, then transmit the response.
hilog.info(0x0000, 'testTag', 'hceCommand = %{public}s', JSON.stringify(hceCommand));
let responseData = [0x90, 0x00]; // change the response depend on different received command.
hceService.transmit(responseData).then(() => {
hilog.info(0x0000, 'testTag', 'hceService transmit Promise success.');
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', 'hceService transmit Promise errCode: ' + err.code + ', errMessage: ' + err.message);
});
} else {
hilog.error(0x0000, 'testTag', 'hceCommandCb errCode: ' + error.code + ', errMessage: ' + error.message);
}
}
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// Check whether the device supports the NFC and HCE capabilities.
if (!canIUse("SystemCapability.Communication.NFC.Core")) {
hilog.error(0x0000, 'testTag', 'nfc unavailable.');
return;
}
if (!cardEmulation.hasHceCapability()) {
hilog.error(0x0000, 'testTag', 'hce unavailable.');
return;
}
hceElementName = {
bundleName: want.bundleName = '',
abilityName: want.abilityName = '',
moduleName: want.moduleName,
}
hceService = new cardEmulation.HceService();
hceService.on('hceCmd', hceCommandCb);
}
onForeground() {
// Ability has brought to foreground
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
}
onDestroy() {
// Ability has back to destroy
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
// When exiting the NFC tag page, call the tag.off API to exit the foreground dispatch mode.
if (hceElementName != undefined) {
try {
hceService.stop(hceElementName);
} catch (error) {
hilog.error(0x0000, 'testTag', 'hceService.stop errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
}
}
}
}