Android's NFC

NFC Introduction:

Near Field Communication near field communication is a data transmission technology.

One major difference with wifi, Bluetooth, infrared ray data transmission technology effective distance is generally not more than 4cm.

 

NFC supports three modes of operation:

1. The card reader mode;

2. The card emulation mode;

3. point to point mode;

 

1. Reader mode:

Read by NFC device (NFC-enabled Android phones) from labels, stickers, newspapers, postcards and other media with an NFC chip information, or write data to these media.

 

2. Card emulation mode:

Is an NFC-enabled phone or other electronic device as debit cards, credit cards, bus cards, access cards such as IC card; basic principle is the information corresponding to the IC card (payment credentials) stored in packets encapsulated into an NFC phone, requires a NFC RF units (corresponding to the brush card using conventional IC card) Shihai use the phone close to an RF NFC, NFC phone will receive a radio frequency signal is sent over, by a complex series of validation, the corresponding information NFC incoming RF IC card, a IC card data is the last of these incoming RF NFC computer connected, and performs corresponding processing (e.g., electron transfer, door operation, etc.).

 

3. Ad Hoc mode:

Bluetooth, infrared similar, can be used to exchange data between different NFC devices, NFC peer to peer mode only effective distance is shorter, no more than 4cm; but if the two devices are using Android4.2 and above, NFC directly using Bluetooth, a technique known as Android Beam, Android Beam so that the transmission data is not limited to the two devices of 4cm.

 

Basics:

1.Android SDK API standard primarily supports NFC Forum (Forum Standard), this standard is called NDEF (NFC Data Exchange Format, NFC Data Exchange Format);

 

2.Android SDK API supports the following three operations NDEF data:

. A NDEF format data read from the NFC tag;

. B NDEF format data is written to the NFC tag;

. C transmits through the Android Beam technology NDEF data to another NFC device;

 

3. The apparatus will be established before the data in the NFC device a NFC tag or another NFC read in 0.1 seconds the NFC connection, then the data is automatically read from the end of the read end data flow; data sink calls according to a specific data format and the corresponding tag types Activity (this behavior is also referred to as a tag Dispatch), which need to define Activity Intent filter, which will be specified in the Intent filter different filtering mechanism, is divided into three levels, also known as triple filtration mechanism of NFC.

 

4.NDEF_DISCOVERED:

NDEF data filter only a fixed format. For example: URI plain text, specify the protocol (http, ftp, smb, etc.) and the like;

 

  TECH_DISCOVERED:

When ACTION_NDEF_DISCOVERED specified Tag not match filtering mechanism, such a filter mechanism will be used to match, this mechanism is not filtered by the Tag match the data format, but rather in accordance with the matching support Tag data storage format, this wider range of filtering;

 

  TAG_DISCOVERED:

If the NFC filtering mechanism as if ... else if ... else statement, then this filtering mechanism is equivalent to else part, the current mechanism face two kinds of filters match fails, the system will take advantage of this filtering mechanism treated, this filtering process for the unrecognized Tag (data format is wrong, but does not match the supported formats Tag).

 

5.Android will in turn match NDEF_DISCOVERED, TECH_DISCOVERED and TAG_DISCOVERED; If you still can not match Tag by triple filtration mechanism, do nothing; usually after a successful match Tag, Android device sounds more crisp sound, without success matching Tag , will be issued relatively dull sound.

 

This process is a process flow as shown below:

 

6. In part manifest file needs to be set are:

Setting permissions:

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

 

Restrictions Android version:

android:minSdkVersion="14"

 

Limiting device installed:

<uses-feature  android:name="android.hardware.nfc"  android:required="true" />

 

Activity is provided Intent Filter, such as a set of three filtering mechanism:

<intent-filter>
    <action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>

 

Next, we first example, this example belongs to the card reader mode, read and write data from the NFC chip.

It's manifest file reads as follows:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.r8c.nfc_demo"
android:versionCode="110"
android:versionName="1.1.0" >

<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="17" />
<!-- NFC权限声明 -->
<uses-permission android:name="android.permission.NFC" />

<uses-feature
android:name="android.hardware.nfc"
android:required="true" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.r8c.nfc_demo.NfcDemoActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- TECH_DISCOVERED类型的nfc -->
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<!-- 后设资源 调用自己建立的文件夹xml中的文件 -->
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
</activity>
</application>

</manifest>


Its contents are as follows Activity, including read, write, delete, delete features three functions :( which is by writing a null value achieved)

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
android.content.Intent Import;
Import android.content.IntentFilter;
Import android.graphics.Color;
Import android.util.Log;
Import android.view.Menu;
Import android.view.View;
Import android.view.View.OnClickListener ;
Import android.widget.Button;
Import android.widget.TextView;
Import android.widget.Toast;

public class NfcDemoActivity the implements OnClickListener the extends Activity {

// the NFC adapter
Private NfcAdapter nfcAdapter = null;
// convey intent
private PendingIntent pi = null;
// filter out the components can not respond to treatment and the Intent
Private IntentFilter tagDetected = null;
// text controls
Private TextView PROMT = null;
// whether to support NFC-enabled tag
= isNFC_support to false Boolean Private;
// read, write, delete button controls
Private readBtn the Button, writeBtn, deleteBtn;

@Override
protected void the onCreate (the Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
the setContentView (R.layout.activity_nfc_demo);
setupViews ();
initNFCData ();
}

@Override
protected void onResume () {
super.onResume ();
IF (== isNFC_support to false) {
// If the device does not support the NFC functionality or NFC turned off to return
return;
}
/ / starts listening to the NFC device is connected
startNFC_Listener ();

iF (NfcAdapter.ACTION_TECH_DISCOVERED.equals (this.getIntent ()
.getAction ())) {
// Note that if the code is almost not come in, because just on one line of code to open the monitor NFC connection, the next line of code immediately received the intent NFC connections, this small chance
// to process the the Intent
processIntent (the this .getIntent ());
}
}

@Override
protected void the onPause () {
super.onPause ();
IF (== isNFC_support to true) {
// if the current Activity is not the most distal end of the phone, connected to the NFC device stops listening
stopNFC_Listener ( );
}
}

@Override
protected void onNewIntent (the intent intent) {
super.onNewIntent (intent);
// app is currently running front-end interface, this time there is intent to send over, then the system will call onNewIntent callback method, the intent send over
// we only need to verify the intent here is NFC-related intent, and if so, call processing method
IF (NfcAdapter.ACTION_TECH_DISCOVERED.equals (intent.getAction ())) {
processIntent (intent);
}
}

@Override
public void onClick (View v) {

// Click the Read button
IF (v.getId () == R.id.read_btn) {
the try {
String Content = the Read (tagFromIntent);
IF (Content = null &&!! content.equals ( "")) {
promt.setText (promt.getText () + "NFC tag content: \ n-" content +
+ "\ n-");
} the else {
promt.setText (promt.getText () + " nfc label content: \ n "+" is empty \ n-");
}
} the catch (IOException E) {
promt.setText (promt.getText () +" error: "+ e.getMessage () +" \ n " );
Log.e ( "myonclick", "read nfc abnormal", E);
} the catch (a FormatException E) {
promt.setText (promt.getText () + "error:" + e.getMessage () + " \ n-");
Log.e ("myonclick "," read nfc abnormal ", E);
}
// After writing the write clicking
} else if (v.getId() == R.id.write_btn) {
try {
write(tagFromIntent);
} catch (IOException e) {
promt.setText(promt.getText() + "错误:" + e.getMessage() + "\n");
Log.e("myonclick", "写nfc异常", e);
} catch (FormatException e) {
promt.setText(promt.getText() + "错误:" + e.getMessage() + "\n");
Log.e("myonclick", "写nfc异常", e);
}
} else if (v.getId() == R.id.delete_btn) {
try {
delete(tagFromIntent);
} catch (IOException e) {
promt.setText(promt.getText() + "错误:" + e.getMessage() + "\n");
Log.e("myonclick", "删除nfc异常", e);
} catch (FormatException e) {
promt.setText(promt.getText() + "错误:" + e.getMessage() + "\n");
Log.e ( "myonclick", "Delete nfc abnormal", E);
}
}
}

Private void setupViews () {
// control binding
PROMT = (the TextView) the findViewById (R.id.promt);
readBtn = (the Button ) the findViewById (R.id.read_btn);
writeBtn = (the Button) the findViewById (R.id.write_btn);
deleteBtn = (the Button) the findViewById (R.id.delete_btn);
// text control to assign initial text
promt.setText ( "waiting for RFID tag");
// listen to read, write, delete button control
readBtn.setOnClickListener (the this);
writeBtn.setOnClickListener (the this);
deleteBtn.setOnClickListener (the this);
}

Private void initNFCData () {
// initialize the device support NFC function
isNFC_support = to true;
// get the default adapter nfc
= NfcAdapter.getDefaultAdapter nfcAdapter (getApplicationContext ());
// define the message
String MetaInfo = "";
// determine whether the device supports NFC or launch NFC
IF (nfcAdapter == null) {
MetaInfo = "device does not support NFC"!;
Toast.makeText (the this, MetaInfo, Toast.LENGTH_SHORT) the .Show ();
isNFC_support = to false;
}
IF {(nfcAdapter.isEnabled ()!)
MetaInfo = "Please first NFC enabled in the system settings!";
Toast.makeText (the this, MetaInfo, Toast.LENGTH_SHORT) the .Show ();
isNFC_support = to false;
}

IF (== isNFC_support to true) {
init_NFC ();
} the else {
promt.setTextColor (Color.RED);
promt.setText (MetaInfo);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nfc_demo, menu);
return true;
}

// 字符序列转换为16进制字符串
private String bytesToHexString(byte[] src) {
return bytesToHexString(src, true);
}

private String bytesToHexString(byte[] src, boolean isPrefix) {
StringBuilder stringBuilder = new StringBuilder();
if (isPrefix == true) {
stringBuilder.append("0x");
}
if (src == null || src.length <= 0) {
return null;
}
char[] buffer = new char[2];
for (int i = 0; i < src.length; i++) {
buffer[0] = Character.toUpperCase(Character.forDigit(
(src[i] >>> 4) & 0x0F, 16));
buffer[1] = Character.toUpperCase(Character.forDigit(src[i] & 0x0F,
16));
System.out.println(buffer);
stringBuilder.append(buffer);
}
return stringBuilder.toString();
}

private Tag tagFromIntent;

/**
* Parses the NDEF Message from the intent and prints to the TextView
*/
public void processIntent(Intent intent) {
if (isNFC_support == false)
return;

// 取出封装在intent中的TAG
tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

promt.setTextColor(Color.BLUE);
String metaInfo = "";
metaInfo + = "Card ID:" + bytesToHexString (tagFromIntent.getId ()) + "\ n-";
Toast.makeText (the this, "find cards", Toast.LENGTH_SHORT) the .Show ();

// List Tech
String prefix = "android.nfc.tech.";
String [] = techList tagFromIntent.getTechList ();

// analysis of NFC card type: Mifare Classic / UltraLight Info
String CardType = "";
for (int I = 0; I <techList. length; I ++) {
IF (techList [I] .equals (NfcA.class.getName ())) {
// read the TAG
NFCA MFC = NfcA.get (tagFromIntent);
the try {
IF ( "" .equals (CardType) )
CardType = "MifareClassic card type \ n NDEF message is not supported \ n";
} the catch (Exception E) {
e.printStackTrace ();
}
} the else IF (techList [I].equals(MifareUltralight.class.getName())) {
MifareUltralight mifareUlTag = MifareUltralight
.get(tagFromIntent);
String lightType = "";
// Type Info
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
lightType = "Ultralight";
break;
case MifareUltralight.TYPE_ULTRALIGHT_C:
lightType = "Ultralight C";
break;
}
CardType = lightType + "卡片类型\n";

Ndef ndef = Ndef.get(tagFromIntent);
CardType += "最大数据尺寸:" + ndef.getMaxSize() + "\n";

}
}
metaInfo += CardType;
promt.setText(metaInfo);
}

// 读取方法
private String read(Tag tag) throws IOException, FormatException {
if (tag != null) {
// Analytical Tag acquired NDEF instance
Ndef NDEF = Ndef.get (Tag);
// open connection
ndef.connect ();
// Get the NDEF message
NdefMessage = ndef.getNdefMessage Message ();
// convert a message to byte array
byte [] = message.toByteArray Data ();
// convert byte array into a string
string STR = new new string (Data, Charset.forName ( "UTF-. 8"));
// close the connection
ndef.close ( );
return STR;
} the else {
Toast.makeText (NfcDemoActivity.this, "nfc card device and disconnect, reconnect ...",
Toast.LENGTH_SHORT) the .Show ();
}
return null;
}

// write the method of the
Private void Write (the Tag Tag) throws IOException, a FormatException {
IF (Tag! = null) {
// new NdefRecord array, in this embodiment only one array element
NdefRecord [] = {createRecord Records ()};
// Create a NdefMessage example
NdefMessage Message = new new NdefMessage (Records);
// parse the acquired TAG NDEF instance
Ndef NDEF = Ndef.get (Tag);
// open the connection
ndef. connect ();
// write NDEF message
ndef.writeNdefMessage (message);
// close the connection
ndef.close ();
promt.setText (promt.getText () + "data is written successfully!" + "\ n") ;
} the else {
Toast.makeText (NfcDemoActivity.this, "nfc card device and disconnect, reconnect ...",
Toast.LENGTH_SHORT) the .Show ();
}
}

// remove method
private void delete (Tag tag ) throws IOException, a FormatException {
IF (Tag! = null) {
// create a new one which no information NdefRecord examples
= New new NdefRecord nullNdefRecord NdefRecord (NdefRecord.TNF_MIME_MEDIA,
new new byte [] {}, new new byte [] {}, new new byte [] {});
NdefRecord [] = {nullNdefRecord Records};
NdefMessage Message = new new NdefMessage (Records);
// parse the acquired TAG NDEF instance
Ndef NDEF = Ndef.get (Tag);
// open connection
ndef.connect ();
// write information
ndef.writeNdefMessage (message);
// close the connection
ndef.close ();
promt.setText (promt.getText () + "delete data successfully!" + "\ n-");
} the else {
Toast.makeText (NfcDemoActivity.this, "nfc card device and disconnect, reconnect ..." ,
Toast.LENGTH_SHORT) the .Show ();
}
}

// returns a NdefRecord instance
private NdefRecord createRecord () throws UnsupportedEncodingException {
// string assembled, ready for your information to be written
String msg = "BEGIN: VCARD \ n" + "VERSION: 2.1 \ n" + " China Wuhan City, Hubei Province, \ n"
+ "of Computer Science, Wuhan University \ n "+" the END: the VCARD ";
// convert the string into a byte array
byte [] textBytes Msg.getBytes = ();
// byte array package to a NdefRecord example to
NdefRecord textRecord = new NdefRecord (NdefRecord. TNF_MIME_MEDIA,
"text / X-a vCard" .getBytes (), new new byte [] {}, textBytes);
return textRecord;
}

Private the MediaPlayer Ring () throws Exception, IOException {
// the TODO Auto-Generated Method Stub
Uri Alert = RingtoneManager
.getDefaultUri (RingtoneManager.TYPE_NOTIFICATION);
the MediaPlayer the MediaPlayer Player new new = ();
player.setDataSource (the this, Alert);
AudioManager AudioManager = Final (AudioManager) the getSystemService (Context.AUDIO_SERVICE);
IF (audioManager.getStreamVolume (AudioManager.STREAM_NOTIFICATION) = 0!) {
player.setAudioStreamType (AudioManager.STREAM_NOTIFICATION);
player.setLooping (to false);
player.prepare () ;
Player.start ();
}
return Player;
}

Private void startNFC_Listener () {
// begin listening NFC device is connected, if the connection is intended to send pi
nfcAdapter.enableForegroundDispatch (the this, pi,
new new the IntentFilter [] {} tagDetected, null );
}

Private void stopNFC_Listener () {
// stop listening to the NFC device is connected
nfcAdapter.disableForegroundDispatch (the this);
}

Private void init_NFC () {
// initialize the PendingIntent, when the connection with an NFC device, on to process current Activity
PI = PendingIntent.getActivity (the this, 0, the Intent new new (the this, getClass ())
.addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// New IntentFilter, using a second filtering mechanism
tagDetected the IntentFilter new new = (NfcAdapter.ACTION_TECH_DISCOVERED);
tagDetected.addCategory (Intent.CATEGORY_DEFAULT);
}

}

Here is the link to download the complete source code example:

Demo1 the NFC Android
---------------------
Author: Bear
Source: CSDN
Original: https: //blog.csdn.net/bear_huangzhen/article/details/46333421
copyright Disclaimer: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/Alex80/p/11117452.html