Android read nfc tags

Reading NFC Tags With Android

Are you curious about what NFC is and how it can be integrated into your own Android applications? This tutorial will quickly introduce you to the topic before diving in and teaching you how to build a simple NFC reader app!

What is NFC?

NFC is the abbreviation for Near Field Communication. It is the international standard for contactless exchange of data. In contrast to a large range of other technologies, such as wireless LAN and Bluetooth, the maximum distance of two devices is 10cm. The development of the standard started in 2002 by NXP Semiconductors and Sony. The NFC Forum, a consortium of over 170 companies and members, which included Mastercard, NXP, Nokia, Samsung, Intel, and Google, has been designing new specifications since 2004.

There are various possibilities for NFC use with mobile devices; for example, paperless tickets, access controls, cashless payments, and car keys. With the help of NFC tags you can control your phone and change settings. Data can be exchanged simply by holding two devices next to each other.

In this tutorial I want to explain how to implement NFC with the Android SDK, which pitfalls exist, and what to keep in mind. We will create an app step by step, which can read the content of NFC tags supporting NDEF.

NFC Technologies

There are a variety of NFC tags that can be read with a smartphone. The spectrum ranges from simple stickers and key rings to complex cards with integrated cryptographic hardware. Tags also differ in their chip technology. The most important is NDEF, which is supported by most tags. In addidition, Mifare should be mentioned as it is the most used contactless chip technology worldwide. Some tags can be read and written, while others are read-only or encrypted.

Only the NFC Data Exchange Format (NDEF) is discussed in this tutorial.

Adding NFC Support in an App

We start with a new project and a blank activity. It is important to select a minimum SDK version of level 10, because NFC is only supported after Android 2.3.3. Remember to choose your own package name. I’ve chosen net.vrallev.android.nfc.demo, because vrallev.net is the domain of my website and the other part refers to the topic of this application.

The default layout generated by Eclipse is almost sufficient for us. I’ve only added an ID to the TextView and changed the text.

To get access to the NFC hardware, you have to apply for permission in the manifest. If the app won’t work without NFC, you can specify the condition with the uses-feature tag. If NFC is required, the app can’t be installed on devices without it and Google Play will only display your app to users who own a NFC device.

The MainActivity should only consist of the onCreate() method. You can interact with the hardware via the NfcAdapter class. It is important to find out whether the NfcAdapter is null. In this case, the Android device does not support NFC.

If we start our app now, we can see the text whether NFC is enabled or disabled.

How to Filter for NFC Tags

We have our sample app and want to receive a notification from the system when we attach an NFC tag to the device. As usual, Android uses its Intent system to deliver tags to the apps. If multiple apps can handle the Intent, the activity chooser gets displayed and the user can decide which app will be opened. Opening URLs or sharing information is handled the same way.

Читайте также:  Как айфон уступил андроиду

NFC Intent Filter

There are three different filters for tags:

  1. ACTION_NDEF_DISCOVERED
  2. ACTION_TECH_DISCOVERED
  3. ACTION_TAG_DISCOVERED

The list is sorted from the highest to the lowest priority.

Now what happens when a tag is attached to the smartphone? If the system detects a tag with NDEF support, an Intent is triggered. An ACTION_TECH_DISCOVERED Intent is triggered if no Activity from any app is registered for the NDEF Intent or if the tag does not support NDEF. If again no app is found for the Intent or the chip technology could not be detected, then a ACTION_TAG_DISCOVERED Intent is fired. The following graphic shows the process:

In summary this means that each app needs to filter after the Intent with the highest priority. In our case, this is the NDEF Intent. We implement the ACTION_TECH_DISCOVERED Intent first to highlight the difference between priorities.

Tech Discovered Intent

We must specify the technology we are interested in. For this purpose, we create a subfolder called xml in the res folder. In this folder we create the file nfc_tech_filter.xml, in which we specify the technologies.

Now we must create an IntentFilter in the manifest, and the app will be started when we attach a tag.

If no other app is registered for this Intent, our Activity will start immediately. On my device, however, other apps are installed, so the activity chooser gets displayed.

NDEF Discovered Intent

As I mentioned before, the Tech Discovered Intent has the second highest priority. However, since our app will support only NDEF, we can use the NDEF Discovered Intent instead, which has a higher priority. We can delete the technology list again and replace the IntentFilter with the following one.

When we attach the tag now, the app will be started like before. There is a difference for me, however. The activity chooser does not appear and the app starts immediately, because the NDEF Intent has a higher priority and the other apps only registered for the lower priorities. That’s exactly what we want.

Foreground Dispatch

Note that one problem remains. When our app is already opened and we attach the tag again, the app is opened a second time instead of delivering the tag directly. This is not our intended behavior. You can bypass the problem by using a Foreground Dispatch.

Instead of the system having distributed the Intent, you can register your Activity to receive the tag directly. This is important for a particular workflow, where it makes no sense to open another app.

I’ve inserted the explanations at the appropriate places in the code.

Now, when you attach a tag and our app is already opened, onNewIntent is called and no new Activity is created.

Reading Data From an NDEF Tag

The last step is to read the data from the tag. The explanations are inserted at the appropriate places in the code once again. The NdefReaderTask is a private inner class.

The app now successfully reads the content.

Useful Apps

To check whether data is read and written properly, I personally like to use following apps:

  • NFC TagInfo by NFC Research Lab for reading data
  • TagInfo by NXP SEMICONDUCTORS for reading data
  • TagWriter by NXP SEMICONDUCTORS for writing data

Conclusion

In this tutorial I have shown you how the data from a NDEF tag can be extracted. You could expand the example to other mime types and chip technologies; a feature to write data would be useful as well. The first step to work with NFC was made. However, the Android SDK offers much more possibilities, such as an easy exchange of data (called Android Beam).

If you want to take your Android development further, check out the huge range of useful Android app templates on Envato Market. Or hire an Android developer on Envato Studio.

About the Author

Ralf Wondratschek is a computer science student from Germany. In addition to his studies, Ralf works as a freelancer in the field of mobile computing. In the last few years he has worked with Java, XML, HTML, JSP, JSF, Eclipse, Google App Engine, and of course Android. He has published two Android apps to date which can be found here.

Читайте также:  Смайлики сердечки для андроид

Источник

Learn2Crack

Android Reading and Writing NFC Tags

NFC (Near Field Communication) is a communication protocol which allows two devices to communicate and transfer data within a short distance. Some of the midrange to high-end Android devices has NFC support which allows you to utilize the feature.

NFC Tags are small chips which you can get in the form of stickers, cards, rings or even keychain. They can store a small amount of data in the range of hundreds of bytes. These are passive things which can work without a power supply or rely on other devices for power such as an NFC Tag depends on your Phone or the NFC readers to work.

Here I have bought a set of 5 tags for 4$ (₹250) from Amazon. The NFC tags I have can store data up to 144 bytes. There are different types of NFC tags which can store a larger amount of data.

Uses of NFC Tags

-> Read and Write a small amount of data such as URL, Contact information, etc.

-> Can be used to launch apps.

-> Can be used to unlock your device.

-> Security keys for App.

These are some of the applications. NFC Tags can have endless possibilities.

In this tutorial, we are going to make an app which can read and write text to an NFC tag.

Make sure your device supports NFC. You can confirm this by Settings -> More -> NFC

Buy NFC Tags to test with our App. You can get NFC Tags from online retailers such as Amazon.

Here I have created an Android Studio project with package com.learn2crack.nfc also Activity as MainActivity and layout as activity_main.

Adding Permissions to Manifest

We need to add the NFC permission to Manifest to use the NFC capability.

Adding Java 8 Support

Since we are using Java 8 Lambda functions, we need to enable Jack compiler and set compileOptions to Java version 8. Insert the snippet similar to the one defined below.

Defining String constants

Instead of hard coding we define strings in res-> values-> strings.xml and refer it from this file whenever needed.

Our main activity layout has an input EditText widget and two Buttons.

The next layout is for write dialog which is a DialogFragment. It has two TextViews and an ImageView widget.

The next layout is for read dialog which displays the contents of the NFC tag.

Creating Listener interface

We create a listener interface which implements two methods onDialogDisplayed() and onDialogDismissed().

Here we override two Fragment lifecycle methods onAttach() and onDetach(). Our MainActivity implements the interface we created before. We call the listener’s onDialogDisplayed() method in onAttach() so that the MainActivity can be notified when the dialog is displayed. Similarly, onDialogDismissed() is called in onDetach() so that the MainActivity knows when the dialog is dismissed.

We define the writeToNfc() method to write data to the NFC tag. In NFCs data is written in a standardized format called NDEF (NFC Data Exchange Format). Android has inbuilt support to create and write NDEF messages. Here we are going to write a plain text message to NFC tag. So we use the MIME type text/plain. Then we create a new NdefRecord object with MIME type and text we want to write in the tag. Then we write the data using the writeNdefMessage() method.

Similarly for reading the message we define readFromNFC() method. We read data using getNdefMessage() method which returns NdefMessage object.

Our MainActivity is the entry point for our application. Instead of defining Intent filters for the NFC tag in Manifest we define within out Activity and use it with enableForegroundDispatch() method. We also need to pass a PendingIntent to this enableForegroundDispatch() method. We use the Intent flag as FLAG_ACTIVITY_SINGLE_TOP which makes sure if the Activity is already running it pass the data to our running Activity instead of launching a new one. This enableForegroundDispatch() method intercepts all the NFC events and makes sure our Activity is the first one to receive it. We use this in our Activity lifecycle onResume() method. Similarly, we disable using disableForegroundDispatch() method on Activity’s onPause() method.

Читайте также:  Антенна для андроид для просмотра тв

The Activity’s newIntent() method is called on an NFC event. We obtain the Tag object from the Intent parcelable extra. We then get a Ndef object from the Tag object and pass it to the respective read or write fragment for read or write operation.

This program will not work on a virtual device. Make sure you test it on a physical device with NFC.

Источник

How to use NFC Tags: Detect, Read and Write NFCs with Android Studio

Kickstart your NFC project with this simple guide and starter code.

Introduction

Near-Field-Communication (NFC) isn’t new technology. With the events of Covid 19, there has been a surge in contactless NFC usage as seen by the new trend of mobile payment like Google Pay and Apple Pay. This is similar to its well-known brother, QR codes.

It has come a long way. First used in 1997 for Hasbro Star Wars toys, the now highly accessible tech which currently exists in around 73% of smartphones, is an untapped source for innovation.

Similar to my previous article on installing TF lite for Raspberry Pi, finding useful NFC material was a chore. This is meant to be a quick and clear guide for the general-use cases of NFCs.

Prerequisites

  • Android Studio — Installation guide here.
  • An Android Phone with NFC capabilities (How to check if I have NFC?)
  • NFC Device (Note: I used an NFC card)

NFC Detection

We will first detect the NFC device information:
1. NFC id
2. NFC Technologies
3. NFC type (Mifare Classic/Ultralight)
Note: We will be using the Mifare Ultralight C for this guide.

Step 0: AndroidManifest.xml, Allow NFC permissions for our app

Step 1: onCreate, Initialize the NFC adapter and define the Pending Intent

Step 2: onResume(), Enable the Foreground Dispatch to listen for NFC intent (Waiting for NFC card to be tapped)

enableForegroundDispatch allows your current (foreground) activity to intercept our NFC intent and claim priority over all other activities both within the app and other apps.

Step 3: onPause(), Disable the foreground dispatch (Stop listening for NFC tag)

Step 4: onNewIntent(), Process our new NFC Intent (Card detected)

After getting the intent, you have to parse the intent to detect the card: Code here for external helper functions.

These are our NFC Intent filters
nfcAdapter.ACTION_TAG_DISCOVERED — NFC tag discovered.
nfcAdapter.ACTION_TECH_DISCOVERED — NFC tag discovered and activities are registered for the specific technologies on the tag.
nfcAdapter.ACTION_NDEF_DISCOVERED — NFC tag discovered with NDEF payload discovered.

TAG_DISCOVERED is meant to be a fallback if no apps can handle TECH_DISCOVERED and NDEF_DISCOVERED . The same for TECH_DISCOVERED which is meant to be a fallback for NDEF_DISCOVERED .

For our case, we don’t want any filters as such we will be using TAG_DISCOVERED and TECH_DISCOVERED for global detection of the NFC.

Step 5: Helper functions, to detect and parse our NFC Tag Data

Step 6: Compile and Run the app → Go to Logcat/Run

NFC Read and Write

From our Mifare Ultralight C NFC Tag specifications: https://www.nxp.com/docs/en/data-sheet/MF0ICU2.pdf

We can only use the 4th to 39th-page address. Each page is 4 bytes, thus, we have at most 140 bytes of storage page.

Since each String letter in UTF-8 takes up around 1 byte, We only at most 140 words to work with assuming that none of our user memory pages are used. In my case, we only had 137 bytes in our card. Some had experimented with gzip to compress this data.

Each readPages reads 4 pages (16 characters/16 bytes).
To read pages 4–12, we have to readPages(4) [pages 4–7] and readPages(8) [pages 8–11] and readPages(12) [pages 12–15]. We would then have to remove the extra 3 pages(12 characters/12 bytes) from our String.

Each writePage writes 1 page(4 characters/4 bytes).

Next, simply change our previous detectTagData(Tag tag).

Global NFC Usage

If you want to be able to read and write your NFC in the background or outside your app, simply add this intent filter in your AndroidManifest.xml.

The idea of global usage is to have NFC presence at anywhere on the phone.

Источник

Оцените статью