Learn how to develop an Android NFC tag writer to write NFC tags. Using an Android NFC API you can write tag with different content as Text, URL, phone number and so on.
This post describes how to develop an Android NFC tag writer that is capable to write different payload in the NFC Tag as Text, URL, Phone Number and so on using NDEF format. Android smartphones are capable not only to read NFC tags that contains data like URL, phone numbers and so on but using Android NFC API is possible to implement an NFC tag writer. In this post, we will explore how to develop an Android app to write NFC Tags using Android NFC API.
What is NFC technology?
Before digging into the details about how to implement a NFC tag writer in Android, it is useful to describe a bit what is NFC technology.
Near Field Technology (NFC) is a technology that enables short-range communication between two compatible devices that support this technology. NFC requires that one device behaves as a transmitter and another one as a receiver. NFC enabled devices can be grouped in two categories:
- Active
- Passive
How to get started with Android NFCTagManager
The first thing to do, when building an Android NFC writer, is verifying if the NFC is present and if it is active:
[java]@Overrideprotected void onCreate(Bundle savedInstanceState) {
…
nfcMger = new NFCManager(this);
..
}
[/java]
where nfcManager is the class that handles NFC details and implementation using NfcAdapter:
[java]public class NFCManager {private Activity activity;
private NfcAdapter nfcAdpt;
public NFCManager(Activity activity) {
this.activity = activity;
}
public void verifyNFC() throws NFCNotSupported, NFCNotEnabled {
nfcAdpt = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdpt == null)
throw new NFCNotSupported();
if (!nfcAdpt.isEnabled())
throw new NFCNotEnabled();
}
}
[/java]
Just to recall, if you have not read the getting started with Android NFC tutorial, it is necessary to register the android app so that it receives notification when the Android device is near the NFC tag. To enable this notification we have to use NFC foreground dispatch:
[java]@Overrideprotected void onResume() {
super.onResume();
try {
nfcMger.verifyNFC();
Intent nfcIntent = new Intent(this, getClass());
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, nfcIntent, 0);
IntentFilter[] intentFiltersArray = new IntentFilter[] {};
String[][] techList = new String[][] {
{ android.nfc.tech.Ndef.class.getName() },
{ android.nfc.tech.NdefFormatable.class.getName() }
};
NfcAdapter nfcAdpt = NfcAdapter.getDefaultAdapter(this);
nfcAdpt.enableForegroundDispatch(this, pendingIntent,
intentFiltersArray, techList);
}
catch(NFCManager.NFCNotSupported nfcnsup) {
Snackbar.make(v, "NFC not supported", Snackbar.LENGTH_LONG).show();
}
catch(NFCManager.NFCNotEnabled nfcnEn) {
Snackbar.make(v, "NFC Not enabled", Snackbar.LENGTH_LONG).show();
}
}
[/java]
How to develop an Android NFC tag writer
Now the Android NFC writer is ready to handle the NFC tag and when the Android smartphone gets near the NFC tag, the event is notified to the app. The next step is writing the data on the tag. The method is quite simple:
[sociallocker] [java]public void writeTag(Tag tag, NdefMessage message) {if (tag != null) {
try {
Ndef ndefTag = Ndef.get(tag);
if (ndefTag == null) {
// Let’s try to format the Tag in NDEF
NdefFormatable nForm = NdefFormatable.get(tag);
if (nForm != null) {
nForm.connect();
nForm.format(message);
nForm.close();
}
}
else {
ndefTag.connect();
ndefTag.writeNdefMessage(message);
ndefTag.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
[/java] [/sociallocker]
This method accepts an abstract representation of the NFC tag we want to write and the NdefMessage containing the message to write. As the first step, the NFCManager class tries to get the Ndef tag (line 4). If the tag is null, the app tries to “format” the tag and the write the message. If the tag is already formatted, the Android app tries to connect to the tag abstract representation and write the NdefMessage.
How to Write an URL into NFC Tag
Now you know how to build an Android NFC tag writer that write data into NFC tag, it is time to start writing some simple information.
As a first example, the Android NFC app writes an URL:
NdefRecord record = NdefRecord.createUri(type + content);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
return msg;
}
[/java]
The code is very simple, using NdefRecord provided by Android NFC API, the Android app creates a Uri record. As we already know, a NdefMessage is an array of record, so we create a NFC Ndef Message holding only one record: the Uri record.In this case, type holds http value because it is a link.
If we want to write NFC tag that holds a phone number so that when the user taps with the smartphone the tag a phone call is triggered, we have to pass as type tel:.
How to write text data into NFC tag using Android
The last example is writing text data in a NFC tag. In this case following NFC specs the code is very simple:
[java]public NdefMessage createTextMessage(String content) {try {
// Get UTF-8 byte
byte[] lang = Locale.getDefault().getLanguage().getBytes("UTF-8");
byte[] text = content.getBytes("UTF-8"); // Content in UTF-8
int langSize = lang.length;
int textLength = text.length;
ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + langSize + textLength);
payload.write((byte) (langSize & 0x1F));
payload.write(lang, 0, langSize);
payload.write(text, 0, textLength);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0],
payload.toByteArray());
return new NdefMessage(new NdefRecord[]{record});
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
[/java]
Implementing the Android UI for NFC writer App
The last step is implementing the UI so that the Android app handles different NFC record type and a user can insert the data to write. The app uses a spinner that holds the different record types and an EditText that hold the data to write and finally a button (a Floating Action Button) to start the operation. As soon as the user clicks on the button the app starts waiting for the NFC tag. When the user taps on the tag, the app starts writing the data.
At the end of this post, you know how to write NFC tag and the different way to fill the payload. At the end, you have developed an Android NFC writer that enables a user to write an NFC tag. You can use this Android NFC app to write NFC tag with different type of content. When a smartphone gets near the NFC tag, this smartphone will show the content of the NFC tag as an URL or phone number.
Hello Mr azzola
I want to send message to the tag. ID tag read with the command >>getID. In this message I should write one byte in an address and read its from the same address ….
I used to write and read the bytes of the Transcieve , but tag did not known … are there command for writing and reading ….(my tag is MLX90129) it supports Iso15693 (NFCV).I used from commands in NFCV. but it don’t operate.
that’s my command:
to write: 0x21
address: 0x11;
data_MSB=0xAB; // write ABCD
data_LSB=0xCD;
to read: 0x20; // read ABCD in the address 0x11
address: 0x11;
what is command suitable to read and write?
(MLX90129: http://www.datasheetspdf.com/datasheet/MLX90129.html)
thanks
It seems to me you are using RFID instead of NFC am i wrong?
Can we get the full code? I do not understand the bits and pieces. #NotACoder
Just a correction.
Near Field Technology (NFC) => Near Field Communication.
Question
Isn’t it necessary to add sector or block information to write?
how can i insert the data of the tag into the localhost database?
want to protect nfc card write with password will u please help me