This tip investigates some of the ways in which the Android API may be used to
implement NFC (Near Field Communication)
“Near field communication is a set of standards for smart phones and similar
devices to establish radio communication with each other by touching them
together or bringing them into close proximity,
usually no more than a few centimeters”. NFC and its implementation is evolving in a way that will
bring about a paradigm shift in mobile ecosystem.
NFC implementations may be classified into three
broad categories:
- Reading/writing NFC tags.
- Enabling peer to peer communication.
- Emulating a contactless device
Reading/writing tags:
An NFC Tag is a small microchip. Small amount of information
can be written to it and read from it using any NFC -enabled device, like a mobile
phone. A typical example of this implementation would be to
write a URL to a tag which can then be pasted to some advertising poster. When any
NFC enabled device touches the tag on the poster the URL
will be read and the corresponding link may be opened almost instantaneously. All the
user had to do was to touch the device to the tag on the poster!!
Yet another use could be writing an emergency telephone number to a tag. When
the user touches the tag using an NFC enabled device it will be
read and a call may be initiated at once!
Enabling peer to peer communication:
In this scenario, two NFC enabled devices communicate to
transmit data locally between each other. However, here too it must be noted that the
amount of data that can be transferred is severely limited,
up to one kilo byte only.
A typical example of this category of
implementation can be when
two friends exchange their favorite you tube videos
by simple tapping their phones together!
Emulating a contactless device:The feasibility of
phone based transactions as compared to alternative means has further propelled the
implementation of NFC for payment and ticketing purposes. Here the NFC enabled device is made to
emulate a smart card which uses radio
frequency identification for secure payment.
NDEF
messages:
The NDEF or the NFC Data Exchange Format is a specification that
defines how a message , exchanged between two NFC-enabled devices or an
NFC tag and an NFC enabled device be formatted .
So data is encapsulated in NDEF Message in the form of records.
The Android API has gone a long way in
facilitating these NFC implementation. Let us find out how, through some examples:
For instance you have an NFC tag and you wish to
write some data to it (Say a phone Number) and read it subsequently. The procedure is Simple :
Step1.1. Ensure That the Android Manifest
specifies the following:
Step1.2. Enabling our application so that it filters for NFC intents.
When the NFC tag you want to handle is scanned by the NFC enabled
device , an intent is created that encapsulates the NFC tag. The intent is sent to an
interested application that filters for the Intent.
We use the following “intent-filter”s for our application’s Activity in order
to be able to filter for the intent:
style=”font-size: medium;”>
The above intent must be followed by the following meta-data tag within the
same activity element:
“@xml/nfctechnologies” refers to the XML file that you must create to specify
the NFC technologies that the intended NFC tag supports: We use the following file
four our implementation placed in the /res/xml folder of the project. Please Note that the tech-list created
by you should a subset of the technologies supported by the intended NFC tag. However
the good news is that
you may specify multiple tech lists. And each tech list will be considered independently.
android.nfc.tech.NfcAandroid.nfc.tech.Ndef tech> android.nfc.tech.MifareUltralight
Further we add an additional intent-filter
that will be filtering for any intent carrying an NDEF formatted payload(NDEF message).
Here the mime-type depends on the type of data that you expect to receive as the NDEF Message.
Step1.3: Detecting The NFC intent and making it available for use (like Writing to it):
Add the following to your onCreate:
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(context);
PendingIntent mNfcPendingIntent = PendingIntent.getActivity(context, 0, new Intent
(context,context.getClass()).addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
Add the following code to your onResume:
IntentFilter ndefDetected = new IntentFilter
(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter techDetected = new IntentFilter
(NfcAdapter.ACTION_TECH_DISCOVERED);
writeTagFilters = new IntentFilter[]
{ndefDetected, tagDetected, techDetected};
mNfcAdapter.enableForegroundDispatch(context,
mNfcPendingIntent, writeTagFilters, new
String[][] { new String[] { NfcA.class.getName() },new String[]{Ndef.class.getName()}, new String[]
{MifareUltralight.class.getName()} });
Override the onNewIntent method of the Activity:
@Override
public void onNewIntent(Intent intent) {setIntent(intent);}
This shall call the onResume where you may implement the
code to write to the NFC Tag:
Step1.4: Create A NDEF message to write to the NFC tag:
use the following function to create a NDEF record: the payload can
contain the phone number to write
static NdefRecord createTextRecord(String payload, Locale locale,
boolean encodeInUtf8,String id) {byte[] langBytes = locale.getLanguage().getBytes(Charset.forName(“US-ASCII”));
Charset utfEncoding = encodeInUtf8 ? Charset.forName(“UTF-8”) :
Charset.forName(“UTF-16”);
byte[] textBytes = payload.getBytes(utfEncoding);
byte[] optionalBytes = id.getBytes(utfEncoding);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT,
optionalBytes,textBytes);
return record;
}
finally create the NDEF message from the record as follows:
NdefMessage message = new NdefMessage(new NdefRecord[]
{ NdefWriter.createTextRecord(“0000000000”, Locale.ENGLISH,true, “phNo”)});
Step1.5: Writing to the Tag:
“intent” below is the NFC intent that you will use
to write the tag. And received after the execution of onNewIntent().
“rawMessage” is the message created
in Step4.
Intent intent = getIntent();
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefFormatable format = NdefFormatable.get(tag);
if (format != null){
format.connect();
format.format(rawMessage);
} else {
Ndef ndef = Ndef.get(tag);
if(ndef != null) {
ndef.connect();
ndef.writeNdefMessage(rawMessage);
}
now this application when run and brought close to a tag will write to it.
Step1.6: Reading the tagDetected:
The procedure will remain the same as far as Step3: thereafter in onResume handle
the (Nfc Intent represented by object “intent”) and read it as follows:
Extract all the NDEF messages:
Intent intent = getIntent();
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.
EXTRA_NDEF_MESSAGES);
if (messages != null) {
NdefMessage[] ndefMessages = new NdefMessage[messages.length];
for (int i = 0; i < messages.length; i++) {
ndefMessages[i] = (NdefMessage) messages[i];
}
}
Read the Records: i is the index of the record read
String recordData = (new String(mMessages[0].getRecords()[i].getPayload()));
String recordId = (new String(mMessages[0].getRecords()[i].getId()));
Now this application when run and brought
close to a tag will read from it.