How to Create an NFC App for Android

Svetlana Cherednichenko
7 min readFeb 28, 2019

NFC is a technology mostly used in banking, and often developers create NFC payment apps for business. However, there are countless ways to use it, and you can be really creative with it. No wonder it is gaining popularity among users and developers, as it’s present in most modern mobile devices. In this article I’ll show you how to build an NFC application and be a bit creative with it.

Near Field Communication, a technology that was announced back in 2004. It allows wireless information exchange over short distances — around 10 centimeters (4 inches) or less — with a chip that’s embedded in a device. This technology was derived from RFID and allows users to connect to other devices, make payments, send media and files, and use NFC tags, which probably is the most creative way to use this technology. You can create an NFC scanner app for almost anything.

Though this technology appeared a long time ago, it has found its use primarily in contactless payments. Other than contactless payments, Near field communication isn’t used for much else other than for enabling quick connections to Bluetooth devices. You can use NFC tags and other devices to record any information.

There are some out-of-the-box solutions, as most Android device manufacturers already provide near field communication Android apps. For example, you can put Wi-Fi data into an NFC tag and just scan it instead of typing in a Wi-Fi password.

However, you can be really creative about the functionality and create your custom solution.

For example, I’m a night owl, and sometimes it’s hard for me to wake up in the morning. I just turn off the alarm and go back to sleep. I decided to have some fun with NFC tags to solve my problem. The plan was to create an alarm that doesn’t go off until I scan an NFC tag that’s in the kitchen.

This would inevitably make me wake up and walk to the kitchen. After that, I probably wouldn’t return to my bed.

To do this, I needed to build an alarm app with an NFC tag. Near field communication technology can be used in lots of things, and in this article I want to show you how to work with different types of data you can record on a tag to turn your ideas into reality.

Let me show you how you can create an NFC scanner app step by step.

How to create an NFC app

Now I’ll show you how to record different types of data to your NFC tag in practice by describing how I built my own app. You’ll need Android Studio and an NFC tag.

1. Creating a project

First, I created a project in Android Studio.

2. Creating UI

Then I wrote a simple UI for my application.

I added four types of tags to my application: plain text, phone number, link, and location.

3. Creating the main class

At this point I had to pay attention to the main class of my app.
To begin with, I initialized the NFCManager class I created.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mNfcManager = new NFCManager(this);
}

After that, I checked if NFC was available on my device and allowed the app to receive notifications if a tag is nearby.

@Override
protected void onResume() {
super.onResume();
try {
mNfcManager.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) {
Toast.makeText(this, "NFC not supported", Toast.LENGTH_SHORT).show();
} catch (NFCManager.NFCNotEnabled nfcnEn) {
Toast.makeText(this, "NFC Not enable", Toast.LENGTH_SHORT).show();
}
}

Then I blocked notifications when the app is inactive.

@Override
protected void onPause() {
super.onPause();
mNfcManager.disableDispatch();
}

I installed IntentFilter and defined an onNewIntent method, which will be triggered each time the device finds an NFC tag nearby. When I got near the tag, I recorded my message on it.

@Override
public void onNewIntent(Intent intent) {
mCurrentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (mNfcMessage != null) {
mNfcManager.writeTag(mCurrentTag, mNfcMessage);
mDialog.dismiss();
Toast.makeText(this, "Tag written", Toast.LENGTH_SHORT).show();
}
}

Depending on which RadioButton is chosen, a different message is recorded to the NFC tag.

@OnClick(R.id.btn_write)
public void onWrite() {
String content = mTextContent.getText().toString();
switch (mRadioGroup.getCheckedRadioButtonId()) {
case R.id.radio_text:
mNfcMessage = mNfcManager.createTextMessage(content);
break;
case R.id.radio_uri:
mNfcMessage = mNfcManager.createUriMessage(content, "https://");
break;
case R.id.radio_phone:
mNfcMessage = mNfcManager.createUriMessage(content, "tel:");
break;
case R.id.radio_geo:
mNfcMessage = mNfcManager.createGeoMessage();
break;
}
if (mNfcMessage != null) {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Tag NFC Tag please");
mDialog.show();
}
}

4. Making NFC work

I created a class that’s responsible for working with NFC. I called this class NFCManager and I added all the methods to it that you can see in MainActivity.

4.1. Here’s a method to check if NFC is available on a device.

public void verifyNFC() throws NFCNotSupported, NFCNotEnabled {
nfcAdpt = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdpt == null)
throw new NFCNotSupported();
if (!nfcAdpt.isEnabled())
throw new NFCNotEnabled();
}

4.2. This method unsubscribes from receiving notifications.

public void disableDispatch() {
nfcAdpt.disableForegroundDispatch(activity);
}

4.3. Here’s a method for recording data to an NFC tag. If necessary, you can format the tag first and then record your data to it.

public void writeTag(Tag tag, NdefMessage message) {
if (tag != null) {
try {
Ndef ndefTag = Ndef.get(tag);
if (ndefTag == null) {
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();
}
}
}

4.4. This is a method for creating a message that contains a link or a phone number.

public NdefMessage createUriMessage(String content, String type) {
NdefRecord record = NdefRecord.createUri(type + content);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
return msg;
}

4.5. Here you can see the method for a message that contains plain text.

public NdefMessage createTextMessage(String content) {
try {
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;
}

4.6. This method will allow you to create a message with location coordinates.

public NdefMessage createGeoMessage() {
String geoUri = "geo:" + 48.471066 + "," + 35.038664;
NdefRecord geoUriRecord = NdefRecord.createUri(geoUri);
return new NdefMessage(new NdefRecord[]{geoUriRecord});
}

4.7. At this point, you need to mention non-typical errors in your code that the user will see if NFC isn’t available.

public static class NFCNotSupported extends Exception {
public NFCNotSupported() {
super();
}
}
public static class NFCNotEnabled extends Exception {
public NFCNotEnabled() {
super();
}
}
}

5. Finally, my application is ready!
Now I can launch and test it.

The first thing I do is insert a link and press the Write Tag button.

Then I need to get the device closer to the tag to record the data.

To test how it went, I close the app and bring the device closer to the tag. The link should now open in a browser.

If I record geolocation, I get this screen:

Did everything work for you? If so, congrats! Now you know how to make an NFC app for Android which methods to use in order to create NFC applications for different purposes. Retail, marketing, tracking, or lifestyle applications — NFC scanner app development can help you with any idea you have.

However, if you’re planning to create a payment app, you need to think about encrypting the data transfer between the tag and the device.

If you have any questions on how to develop an NFC reader app, be sure to write to Mobindustry. Also, don’t forget to rate this article — I want to know whether it was useful for you.

Get a Free Consultation!
sales@mobindustry.net

https://www.mobindustry.net/how-to-create-an-nfc-app-for-android/

--

--