NFC applications on Android

Source: Internet
Author: User
NFC (Near Field Communication) short-range communication technology

NFC is a set of short-distance wireless communication, usually with a distance of 4 cm or shorter. The working frequency of NFC is 13.56 M Hz, and the transmission rate is 106 kbit/s to 848 kbit/s. NFC always occurs between an initiator and a passive target. The initiator emits near-field radio waves, which can supply power to the Passive Target. These passive targets include tags that do not require power supply, cards, or power supplies.

Compared with other wireless communication technologies, such as Bluetooth and WiFi, NFC provides lower loan and distance, and is cost-effective, without power supply or matching, the entire communication process can be completed in just one second.

An Android device with NFC support is usually an initiator. It can also be used as an NFC read/write device. He will detect NFC tags and open an activity to process. Android 2.3.3 also supports limited P2P.

Tags can be divided into many types. In simple mode, only read and write segments are provided, and some can only read. Complex tags support some operations and encryption to control the reading and writing of data segments in tags. Even some tags have simple operating systems that allow some complex interactions and some code execution.

API Overview

Android. NFC package contains top-level classes used to interact with the local NFC Adapter. These classes can represent the detected tags and use the ndef data format.

Class

Description

Nfcmanager

An NFC adapter manager that lists all NFC adapters supported by this Android device. most Android devices only have one NFC Adapter. In most cases, you can use the static method getdefaadapter adapter (context) to retrieve the adapter.

Nfcadapter

Indicates the NFC adapter of the device. You can define the intent to request the system to send the tags notification to your activity. You can also provide a method to register the front-end tag notification release and front-end ndef push. Frontend ndef push is the only Supported p2p NFC communication mode in the current Android version.

Ndefmessage andndefrecord

Ndef is a data structure defined by the NFC forum. It is used to effectively store data to NFC tags, such as text, URL, and other MIME types. An ndefmessage acts as a container that stores the sent and read data. An ndefmessage object contains 0 or more ndefrecord. Each ndef record has a type, such as text, URL, smart poster/advertisement, or other MIME data. The first nfcrecord type in ndefmessage is used to send tags to the activity on an Android device.

Tag

Identifies a passive NFC target, such as tag, card, key hook, or even an NFC card simulated by phone.

When a tag is detected, a tag object will be created and encapsulated into an intent, and then the NFC publishing system sends the intent to the activity registered to accept the intent. You can use the gettechlist () method to obtain the technical details supported by this tag and create a corresponding tagtechnology object provided by Android. NFC. Tech.

Android. NFC. Tech package contains classes that query tag attributes and perform I/O operations. These classes indicate different NFC technical standards supported by a tag.

Class

Description

Tagtechnology

This interface is required by all the tag technology classes below.

Nfca

Supports ISO 14443-3a. Provides access to NFC-A (ISO 14443-3a) properties and I/O operations.

Nfcb

Provides access to NFC-B (ISO 14443-3b) properties and I/O operations.

Nfcf

Provides access to NFC-F (JIS 6319-4) properties and I/O operations.

Nfcv

Provides access to NFC-V (ISO 15693) properties and I/O operations.

Isodep

Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations.

Ndef

Provides access to and other operations on the data of tags formatted as ndef.

Provides access to ndef data and operations on NFC tags that have been formatted as ndef.

Ndefformatable

Provides a formatting operation for tags that can be formatted into ndef format.

Mifareclassic

If the Android device supports Mifare, it provides attributes and I/O operations for the Mifare classic target.

Mifareultralight

If the Android device supports Mifare, it provides attributes and I/O operations for the Mifare ultralight target.

Declare the elements of Android manifest. xml

1. NFC uses elements to access NFC hardware:

2. The minimum SDK version must be set correctly. API level 9 only supports limited tags, including:
. Use action_tag_discovered to publish Tag Information
. Access ndef messages only through the extra_ndef_messages Extension
Other tag attributes and I/O operations are not supported.
Therefore, you may want to use API level 10 to implement extensive read/write support for tags.

3. Uses-Feature Element Definition: Your program can display NFC hardware in the Android Market.

4. The NFC intent filter tells the Android system that your activity can process NFC data. One or more intent filters can be defined:

Android: Resource = "@ XML/Nfc_tech_filter. Xml "/>

The preceding three intent filters have priority. For more information, see the tag publishing system below.

You can also see androidmanifest. xml in the nfcdemo example to have a deeper understanding.

Tag Publishing System

When the Android device detects an NFC tag, the common behavior is to automatically find the most suitable activity and process the tag intent without selecting the activity to process. Because the device scans NFC tags in a very short range and time, if you have the user to select, you may need to move the device, which will interrupt the scanning process. You should develop the tags activity that you only need to process to prevent the user from choosing which activity to process. Android provides two systems to help you correctly identify whether an NFC tag is what your activity wants to handle: The intent publishing system and the foreground activity publishing system.

The intent publishing system checks intent filters of all activities to find the activities that have defined the tag to be processed. If multiple activities are configured to process the same tag intent, the activity selector is used to select the activity to use. After the selected activity is selected, the selected activity is used to process the intent.

The foreground publishing system allows an activity to overwrite the intent publishing system and process the tag intent first. This requires that the activity of the tag intent be processed and run on the foreground. When an NFC tag is scanned, the system first checks whether the front-end activity supports processing the intent. If yes, the intent is sent to the activity. If not, it is transferred to the intent publishing system.

Use intent Release System

The intent publishing system specifies three intents with different priorities. Generally, after a tag is detected, the intent is started. The startup follows the following actions:

· Android. NFC. action. ndef_discovered: This intent is started when a tag containing the ndef load is detected. This is the highest priority intent. The Android system does not allow you to specify a intent to process all NFC data types, you must go to androidmanifest. specify the elements corresponding to the NFC tag in XML, so that when the data type passed by the scanned tag matches the one you defined, your activity will be called. For example, to process an ndef_discovered intent containing plain text, you need to define androidmanifest. XML as follows:
File:

 

If ndef_discovered intent has been started, tech_discovered and tag_discovered intents will not be started. If an unknown tag or tag that does not contain the ndef load is detected, the intent will not be started.

· Android. NFC. action. tech_discovered: If ndef_discovered intent is not started or the filter of no activity detects ndef_discovered, And the tag is known, this tech_discovered intent will start. tech_discovered intent requires you to specify the Technologies List in a resource file (XML. For more details, see the following specifying
Tag technologies to handle.

· Android. NFC. Action. tag_discovered: If no activity processing _ discovered and tech_discovered intents or tag is detected as unknown, the intent will be started.

Specifying tag technologies to handle specifies the technologies to process

Assume that your activity is in androidmanifest. the XML file declares that it is used to process android. NFC. action. tech_discovered intent. You must create a resource file in XML format and add the technologies supported by your activity to the tech-list set. In this way, your activity will be recognized as a processor capable of processing these tech-lists. If the technology used by the tag belongs to your defined list, your activity will receive this intent. You can use gettechlist () to obtain tag-supported technologies.

For example, if a tag is detected to support mifareclassic, ndefformatable, and nfca, your tech-list set must specify one or more of them to ensure that your activity can process this intent.

The following is an example of a resource file that defines all technologies. You can delete unnecessary items as needed and save the file with any name +. XML to the/RES/XML folder.

Android. NFC. Tech. isodep
Android. NFC. Tech. nfca
Android. NFC. Tech. nfcb
Android. NFC. Tech. nfcf
Android. NFC. Tech. nfcv
Android. NFC. Tech. ndef
Android. NFC. Tech. ndefformatable
Android. NFC. Tech. mifareclassic
Android. NFC. Tech. mifareultralight

You can also specify multiple tech-list sets. Each set is considered independent. If any single tech-list set is a subset of the technologies set returned by gettechlist (), your activity will be considered matched. This operation also provides 'and' or 'operations. The following example indicates that the nfca and ndef cards are supported, or the nfcb and ndef cards are supported:

Android. NFC. Tech. nfca
Android. NFC. Tech. ndef

Android. NFC. Tech. nfcb
Android. NFC. Tech. ndef

In the androidmanifest. xml file, the method for specifying this tech-list resource file is to create an element in the element, for example, the following example:


...

Android: Resource = "@ XML/nfc_tech_filter"/>
...

Use the foreground publishing system using the foreground Dispatch System

The foreground publishing system allows an activity to intercept a tag intent to obtain the highest priority. This method is easy to use and implement:

1. Add the following code to the oncreate () method of the activity.

A. Create a pendingintent object so that the Android system can locate this object when a tag is detected.

Pendingintent = pendingintent. getactivity (
This, 0, new intent (this, getclass (). addflags (intent. flag_activity_single_top), 0 );

B. declare the intent you want to process in intent filters. When a tag is detected, check the foreground publishing system. If the foreground activity meets the requirements of the intent filter, the front-end activity will process the intent. If not, the foreground publishing system transfers the intent to the intent publishing system. If null intent filters is specified, when any tag is detected, you will receive the tag_discovered intent. Therefore, please note that you should only process the intent you want.

Intentfilter ndef = new intentfilter (nfcadapter. action_ndef_discovered );
Try {
Ndef. adddatatype ("*/*");/* handles all MIME Based dispatches.
You shoshould specify only the ones that you need .*/
}
Catch (malformedmimetypeexception e ){
Throw new runtimeexception ("fail", e );
}
Intentfiltersarray = new intentfilter [] {
Ndef,
};

C. Set a list of tag technologies to be processed by your program and call the object. Class. getname () method to obtain the technology class you want to support.

Techlistsarray = new string [] [] {New String [] {nfcf. Class. getname ()}};

2. overwrite the following method to enable or disable the foreground publishing system. For example, onpause () and onresume () methods. Enableforegrounddispatch (activity,
Pendingintent, intentfilter [], string [] []) and the activity is on the foreground (which can be called in onresume () to ensure this ). You also need to overwrite the onnewintent callback to process the obtained NFC tag data.

Public void onpause (){
Super. onpause ();
Madapter. disableforegrounddispatch (this );
}
Public void onresume (){
Super. onresume ();
Madapter. enableforegrounddispatch (this, pendingintent, intentfiltersarray, techlistsarray );
}
Public void onnewintent (intent ){
Tag tagfromintent = intent. getparcelableextra (nfcadapter. extra_tag );
// Do something with tagfromintent
}

See the foregrounddispatch sample from API demos for the complete sample.

Use Data on NFC tags

Data on NFC tags is stored in bytes, so you can convert them into other formats you want. When writing to a tag, you must write in byte format. Android provides APIs to help write ndef-compliant information. Using this standard ensures that your data can be supported by all android NFC devices when writing to tags. However, many tags use their own standards to store data, which are also supported by Android. However, you must implement the protocol stack to read and write these tags. You can find all supported technologies in Android. NFC. Tech and learn about technology in the tagtechnology interface. This section briefly introduces how to use ndef In the Android system.
Message. This does not mean a complete ndef function introduction. But marked the main things that need attention and use.

To facilitate the use of ndef messages, Android provides ndefrecord and ndefmessage to wrap the original byte data into ndef messages. An ndefmessage is a container that saves 0 or more ndefrecords. Each ndefrecord has its own unique type name format. The record type and ID are separated from other records. You can store different types of records with different lengths to the same
Ndefmessage. The NFC tag Capacity Limit determines the size of your ndefmessage.
Tags that support ndef and ndefformatable can return and accept ndefmessage objects as parameters for read/write operations. You need to create your own logic to read and write bytes for other tag technologies in Android. NFC. Tech.

You can download ndef standard technical documents from NFC Forum (http://www.nfc-forum.org/specs/), such as plain text and smart posters. The nfcdemo example declares ndef messages for both plain text and smart posters.

Read an NFC tag

When an NFC tag is near an NFC device, a corresponding intent will be created on the device. Then notify the appropriate program to process the intent.
The following method processes the tag_discovered intent and uses the iterator to obtain the data contained in the ndef tag load:

Ndefmessage [] getndefmessages (intent ){
// Parse the intent
Ndefmessage [] msgs = NULL;
String action = intent. getaction ();
If (nfcadapter. action_tag_discovered.equals (Action )){
Parcelable [] rawmsgs = intent. getparcelablearrayextra (nfcadapter. extra_ndef_messages );
If (rawmsgs! = NULL ){
Msgs = new ndefmessage [rawmsgs. Length];
For (INT I = 0; I <rawmsgs. length; I ++ ){
Msgs [I] = (ndefmessage) rawmsgs [I];
}
}
Else {
// Unknown tag type
Byte [] Empty = new byte [] {};
Ndefrecord record = new ndefrecord (ndefrecord. tnf_unknown, empty );
Ndefmessage MSG = new ndefmessage (New ndefrecord [] {record });
Msgs = new ndefmessage [] {MSG };
}
}
Else {
Log. E (TAG, "unknown intent" + intent );
Finish ();
}
Return msgs;
}

Remember that the data read by the NFC device is of the byte type, so you may need to convert it into another format to present it to the user. The nfcdemo example shows how to use the class com. example. Android. NFC. Record to parse ndef messages, such as plain text and smart posters.

Write NFC tag

Writing to NFC tags involves constructing an ndef message and using tag technologies that match tags. The following code shows how to write a simple text to the ndefformatable Tag:

Ndefformatable tag = ndefformatable. Get (t );
Locale locale = locale. us;
Final byte [] langbytes = locale. getlanguage (). getbytes (charsets. us_ascii );
String text = "Tag, you're it! ";
Final byte [] textbytes = text. getbytes (charsets. utf_8 );
Final int utfbit = 0;
Final char status = (char) (utfbit + langbytes. Length );
Final byte [] DATA = bytes. Concat (New byte [] {(byte) status}, langbytes, textbytes );
Ndefrecord record = ndefrecord (ndefrecord. tnf_well_known, ndefrecord. rtd_text, new byte [0], data );
Try {
Ndefrecord [] records = {text };
Ndefmessage message = new ndefmessage (records );
Tag. Connect ();
Tag. Format (Message );
}
Catch (exception e ){
// Do error handling
}

Point-to-point data exchange

Frontend push technology supports simple point-to-point data exchange. You can use enableforegroundndefpush (activity,
Ndefmessage) method to enable this function. To use this function:

· The activity that pushes data must be a foreground activity.

· You must encapsulate the data you want to send into the ndefmessage object.

· Devices receiving push data must support the com. Android. NPP ndef push protocol, which is optional for Android devices.

If your activity has enabled the push function at the front end, the standard intent publishing system is forbidden. However, if your activity allows the foreground to publish the system, the tag detection function is still available, but only applicable to the foreground publishing system.

To enable foreground push:

1. Create an ndefmessage containing ndefrecords that you want to push to other NFC devices.

2. Implement onresume () and onpause () callbacks in your activity to correctly process the life cycle of the front-end push. You must call enableforegroundndefpush (activity,
Ndefmessage) (which can be called in onresume () to ensure this ).

Public void onresume (){
Super. onresume ();
If (madapter! = NULL)
Madapter. enableforegroundndefpush (this, myndefmessage );
}
Public void onpause (){
Super. onpause ();
If (madapter! = NULL)
Madapter. disableforegroundndefpush (this );
}

When the activity is on the frontend, you can push data close to another NFC device. For more information about point-to-point data exchange, see foregroundndefpush.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.