Provides classes that manage the NFC functionality.

The NFC functionality is related to Near Field Communication.

The NFC APIs let applications:

Setting Up NFC

Before an application can use the NFC feature, it needs to check if NFC is supported on the device by getting an instance of the {@link com.trustedlogic.trustednfc.android.NfcManager} class.

	NfcManager mNfcManager = (NfcManager) getSystemService(Context.NFC_SERVICE);
	if (mNfcManager == null) {
		// Device does not support NFC
	}

An application can ensure that NFC is enabled. If not, an application with the needed permission can request that NFC be enabled.

	if (!mNfcManager.isEnabled) {
		// NFC is currently disabled.
		// Enable NFC.
		mNfcManager.enable();
	}

Before using the card emulation mode, an application can ensure that a secure element is selected ({@link com.trustedlogic.trustednfc.android.NfcManager#getSelectedSecureElement}). If not, an application with the needed permission can recover the list of available secure elements on the device ({@link com.trustedlogic.trustednfc.android.NfcManager#getSecureElementList}) and select one ({@link com.trustedlogic.trustednfc.android.NfcManager#selectSecureElement}).

Before using the NFC feature, an application can configure the NFC device by calling {@link com.trustedlogic.trustednfc.android.NfcManager#setProperties}. This function allows:

The setting properties can be customized according to the Device capabilities. The next table give the minimal set of properties supported by the Device. Depending on the implementation, the table may be completed.

Property Name Property Values
discovery.felica true|false
discovery.iso14443A true|false
discovery.iso14443B true|false
discovery.iso15693 true|false
discovery.nfcip true|false
nfcip.baudrate 106|212|424
nfcip.generalbytes
nfcip.mode active|passive|all
nfcip.role initiator|target|both
llcp.lto 150 (0 to 255)
llcp.opt 0 (0 to 3)
llcp.miu 128 (128 to 2176)
llcp.wks 1 (0 to 15)

(default values in bold)

NFC Permissions

To change the NFC service settings such as enabling the NFC targets discovery or activating the secure element, an application must declare the NFC_ADMIN permission.

To perform NFC raw communication with a remote NFC target in Reader/Write Mode or Peer-to-Peer Mode, an application must declare the NFC_RAW permission.

To receive NDEF message or Secure Element intents, an application must declare the NFC_NOTIFY permission.

To receive the LLCP link intent and perform an LLCP communication with a remote NFC target, an application must declare the NFC_LLCP permission.

NFC Usage

The following code samples illustrate the APIs usage regarding the NFC service use cases.

Reader/Writer Mode NDEF message notification

This code sample illustrates the NDEF message notification through an Intent declared in the manifest and a receiver implemented in the application.

Main involved classes/methods:

Manifest Example:

	<receiver android:name=".NfcReaderDemoReceiver">
            <intent-filter>
               <action android:name= "com.trustedlogic.trustednfc.android.action.NDEF_TAG_DISCOVERED"/>
            </intent-filter>
        </receiver>

Receiver Example:

public class NdefMessageReceiverSample extends BroadcastReceiver {
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(NfcManager.NDEF_TAG_DISCOVERERD_ACTION)) {
			NdefMessage msg = intent.getParcelableExtra(NfcManager.NDEF_MESSAGE_EXTRA);
		
		/* Manage the NdefMessage received */
	}

Reader/Writer Mode raw exchange

This code sample illustrates raw exchanges with a NFC target in Reader/Writer mode.

Main involved classes/methods:

public class TagReaderSample {

	/** The NFC manager to access NFC features */
	private NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE);

	private void runTagReader() {
		NfcTag tag = null;
		String type;
		byte[] cmd = { 0x01, 0x02, 0x03 };
		byte[] res;

		while (true) {
			try {
				Log.i("NFC example", "Please wave in front of the tag");
				// Open a connection on next available tag
				try {
					tag = manager.openTagConnection();
				} catch (NfcException e) {
					// TODO: Handle open failure
				}

				// Look for a mifare 4k
				type = tag.getType();
				if (type.equals("Mifare4K")) {
					Log.i("NFC example", "Tag detected");
					tag.connect();
					// Ready to communicate, we can send transceive !
					res = tag.transceive(cmd);
				} else {
					Log.i("NFC example", "Unknown tag");
				}
			} catch (IOException e) {
				// TODO: Handle broken connection
			} finally {
				if (tag != null) {
					tag.close();
				}
			}
		}
	}
}

Peer-to-Peer Mode raw exchange

This code sample illustrates raw exchanges with a NFC target in Peer-to-Peer mode.

Main involved classes/methods:

public class P2pSample {

	/** The NFC manager to access NFC features */
	private NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE);

	private void runP2p() {
		P2pDevice deviceP2p;
		P2pInitiator initiator;
		P2pTarget target;
		byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		byte[] echo = new byte[data.length * 10];

		try {
			deviceP2p = manager.openP2pConnection();

			if (deviceP2p.getMode() == P2pDevice.MODE_P2P_INITIATOR) {
				target = new P2pTarget(deviceP2p);
				// Connect to the detected P2P target
				target.connect();
				// send data to the target
				target.transceive(data);
				// disconnect the connected target
				target.disconnect();
			} else if (deviceP2p.getMode() == P2pDevice.MODE_P2P_TARGET) {
				initiator = new P2pInitiator(deviceP2p);
				//target in receive state 
				echo = initiator.receive();	
				// send back the data received
				initiator.send(echo);
			}
		} catch (IOException e0) {

		} catch (NfcException e1) {

		}
	}
}

Peer-to-Peer Mode LLCP exchange

This code sample illustrates how to get LLCP link state notification with the declaration of a Receiver in the manifest of the application and the implementation of the receiver in the application.

Manifest Example:

	<receiver android:name=".LlcpModeReceiverSample">
            <intent-filter>
		<action android:name= "com.trustedlogic.trustednfc.android.action.LLCP_LINK_STATE_CHANGED"/>
            </intent-filter>
        </receiver>

Receiver Example:

public class LlcpModeReceiverSample extends BroadcastReceiver {
	public void onReceive(Context context, Intent intent) {

		if (intent.getAction().equals(NfcManager.LLCP_LINK_STATE_CHANGED_ACTION)){
			byte[] aid = intent.getByteArrayExtra(NfcManager.LLCP_LINK_STATE_CHANGED_EXTRA);
			/* Create an LLCP service or client and start an LLCP communication */
		} 
	}

This code samples illustrate LLCP exchanges with a NFC Peer.

Main involved classes/methods:

public class LlcpServerSample {

	/** The NFC manager to access NFC features */
	private NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE);

	private void runLlcpClient() {
		LlcpSocket sock;
		byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		byte[] echo = new byte[data.length * 10];
		int length = 0;

		sock = manager.createLlcpSocket((short) 128, (byte) 2, 1024);
		
		// set a timeout in ms for connect request
		sock.setConnectTimeout(10);
		
		try {
			// Connect to remote service
			// NOTE: could be sock.connect("com.trusted-logic.tnfc.testapp");
			sock.connect((byte) 0x10);

			// Send data
			for (int i = 0; i < 10; i++) {
				sock.send(data);
			}

			// Receive echo
			while (length < 10 * data.length) {
				length += sock.receive(echo);
			}

		} catch (IOException e) {
			// TODO: Handle broken connection broken (link down, remote closure
			// or connect rejected) or Timeout expired
		}
	}
}
public class LlcpClientSample {

	/** The NFC manager to access NFC features */
	private NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE);

	private void runLlcpClient() {
		LlcpSocket sock;
		byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		byte[] echo = new byte[data.length * 10];
		int length = 0;

		sock = manager.createLlcpSocket((short) 128, (byte) 2, 1024);
		try {
			// Connect to remote service
			// NOTE: could be sock.connect("com.trusted-logic.tnfc.testapp");
			sock.connect((byte) 0x10);

			// Send data
			for (int i = 0; i < 10; i++) {
				sock.send(data);
			}

			// Receive echo
			while (length < 10 * data.length) {
				length += sock.receive(echo);
			}

		} catch (IOException e) {
			// TODO: Handle broken connection broken (link down, remote closure
			// or connect rejected)
		}
	}
}

Card Emulation Mode transaction notification

This code sample illustrates how to get the card emulation notification with the declaration of a Receiver in the manifest of the application and the implementation of the receiver in the application.

Manifest Example:

	<receiver android:name=".NfcReaderDemoReceiver">
            <intent-filter>
		<action android:name= "com.trustedlogic.trustednfc.android.action.TRANSACTION_DETECTED"/>
            </intent-filter>
        </receiver>

Receiver Example:

public class CardEmulationReceiverSample extends BroadcastReceiver {
	public void onReceive(Context context, Intent intent) {

		if (intent.getAction().equals(NfcManager.TRANSACTION_DETECTED_ACTION)){
			byte[] aid = intent.getByteArrayExtra(NfcManager.AID_EXTRA);
			/* Manage the AID: */
			/* For example start an activity related to this AID value or display a popup with the AID */
		} 
	}

Multiple Applications rules

Several LLCP sockets can be created by a single application or by multiple applications by calling {@link com.trustedlogic.trustednfc.android.NfcManager#createLlcpSocket}, {@link com.trustedlogic.trustednfc.android.NfcManager#createLlcpConnectionlessSocket} or {@link com.trustedlogic.trustednfc.android.NfcManager#createLlcpServiceSocket}, provided the local SAP numbers are differents.

Only one application can open a raw connection by calling {@link com.trustedlogic.trustednfc.android.NfcManager#openTagConnection} or {@link com.trustedlogic.trustednfc.android.NfcManager#openP2pConnection}. While this application has not closed or cancelled its connection, any other application that attempts to open another raw connection will raise an exception. During an open connnection, the card emulation mode is always enabled and applications are able to receive card emulation intents.

When an application opens a tag connection by calling {@link com.trustedlogic.trustednfc.android.NfcManager#openTagConnection}, this operation is exclusive, no NDEF message intent are broadcast while the connection is not closed or canceled.

When an application opens a peer-to-peer connection by calling {@link com.trustedlogic.trustednfc.android.NfcManager#openP2pConnection}, this operation is exclusive, no LLCP intent are broadcast and LLCP sockets are disabled while the connection is not closed or canceled.

NFC Tag types

The {@link com.trustedlogic.trustednfc.android.NfcTag} type returned by {@link com.trustedlogic.trustednfc.android.NfcTag#getType} indicates the set of commands supported by the tag. These commands can be used in {@link com.trustedlogic.trustednfc.android.NfcTag#transceive}.

Tag Type Returned string
Jewel/Topaz Jewel
Mifare UltraLight MifareUL
Mifare Standard 1K Mifare1K
Mifare Standard 4K Mifare4K
Mifare DESFIRE MifareDESFIRE
Felica Felica
ISO14443-4 A or B Iso14443
ISO15693 Iso15693