Click here to Skip to main content
15,881,588 members
Articles / Mobile Apps / Android
Article

NFC Application Development on Android* with Case Studies

22 Jul 2014CPOL7 min read 25.2K   11  
This paper introduces NFC-based technology and usage modes in the current market. Then it also describes how to use NFC in the android applications. Finally, it presents two case studies for how to develop the NFC-based reader/writer applications.

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

Introduction

NFC (near field communication) is a standards-based, short-range wireless connectivity technology that enables simple and intuitive two-way interactions between electronic devices. It is very convenient to touch and communicate between two NFC devices. For example, with smartphone-integrated NFC technology, you can easily touch your phone to purchase items, share business cards, download discount coupons and so on. You will see many NFC-based new usages will be developed in the future.

This paper introduces NFC-based technology and usage modes in the current market. Then it also describes how to use NFC in the android applications. Finally, it presents two case studies for how to develop the NFC-based reader/writer applications.

NFC Technology Architecture

NFC is based on RFID technology at 13.56 MHz, with a typical operating distance up to 10 cm. The data exchange rate is up to 424 kilobits/s. Compared to other communication technology, the biggest advantage of NFC is it is quick and easy to use. The following graph compares NFC to other communication technologies.

Image 1

Figure 1: Comparison of short-range communication technologies

NFC technology has three modes: NFC card emulation mode, peer-to-peer mode, and reader/writer mode, shown in the following graph.

Image 2

Figure 2: NFC Protocol Families

In card emulation mode, NFC simulates an RFID integrated circuit (IC) card, with a security module, which allows users to make purchases safely. In peer–to-peer mode, you can share information, such as business cards, between different NFC devices via an NFC connection. You can also set up a WiFi* or Bluetooth* connection quickly through the NFC connection and transfer big files through the WiFi or Bluetooth connection. In reader/writer mode, you can use NFC-enabled devices to read NFC tags and launch smart tasks.

Each mode is discussed in more detail below.

NFC Card Emulation Mode

An NFC module usually consists of two parts: an NFC controller and a secure element (SE). The NFC controller is responsible for communication. The SE is responsible for encrypting and decrypting sensitive data.

Image 3

Figure 3: NFC Hardware Components

The SE connects to the NFC controller via SWP (Single Wire Protocol) or DCLB (Digital Contactless Bridge) bus. NFC standards define a logical interface between the host and the controller allowing them to communicate via the RF-field. A built-in app or a small OS implements the SE, which is responsible for the encrypting and decrypting the sensitive data.

Image 4

The three solutions to implement the SE are:

  • Embedded in SIM card
  • Embedded in SD card
  • Embedded in NFC Chip

Image 5

Figure 4: Three NFC SE Solutions

The telecom operators, such as CMCC (China Mobile Communication Corporation), Vodafone and AT&T, usually prefer the SIM card-based solution, who are encouraging their users to replace old SIM cards with new NFC-enabled ones for free.

NFC Peer-to peer Mode

Two devices with NFC can communicate directly and easily to share small files such as business cards. Two NFC-enabled devices can also share configured .xml files with each other and establish Bluetooth/WiFi connection to share big files. In this mode, no SE module is needed.

NFC Reader /Writer Mode

In this mode, the NFC host can read/write NFC tags. A good example is to read useful

information from smart posters. Users can access links to view the advertisements and download discount coupons.

Image 6Image 7

Figure 5: NFC Reader/Writer Mode

Introduction to Android NFC development

Android supports NFC with two packages: android.nfc and android.nfc.tech.

The main classes in the android.nfc package are:

NfcManager: Android devices can be used to manage all indicated NFC adapters, but because most Android devices support only one NFC adapter, NfcManager is generally called directly with getDefaultAdapter to get the specific phone adapter.

NfcAdapter: It works as an NFC agent, which is similar to the network adapter installed in the computer,by which cellphones access the NFC hardware to initiate NFC communication.

NDEF: NFC standards define a common data format called NFC Data Exchange Format (NDEF), which can store and transport various kinds of items, ranging from any MIME-typed object to ultra-short RTD-documents, such as URLs. NdefMessage and NdefRecord are two kinds of NDEF for the NFC forum defined data formats, which will be used in the sample code.

Tag: Android defined it represents a passive object like labels, cards, and so on. When the device detects a tag, Android will create a tag object, then put it in the Intent object, lastly send it to the appropriate Activity.

The android.nfc.tech package also contains many important sub-classes. These sub-classes provide access to a tag technology's features, which contain read and write operations. Depending on the type of technology used, these classes are divided into different categories, such as: NfcA, NfcB, NfcF, MifareClassic, and so on.

When a phone has NFC turned on, and after detection of a TAG, the TAG distribution system will automatically create a package of NFC TAG information of intent. If the phone has more than one application that can deal with this intent, a pop-up box will ask the user to choose which TAG activity to do. The TAG distribution system defines three types of intent. It is arranged in descending order of priority:

NDEF_DISCOVERED, TECH_DISCOVERED, TAG_DISCOVERED

Here we use the action intent-filter type to handle all types from TECH_DISCOVERED to ACTION_TECH_DISCOVERED. The file nfc_tech_filter.xml is used for the types defined in the file TAG. For details, see the Android documentation. The figure below shows the Activity of the matching process when the phone detects a TAG .

Image 8

Figure 6: Process of NFC Tag Detected

Case study: Develop an NFC-based reader/writer application

The following demo shows the reader/writer function for the NFC tag. Before you can access a device's NFC hardware and properly handle NFC intents, declare these items in your AndroidManifest.xml file:

XML
<uses-permission android:name="android.permission.NFC" />

The minimum SDK version that your application must support is level 10, so declare these items in your AndroidManifest.xml file:

XML
<uses-sdk android:minSdkVersion="10"/>

In the onCreate function,you can apply the NfcAdapter:

public void onCreate(Bundle savedInstanceState) {
……
adapter = NfcAdapter.getDefaultAdapter(this);
……
}

The following Intent call back shows the reader function. If the system broadcast Intent equals NfcAdapter.ACTION_TAG_DISCOVERED , then you can read the information in the tag and show it.

C++
@Override
	protected void onNewIntent(Intent intent){
		if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
		mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  // get the detected tag
		Parcelable[] msgs =
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
			NdefRecord firstRecord = ((NdefMessage)msgs[0]).getRecords()[0];
			byte[] payload = firstRecord.getPayload();
			int payloadLength = payload.length;
			int langLength = payload[0];
			int textLength = payloadLength - langLength - 1;
			byte[] text = new byte[textLength];
			System.arraycopy(payload, 1+langLength, text, 0, textLength);
			Toast.makeText(this, this.getString(R.string.ok_detection)+new String(text), Toast.LENGTH_LONG).show();
					}
	}

The following code shows the writer function. Before you can determine the value of mytag, you must know whether there is a tag detected or not, then write the information to mytag.

C++
If (mytag==Null){
	……
}
else{
……
write(message.getText().toString(),mytag);
……
}
	private void write(String text, Tag tag) throws IOException, FormatException {
		NdefRecord[] records = { createRecord(text) };
		NdefMessage  message = new NdefMessage(records);
// Get an instance of Ndef for the tag.
		Ndef ndef = Ndef.get(tag); // Enable I/O
		ndef.connect(); // Write the message
		ndef.writeNdefMessage(message); // Close the connection
		ndef.close();
	}

Depending on the information read from the tag, you can do more operations, such as launch a smart task, access a web site, and so on.

Case study: Develop an NFC-based application that uses the MifareClassic Card

In this demo, we use the Mifare card for the data read test and use the card’s TAG type, MifareClassic. The MifareClassic card is commonly used in many scenarios, such as ID card,bus card and so on. The traditional MifareClassic card’s storage space is divided into 16 zones (Sector), each zone has four blocks (Block), and each block can store 16 bytes of data.

The last block in each district is called the Trailer, which is mainly used to store the local block key for reading and writing data. It has two keys: A and B, and each key length is 6 bytes, the default value of which is generally full-key FF or 0 by the MifareClassic.KEY_DEFAULT definition.

So when writing the Mifare card, you first need to have the correct key value (play a protective role), and the successful authentication must be done before a user can read and write data in the area.

XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android"   
    package="org.reno"   
    android:versionCode="1"   
    android:versionName="1.0" >   
    <uses-permission android:name="android.permission.NFC" />   
    <uses-sdk android:minSdkVersion="14" />   
    <uses-feature android:name="android.hardware.nfc" android:required="true" />   
    <application   
        android:icon="@drawable/ic_launcher"   
        android:label="@string/app_name" >   
        <activity   
            android:name="org.reno.Beam"   
            android:label="@string/app_name"   
            android:launchMode="singleTop" >   
            <intent-filter>   
                <action android:name="android.intent.action.MAIN" />   
   
                <category android:name="android.intent.category.LAUNCHER" />   
            </intent-filter>   
            <intent-filter>   
                <action android:name="android.nfc.action.TECH_DISCOVERED" />   
            </intent-filter>   
            <meta-data   
                android:name="android.nfc.action.TECH_DISCOVERED"   
                android:resource="@xml/nfc_tech_filter" />   
        </activity>  
    </application>   
</manifest>

res/xml/nfc_tech_filter.xml:

XML
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> 
    <tech-list> 
       <tech>android.nfc.tech.MifareClassic</tech> 
    </tech-list> 
</resources>

An example of how to read a MifareClassic card is as follows:

C++
 private void processIntent(Intent intent) {
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    for (String tech : tagFromIntent.getTechList()) {
        System.out.println(tech);
    }
    boolean auth = false;
    MifareClassic mfc = MifareClassic.get(tagFromIntent);
    try {
        String metaInfo = "";
        //Enable I/O operations to the tag from this TagTechnology object.
        mfc.connect();
        int type = mfc.getType();
        int sectorCount = mfc.getSectorCount();
        String typeS = "";
        switch (type) {
        case MifareClassic.TYPE_CLASSIC:
            typeS = "TYPE_CLASSIC";
            break;
        case MifareClassic.TYPE_PLUS:
            typeS = "TYPE_PLUS";
            break;
        case MifareClassic.TYPE_PRO:
            typeS = "TYPE_PRO";
            break;
        case MifareClassic.TYPE_UNKNOWN:
            typeS = "TYPE_UNKNOWN";
            break;
        }
        metaInfo += "Card type:" + typeS + "n with" + sectorCount + " Sectorsn, "
                + mfc.getBlockCount() + " BlocksnStorage Space: " + mfc.getSize() + "Bn";
        for (int j = 0; j < sectorCount; j++) {
            //Authenticate a sector with key A.
            auth = mfc.authenticateSectorWithKeyA(j,
                    MifareClassic.KEY_DEFAULT);
            int bCount;
            int bIndex;
            if (auth) {
                metaInfo += "Sector " + j + ": Verified successfullyn";
                bCount = mfc.getBlockCountInSector(j);
                bIndex = mfc.sectorToBlock(j);
                for (int i = 0; i < bCount; i++) {
                    byte[] data = mfc.readBlock(bIndex);
                    metaInfo += "Block " + bIndex + " : "
                            + bytesToHexString(data) + "n";
                    bIndex++;
                }
            } else {
                metaInfo += "Sector " + j + ": Verified failuren";
            }
        }
        promt.setText(metaInfo);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Summary

The smartphone equipped with NFC allow individuals to have everything they need at the tip of their fingers without lugging around ticket stubs or parking passes. The technology can even connect with friends to share information, play games, and transfer data. NFC strives to embrace both work and play, a crucial factor in creating its success and facilitating our lives in the future.

About the Author

Songyue Wang and Liang Zhang are application engineers in Intel Software and Service Group, and focus on mobile application enabling, including Android applications development and optimization for x86 devices, Web HTML5 application development.

Other Related Articles and Resources

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Intel is inside more and more Android devices, and we have tools and resources to make your app development faster and easier.


Comments and Discussions