Mobile Web Wearable Web

NFC: Managing an NFC Device and Detecting NFC Tags and Peers

This tutorial demonstrates how you can use NFC connectivity to detect NFC tags and exchange data with NFC-enabled devices.

The NFC API is optional for both Tizen mobile and wearable profiles, which means that it may not be supported in all mobile and wearable devices. The NFC API is supported on all Tizen Emulators.

Warm-up

Become familiar with the NFC API basics by learning about:

Task in Mobile Applications

In the Contacts Exchanger task, we will walk through how to exchange contacts between devices over an NFC connection.

Managing NFC Connectivity

Learning how to enable or disable the NFC service is a basic NFC management skill:

Note
The NFC API does not provide methods to directly enable or disable the NFC adapter of the device. When NFC is required, you must request the built-in Settings application to let the user enable or disable the NFC.
  1. To get the default NFC adapter, use the getDefaultAdapter() method and prepare an ApplicationControl object (in mobile and wearable applications) to request the NFC switching operation:

    var nfcSwitchAppControl = new tizen.ApplicationControl("http://tizen.org/appcontrol/operation/setting/nfc", null, null, null,
                                                           [new tizen.ApplicationControlData("type", "nfc")]);
    var adapter = tizen.nfc.getDefaultAdapter();
  2. Define the event listener for the launchAppControl() method:
    function launchSuccess()
    {
       console.log("NFC Settings application has successfully launched.");
    }
    function launchError(error) 
    {
       alert("An error occurred: " + error.name + ". Please enable NFC through the Settings application.");
    }
  3. Define the event handler for an application control, which implements the ApplicationControlDataArrayReplyCallback interface (in mobile and wearable applications):
    var serviceReply =
    {
       /* onsuccess is called when the launched application reports success */
       onsuccess: function(data)
       {
          if (adapter.powered)
          {
             console.log("NFC is successfully turned on.");
          }
       }
       /* onfailure is called when the launched application reports failure of the requested operation */
       onfailure: function() 
       {
          alert("NFC Settings application reported failure.");
       }
    }
  4. If necessary, request launching the NFC Settings with nfcSwitchAppControl as parameter:
    if (adapter.powered)
    {
       console.log("NFC is already enabled");
    }
    else
    {
       console.log("Try to launch the NFC Settings application.");
       tizen.application.launchAppControl(nfcSwitchAppControl, null, launchSuccess, launchError, serviceReply);
    }

Detecting NFC Tags and Peer Devices

Learning how to detect NFC tags and peer devices is a basic NFC management skill:

  1. To get the default NFC adapter, use the getDefaultAdapter() method:

    var nfcAdapter = tizen.nfc.getDefaultAdapter();
  2. Define the event handlers for NFC tag detection using the NFCTagDetectCallback listener interface (in mobile and wearable applications):

    var setTagDetect =
    {
       /* When an NFC tag is detected */
       onattach: function(nfcTag)
       {
          console.log("NFC Tag detected. Its type is: " + nfcTag.type);
       }
    
       /* When an NFC tag becomes unavailable */
       ondetach: function()
       {
          console.log("NFC Tag unavailable");
       }
    }
  3. Register the listener to use the defined event handlers.

    You can limit the listener to detect only specific NFC tag types by defining the tag types as the second parameter of the setTagListener() method. In the following example, only MIFARE tags are detected.

    /* Defines the tag types to be detected */
    var tagFilter = ["MIFARE_MINI", "MIFARE_1K", "MIFARE_4K", "MIFARE_ULTRA", "MIFARE_DESFIRE"];
    
    /* Registers the event listener */
    nfcAdapter.setTagListener(setTagDetect, tagFilter);
  4. To stop the tag detection, use the unsetTagListener() method:

    nfcAdapter.unsetTagListener();

NFC peers are detected similarly as NFC tags, except that the setPeerListener() method is used to register the NFCPeerDetectCallback listener interface (in mobile and wearable applications), and the unsetPeerListener() method is used to stop the peer detection.

Handling NDEF Messages

Learning how to create NDEF messages is a basic NFC management skill:

  1. To create an NDEF URI record, create an NDEFRecordURI interface instance (in mobile and wearable applications) and specify the URI parameter.

    Additionally, you can create instances of the NDEFRecord (in mobile and wearable applications), NDEFRecordText (in mobile and wearable applications), or NDEFRecordMedia (in mobile and wearable applications) interfaces based on the record type to be created.

    var newRecord = new tizen.NDEFRecordURI("https://www.tizen.org/");
  2. Create an NDEFMessage interface instance (in mobile and wearable applications):

    var newMessage = new tizen.NDEFMessage(); 
  3. To add an NDEF record to an NDEF message, use the records attribute of the NDEFMessage interface:

    newMessage.records[0] = newRecord;

Exchanging NDEF Data with Peers

Learning how to exchange NDEF messages is a basic NFC management skill:

  1. To receive NDEF messages from a peer device, use the setReceiveNDEFListener() method of the NFCPeer interface (in mobile and wearable applications).

    The setReceiveNDEFListener() method registers the NDEFMessageReadCallback listener interface (in mobile and wearable applications), which is invoked when an NDEF message from a peer device is read.

    /* NDEFMessageReadCallback listener */
    function readMessage(message)
    {
       console.log("Record Count is " + message.recordCount);
    }
    
    /* Set a listener to receive an NDEF message */
    Peer.setReceiveNDEFListener(readMessage);
  2. To send an NDEF message to an NFC peer, use the sendNDEF() method:

    var newMessage = new tizen.NDEFMessage();
    
    Peer.sendNDEF(newMessage);

Exchanging NDEF Data with Tags

Learning how to exchange NDEF data with tags is a basic NFC management skill:

  1. To read data from an NFC tag, use the readNDEF() method of the NFCTag interface (in mobile and wearable applications).

    The readNDEF() method registers the NDEFMessageReadCallback listener interface (in mobile and wearable applications), which is invoked when an NDEF message is read.

    /* NDEFMessageReadCallback listener */
    function readMessage(message)
    {
       console.log("Record Count is " + message.recordCount);
    }
    
    /* Check whether the NFC tag supports NDEF format */
    if (Tag.isSupportedNDEF)
    {
       /* Read NDEF data */
       Tag.readNDEF(readMessage);
    }
  2. To write data on an NFC tag, use the writeNDEF() method:

    var newMessage = new tizen.NDEFMessage();
    function writeCallback()
    {
       console.log("Success!");
    }
    Tag.writeNDEF(newMessage, writeCallback);

    You can use the transceive() method to transfer raw data as a byte array to an NFC tag without knowing the underlying details of the tag.

Using NFC Card Emulation

Learning how to enable or disable the NFC card emulation and detect Secure Element transactions is a basic NFC management skill:

  1. Declare the required variables and obtain the NFCAdapter object (in mobile and wearable applications) using the getDefaultAdapter() method of the NFCManager interface (in mobile and wearable applications):
    var adapter = tizen.nfc.getDefaultAdapter();
    var modeListenerId = 0, aseListenerId = 0, transListenerId = 0;
    
  2. Use the addCardEmulationModeChangeListener() method of the NFCAdapter interface to register a listener to monitor the current card emulation mode:
    modeListenerId = adapter.addCardEmulationModeChangeListener(function(mode)
    {
       if (mode === "ALWAYS_ON")
       {
          console.log("We are ready to go now");
       }
    });
    
  3. To enable NFC card emulation, change the value of the cardEmulationMode attribute:
    adapter.cardEmulationMode = "ALWAYS_ON";
    
  4. To be notified when the type of an active NFC secure element changes, use the addActiveSecureElementChangeListener() method of the NFCAdapter interface:
    aseListenerId = adapter.addActiveSecureElementChangeListener(function(seType)
    {
       console.log("Active secure element is " + seType);
    });
    
  5. To be notified when a NFC secure element transaction data is exchanged, use the addTransactionEventListener() method of the NFCAdapter interface:
    function onDetected(appletId, data)
    {
       console.log("NFC secure element transaction detected. Application: " + appletId + ". Protocol data: " + data);
    });
    transListenerId = adapter.addTransactionEventListener("UICC", onDetected);
    
  6. Remove the registered listeners when they are no longer necessary and disable NFC card emulation:
    adapter.removeActiveSecureElementChangeListener(aseListenerId);
    adapter.removeTransactionEventListener(transListenerId);
    adapter.removeCardEmulationModeChangeListener(modeListenerId);
    adapter.cardEmulationMode = "OFF";
    

Using NFC Host-based Card Emulation

Learning how to detect NFC HCE (host-based card emulation) events and manage AID (Application ID) is a basic NFC management skill:

  1. Declare the required variables and obtain the NFCAdapter object (in mobile and wearable applications) using the getDefaultAdapter() method of the NFCManager interface (in mobile and wearable applications).

    To enable NFC card emulation, change the value of the cardEmulationMode attribute.

    var hceListenerId = 0;
    var adapter = tizen.nfc.getDefaultAdapter();
    
    adapter.cardEmulationMode = "ALWAYS_ON";
    
  2. Use the addHCEEventListener() method of the NFCAdapter interface to register a listener to detect the HCE event:
    hceListenerId = adapter.addHCEEventListener(function(event_data)
    {
       if (event_data.eventType =="ACTIVATED")
       {
         console.log("HCE activated");
       }
       else if (event_data.eventType =="DEACTIVATED")
       {
         console.log("HCE deactivated");
       }
       else if (event_data.eventType =="APDU_RECEIVED")
       {
         console.log("APDU received");
       }
    });
    
  3. Use the sendHostAPDUResponse() method of the NFCAdapter interface to send a host APDU (Application Protocol Data Unit is defined in the ISO/IEC 7816-4 specification) response to a Contactless Front-end:
    try 
    {
       var successCB = function() 
       {
         console.log("Sending APDU response was successful.");
       };
    
       var errorCB = function() 
       {
         console.log("Sending APDU response failed.");
       };
    
       var apdu_response= [0x00,0xA4,0x04,0x00,0x04,0x11,0x12, 0x13, 0x14];
       adapter.sendHostAPDUResponse(apdu_response, successCB, errorCB);
    } 
    catch (err) 
    {
       console.log(err.name + ":" + err.message);
    }
    
  4. To register an AID for a specific category and secure element type, use the registerAID() method of the NFCAdapter interface:
    try 
    {
       var aid = "ABC0012345";
       adapter.registerAID("HCE", aid, "PAYMENT")
    } 
    catch (err) 
    {
       console.log(err.name + ":" + err.message);
    }
    
  5. To retrieve the registered AIDs for a specific category and secure element type, use the getAIDsForCategory() method of the NFCAdapter interface:
    try 
    {
       var successCallback = function(aid_datas) 
       {
          for (var i = 0 ; i < aid_datas.length ; i++)
          {
             console.log("SE Type is " + aid_datas[i].type);
             console.log("AID is " + aid_datas[i].aid);
             console.log("readonly : " + aid_datas[i].readOnly);
          }
       };
    
       var errorCallback = function(error) 
       {
         console.log("getAIDsForCategory failed.");
       };
    
       adapter.getAIDsForCategory("HCE", "PAYMENT", successCallback, errorCallback);
    } 
    catch (err) 
    {
       console.log(err.name + ":" + err.message);
    }
    
  6. Remove the registered listeners when they are no longer necessary, and disable NFC card emulation:
    adapter.removeHCEEventListener(hceListenerId);
    adapter.cardEmulationMode = "OFF";
    
Go to top