# Class Nfc

java.lang.Object
com.codename1.nfc.Nfc

public class Nfc extends Object

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 -- `NfcAdapter` foreground dispatch / reader-mode + `HostApduService` for 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. The `NFCReaderUsageDescription` plist 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
  Modifier
  Constructor
  Description
  `protected`
  `Nfc()`
  Ports construct subclasses.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `addTagListener(NfcListener listener)`
  Registers a long-running tag-discovery listener -- useful on Android reader-mode where multiple tags can be tapped in succession.
  `boolean`
  `canHostEmulate()`
  `true` when this device can act as a host-emulated contactless card.
  `boolean`
  `canRead()`
  `true` when NFC is supported AND currently enabled (Android setting toggle on, iOS Core NFC available).
  `boolean`
  `canWrite()`
  `true` when NFC writing is supported on this device.
  `static Nfc`
  `getInstance()`
  Returns the platform-specific singleton owned by the current port.
  `boolean`
  `isSupported()`
  `true` when NFC hardware is present, regardless of whether it is currently enabled.
  `AsyncResource<NdefMessage>`
  `readNdef(NfcReadOptions options)`
  Convenience for `readTag(new NfcReadOptions().setNdefOnly(true))` followed by `Tag.readNdef()`.
  `AsyncResource<Tag>`
  `readTag(NfcReadOptions options)`
  Performs a single tag-read session.
  `void`
  `registerHostCardEmulationService(HostCardEmulationService service)`
  Registers a Host Card Emulation service.
  `void`
  `removeTagListener(NfcListener listener)`
  Removes a listener previously added via `addTagListener(NfcListener)`.
  `boolean`
  `stopRead()`
  Cancels any in-flight `readTag(NfcReadOptions)` / `readNdef(NfcReadOptions)` / `writeNdef(NfcReadOptions, NdefMessage)` call.
  `void`
  `unregisterHostCardEmulationService()`
  Removes a previously registered HCE service.
  `AsyncResource<Boolean>`
  `writeNdef(NfcReadOptions options, NdefMessage message)`
  Convenience writer -- opens a tag-read session, writes the given message and resolves with `true`.

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Constructor Details

  - ### Nfc

    protected Nfc()
    Ports construct subclasses. Application code obtains the active instance via `getInstance()`.

- ## Method Details

  - ### getInstance

    public static Nfc getInstance()
    Returns the platform-specific singleton owned by the current port. On ports that do not implement NFC this returns a base `Nfc` instance whose methods report the device as unsupported; calling code never needs a `null` check or a platform-specific `if`.

  - ### isSupported

    public boolean isSupported()
    `true` when NFC hardware is present, regardless of whether it is currently enabled. Combine with `canRead()` to drive UI affordances. Returns `false` on the fallback base class.

  - ### canRead

    public boolean canRead()
    `true` when NFC is supported AND currently enabled (Android setting toggle on, iOS Core NFC available). Defaults to `false`.

  - ### canWrite

    public boolean canWrite()
    `true` when NFC writing is supported on this device. On Android this mirrors `canRead()`; on iOS, writing requires iOS 13+ and the `NFCReaderUsageDescription` plist entry. Defaults to `false`.

  - ### canHostEmulate

    public boolean canHostEmulate()

    `true` when this device can act as a host-emulated contactless card. Android requires `FEATURE_NFC_HOST_CARD_EMULATION`; iOS 17.4

    - EU only with the HCE entitlement. Defaults to `false`.

  - ### readTag

    public AsyncResource<Tag> readTag(NfcReadOptions options)

    Performs a single tag-read session. Resolves with the discovered `Tag` (call `Tag.readNdef()` or one of the technology accessors) or fails with an `NfcException`. The base class fails immediately with `NfcError.NOT_AVAILABLE`.

    Cancel an in-flight read via `stopRead()`.

  - ### readNdef

    public AsyncResource<NdefMessage> readNdef(NfcReadOptions options)
    Convenience for `readTag(new NfcReadOptions().setNdefOnly(true))` followed by `Tag.readNdef()`. Resolves with the parsed NDEF message, or fails with an `NfcException`.

  - ### writeNdef

    public AsyncResource<Boolean> writeNdef(NfcReadOptions options, NdefMessage message)
    Convenience writer -- opens a tag-read session, writes the given message and resolves with `true`. Fails with `NfcError.READ_ONLY` for locked tags and with `NfcError.CAPACITY_EXCEEDED` when the message is too large.

  - ### stopRead

    public boolean stopRead()

    Cancels any in-flight `readTag(NfcReadOptions)` / `readNdef(NfcReadOptions)` / `writeNdef(NfcReadOptions, NdefMessage)` call. The pending `AsyncResource` completes with `NfcError.USER_CANCELED`.

    ###### Returns

    `true` when a call was cancelled; `false` when no session was pending. Always `false` on the fallback base class.

  - ### addTagListener

    public void addTagListener(NfcListener listener)

    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

    public void removeTagListener(NfcListener listener)
    Removes a listener previously added via `addTagListener(NfcListener)`. No-op on the fallback base class.

  - ### registerHostCardEmulationService

    public void registerHostCardEmulationService(HostCardEmulationService service)

    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.