Class Nfc
Entry point for the Codename One NFC API -- read and write NDEF
messages, exchange APDUs with smart cards, and host-emulate as a
contactless card. Obtain the platform implementation via
getInstance(); the returned subclass is owned by the active port.
Quick start: Read an NDEF URI
Nfc nfc = Nfc.getInstance();
if (!nfc.canRead()) {
// device has no NFC or it is disabled
return;
}
nfc.readTag(new NfcReadOptions()
.setNdefOnly(true)
.setAlertMessage("Hold near the poster"))
.onResult((tag, err) -> {
if (err != null) {
return;
}
tag.readNdef().onResult((msg, e) -> {
if (e == null) {
String url = msg.getFirstRecord().getUriPayload();
// launch / display url
}
});
});
Quick start: Send an APDU to a smart card
nfc.readTag(new NfcReadOptions()
.setTechFilter(TagType.ISO_DEP)
.setIsoSelectAids(myAid))
.onResult((tag, err) -> {
if (err != null) return;
IsoDep iso = tag.getIsoDep();
if (iso == null) return;
iso.transceive(myCommandApdu).onResult((resp, e) -> {
if (ApduResponse.isSuccess(resp)) { ... }
});
});
Quick start: Host card emulation
class MyService extends HostCardEmulationService {
public String[] getAids() { return new String[] { "F0010203040506" }; }
public byte[] processCommand(byte[] apdu) {
return ApduResponse.withStatus(new byte[] { 'O', 'K' },
ApduResponse.swSuccess());
}
}
Nfc.getInstance().registerHostCardEmulationService(new MyService());
Platform support
- Android --
NfcAdapterforeground dispatch / reader-mode +HostApduServicefor HCE. Both manifest entries are auto-injected by the Maven plugin and the build daemon when this class is referenced. - iOS --
Core NFC(NFCNDEFReaderSession,NFCTagReaderSession) for reading;CardSession(iOS 17.4+, EU only) for HCE. TheNFCReaderUsageDescriptionplist entry and the relevant entitlements are auto-injected by IPhoneBuilder. - JavaSE simulator -- the Simulate -> NFC menu lets you tap a
virtual tag, edit its NDEF payload, and fire APDUs at any registered
HostCardEmulationService. - All other platforms (desktop deploy, JavaScript, ...) -- this
base class is returned as-is and reports the device as unsupported;
every operation completes with
NfcError.NOT_AVAILABLE.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddTagListener(NfcListener listener) Registers a long-running tag-discovery listener -- useful on Android reader-mode where multiple tags can be tapped in succession.booleantruewhen this device can act as a host-emulated contactless card.booleancanRead()truewhen NFC is supported AND currently enabled (Android setting toggle on, iOS Core NFC available).booleancanWrite()truewhen NFC writing is supported on this device.static NfcReturns the platform-specific singleton owned by the current port.booleantruewhen NFC hardware is present, regardless of whether it is currently enabled.readNdef(NfcReadOptions options) Convenience forreadTag(new NfcReadOptions().setNdefOnly(true))followed byTag.readNdef().readTag(NfcReadOptions options) Performs a single tag-read session.voidRegisters a Host Card Emulation service.voidremoveTagListener(NfcListener listener) Removes a listener previously added viaaddTagListener(NfcListener).booleanstopRead()Cancels any in-flightreadTag(NfcReadOptions)/readNdef(NfcReadOptions)/writeNdef(NfcReadOptions, NdefMessage)call.voidRemoves a previously registered HCE service.writeNdef(NfcReadOptions options, NdefMessage message) Convenience writer -- opens a tag-read session, writes the given message and resolves withtrue.
-
Constructor Details
-
Nfc
protected Nfc()Ports construct subclasses. Application code obtains the active instance viagetInstance().
-
-
Method Details
-
getInstance
-
isSupported
public boolean isSupported()truewhen NFC hardware is present, regardless of whether it is currently enabled. Combine withcanRead()to drive UI affordances. Returnsfalseon the fallback base class. -
canRead
public boolean canRead()truewhen NFC is supported AND currently enabled (Android setting toggle on, iOS Core NFC available). Defaults tofalse. -
canWrite
public boolean canWrite()truewhen NFC writing is supported on this device. On Android this mirrorscanRead(); on iOS, writing requires iOS 13+ and theNFCReaderUsageDescriptionplist entry. Defaults tofalse. -
canHostEmulate
public boolean canHostEmulate()truewhen this device can act as a host-emulated contactless card. Android requiresFEATURE_NFC_HOST_CARD_EMULATION; iOS 17.4- EU only with the HCE entitlement. Defaults to
false.
- EU only with the HCE entitlement. Defaults to
-
readTag
Performs a single tag-read session. Resolves with the discovered
Tag(callTag.readNdef()or one of the technology accessors) or fails with anNfcException. The base class fails immediately withNfcError.NOT_AVAILABLE.Cancel an in-flight read via
stopRead(). -
readNdef
Convenience forreadTag(new NfcReadOptions().setNdefOnly(true))followed byTag.readNdef(). Resolves with the parsed NDEF message, or fails with anNfcException. -
writeNdef
Convenience writer -- opens a tag-read session, writes the given message and resolves withtrue. Fails withNfcError.READ_ONLYfor locked tags and withNfcError.CAPACITY_EXCEEDEDwhen the message is too large. -
stopRead
public boolean stopRead()Cancels any in-flight
readTag(NfcReadOptions)/readNdef(NfcReadOptions)/writeNdef(NfcReadOptions, NdefMessage)call. The pendingAsyncResourcecompletes withNfcError.USER_CANCELED.Returns
truewhen a call was cancelled;falsewhen no session was pending. Alwaysfalseon the fallback base class. -
addTagListener
Registers a long-running tag-discovery listener -- useful on Android reader-mode where multiple tags can be tapped in succession. Each new tag calls
NfcListener.tagDiscovered(Tag)from the EDT.Ports that do not support multi-shot reading fall back to a single-shot
readTag(NfcReadOptions)each time -- iOS for example dismisses the system sheet after the first tag and re-prompts.No-op on the fallback base class.
-
removeTagListener
Removes a listener previously added viaaddTagListener(NfcListener). No-op on the fallback base class. -
registerHostCardEmulationService
Registers a Host Card Emulation service. Only one service may be registered per app, and only the AIDs reported by
HostCardEmulationService.getAids()are routed to it.On Android the platform routing tables are populated from the service's manifest entry; the Codename One Maven plugin and BuildDaemon auto-generate that entry from the AIDs at build time. At runtime this method simply hands the live instance to the port so APDUs can be dispatched.
No-op on the fallback base class.
-
unregisterHostCardEmulationService
public void unregisterHostCardEmulationService()Removes a previously registered HCE service. No-op on the fallback base class.
-