NFC应用的demo以及相关的类的介绍如下:
TagViewer
一项activity,处理了一个新的标签,该设备只是发现广播,解析它,并将其显示在ListActivity其记录内容
NdefMessageParser 解析内NDEF消息记录类型的记录。
ParsedNdefRecord 解析NdefRecord所有类型实现的接口。
SmartPoster NFC是一个表示类型智能海报记录。
TextRecord NFC是一个文字记录表示类型。
UriRecord NFC是一个开放的记录表示类型。
FakeTagsActivity 一个activity,如果他们的发射已被标记扫描。这是有用的,如果你没有获得支持NFC设备或标签。
MockNdefMessages 这个类提供了一个未定义的NFC Ndef格式标签列表。
如果你正在开发一个应用程序使用了NFC的API,请记住,该功能只在Android 2.3(API级别9)和更高版本的平台支持。此外,在运行Android 2.3(API级别9)或更高的设备,并非所有的设备将提供NFC的支持。
demo如下:
TagViewer.java
package com.example.android.nfc;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.android.nfc.record.ParsedNdefRecord;
import java.util.List;
public class TagViewer extends Activity {
static final String TAG = "ViewTag";
static final int ACTIVITY_TIMEOUT_MS = 1 * 1000;
TextView mTitle;
LinearLayout mTagContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tag_viewer);
mTagContent = (LinearLayout) findViewById(R.id.list);
mTitle = (TextView) findViewById(R.id.title);
resolveIntent(getIntent());
}
void resolveIntent(Intent intent) {
// Parse the intent
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs;
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, empty, empty);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
}
// Setup the views
setTitle(R.string.title_scanned_tag);
buildTagViews(msgs);
} else {
Log.e(TAG, "Unknown intent " + intent);
finish();
return;
}
}
void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) {
return;
}
LayoutInflater inflater = LayoutInflater.from(this);
LinearLayout content = mTagContent;
content.removeAllViews();
List records = NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for (int i = 0; i < size; i++) {
ParsedNdefRecord record = records.get(i);
content.addView(record.getView(this, inflater, content, i));
inflater.inflate(R.layout.tag_divider, content, true);
}
}
@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
resolveIntent(intent);
}
@Override
public void setTitle(CharSequence title) {
mTitle.setText(title);
}
}
NdefMessageParser.java
package com.example.android.nfc;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import com.example.android.nfc.record.ParsedNdefRecord;
import com.example.android.nfc.record.SmartPoster;
import com.example.android.nfc.record.TextRecord;
import com.example.android.nfc.record.UriRecord;
import java.util.ArrayList;
import java.util.List;
public class NdefMessageParser {
// Utility class
private NdefMessageParser() {
}
/** Parse an NdefMessage */
public static List parse(NdefMessage message) {
return getRecords(message.getRecords());
}
public static List getRecords(NdefRecord[] records) {
List elements = new ArrayList();
for (NdefRecord record : records) {
if (UriRecord.isUri(record)) {
elements.add(UriRecord.parse(record));
} else if (TextRecord.isText(record)) {
elements.add(TextRecord.parse(record));
} else if (SmartPoster.isPoster(record)) {
elements.add(SmartPoster.parse(record));
}
}
return elements;
}
}
ParsedNdefRecord.java
package com.example.android.nfc.record;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public interface ParsedNdefRecord {
public View getView(Activity activity, LayoutInflater inflater, ViewGroup parent,
int offset);
}
SmartPoster.java
package com.example.android.nfc.record;
import android.app.Activity;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.example.android.nfc.NdefMessageParser;
import com.example.android.nfc.R;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class SmartPoster implements ParsedNdefRecord {
private final TextRecord mTitleRecord;
private final UriRecord mUriRecord;
private final RecommendedAction mAction;
private final String mType;
private SmartPoster(UriRecord uri, TextRecord title, RecommendedAction action, String type) {
mUriRecord = Preconditions.checkNotNull(uri);
mTitleRecord = title;
mAction = Preconditions.checkNotNull(action);
mType = type;
}
public UriRecord getUriRecord() {
return mUriRecord;
}
public TextRecord getTitle() {
return mTitleRecord;
}
public static SmartPoster parse(NdefRecord record) {
Preconditions.checkArgument(record.getTnf() == NdefRecord.TNF_WELL_KNOWN);
Preconditions.checkArgument(Arrays.equals(record.getType(), NdefRecord.RTD_SMART_POSTER));
try {
NdefMessage subRecords = new NdefMessage(record.getPayload());
return parse(subRecords.getRecords());
} catch (FormatException e) {
throw new IllegalArgumentException(e);
}
}
public static SmartPoster parse(NdefRecord[] recordsRaw) {
try {
Iterable records = NdefMessageParser.getRecords(recordsRaw);
UriRecord uri = Iterables.getOnlyElement(Iterables.filter(records, UriRecord.class));
TextRecord title = getFirstIfExists(records, TextRecord.class);
RecommendedAction action = parseRecommendedAction(recordsRaw);
String type = parseType(recordsRaw);
return new SmartPoster(uri, title, action, type);
} catch (NoSuchElementException e) {
throw new IllegalArgumentException(e);
}
}
public static boolean isPoster(NdefRecord record) {
try {
parse(record);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
public View getView(Activity activity, LayoutInflater inflater, ViewGroup parent, int offset) {
if (mTitleRecord != null) {
// Build a container to hold the title and the URI
LinearLayout container = new LinearLayout(activity);
container.setOrientation(LinearLayout.VERTICAL);
container.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
container.addView(mTitleRecord.getView(activity, inflater, container, offset));
inflater.inflate(R.layout.tag_divider, container);
container.addView(mUriRecord.getView(activity, inflater, container, offset));
return container;
} else {
// Just a URI, return a view for it directly
return mUriRecord.getView(activity, inflater, parent, offset);
}
}
private static T getFirstIfExists(Iterable<?> elements, Class type) {
Iterable filtered = Iterables.filter(elements, type);
T instance = null;
if (!Iterables.isEmpty(filtered)) {
instance = Iterables.get(filtered, 0);
}
return instance;
}
private enum RecommendedAction {
UNKNOWN((byte) -1), DO_ACTION((byte) 0), SAVE_FOR_LATER((byte) 1), OPEN_FOR_EDITING(
(byte) 2);
private static final ImmutableMap LOOKUP;
static {
ImmutableMap.Builder builder = ImmutableMap.builder();
for (RecommendedAction action : RecommendedAction.values()) {
builder.put(action.getByte(), action);
}
LOOKUP = builder.build();
}
private final byte mAction;
private RecommendedAction(byte val) {
this.mAction = val;
}
private byte getByte() {
return mAction;
}
}
private static NdefRecord getByType(byte[] type, NdefRecord[] records) {
for (NdefRecord record : records) {
if (Arrays.equals(type, record.getType())) {
return record;
}
}
return null;
}
private static final byte[] ACTION_RECORD_TYPE = new byte[] {'a', 'c', 't'};
private static RecommendedAction parseRecommendedAction(NdefRecord[] records) {
NdefRecord record = getByType(ACTION_RECORD_TYPE, records);
if (record == null) {
return RecommendedAction.UNKNOWN;
}
byte action = record.getPayload()[0];
if (RecommendedAction.LOOKUP.containsKey(action)) {
return RecommendedAction.LOOKUP.get(action);
}
return RecommendedAction.UNKNOWN;
}
private static final byte[] TYPE_TYPE = new byte[] {'t'};
private static String parseType(NdefRecord[] records) {
NdefRecord type = getByType(TYPE_TYPE, records);
if (type == null) {
return null;
}
return new String(type.getPayload(), Charsets.UTF_8);
}
}