您的位置:首页 > 移动开发 > Android开发

android-Advanced NFC

2015-12-20 16:56 465 查看
There are cases, however, when you scan a tag that does not contain NDEF data or when the NDEF data could not be mapped to a MIME type or URI. In these cases, you need to open
communication directly with the tag and read and write to it with your own protocol (in raw bytes).

android.nfc.tech
package

提到移动互联网,不能不提Android;说到云计算,不能不说KVM、Xen、OpenStack;谈起大数据,不能不谈Hadoop(大数据的最优解决方案)……这些开源技术

》The following example shows how to work with a MIFARE Ultralight tag.
package com.example.android.nfc;

import android.nfc.Tag;
import android.nfc.tech.MifareUltralight;
import android.util.Log;
import java.io.IOException;
import java.nio.charset.Charset;

public class MifareUltralightTagTester {

private static final String TAG = MifareUltralightTagTester.class.getSimpleName();

public void writeTag(Tag tag, String tagText) {
MifareUltralight ultralight = MifareUltralight.get(tag);
try {
ultralight.connect();
ultralight.writePage(4, "abcd".getBytes(Charset.forName("US-ASCII")));
ultralight.writePage(5, "efgh".getBytes(Charset.forName("US-ASCII")));
ultralight.writePage(6, "ijkl".getBytes(Charset.forName("US-ASCII")));
ultralight.writePage(7, "mnop".getBytes(Charset.forName("US-ASCII")));
} catch (IOException e) {
Log.e(TAG, "IOException while closing MifareUltralight...", e);
} finally {
try {
ultralight.close();
} catch (IOException e) {
Log.e(TAG, "IOException while closing MifareUltralight...", e);
}
}
}

public String readTag(Tag tag) {
MifareUltralight mifare = MifareUltralight.get(tag);
try {
mifare.connect();
byte[] payload = mifare.readPages(4);
return new String(payload, Charset.forName("US-ASCII"));
} catch (IOException e) {
Log.e(TAG, "IOException while writing MifareUltralight
message...", e);
} finally {
if (mifare != null) {
try {
mifare.close();
}
catch (IOException e) {
Log.e(TAG, "Error closing tag...", e);
}
}
}
return null;
}
}

》 Override the following activity lifecycle callbacks and add logic to enable and disable the foreground dispatch when the activity loses ([code]onPause()
) and regains (
onResume()
) focus.
, java.lang.String[][])]enableForegroundDispatch()
must be called from the main thread and only when the activity is in the foreground (calling in
onResume()
guarantees this). You also need to implement the
onNewIntent
callback to process the data from the scanned NFC tag.[/code]
public void onPause() {
super.onPause();
mAdapter.disableForegroundDispatch(this);
}

public void onResume() {
super.onResume();
mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
}

public void onNewIntent(Intent intent) {
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//do something with tagFromIntent
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: