最近在研究android的nfc问题
首先再网上有很多关于android nfc 读写的问题,但是大多数都是关于Mifare Classic类型卡的读写,我百试不得骑解,于是自己写了一些程序供大家参考,
我的手机android 4.4,google Nexus4
nfc 卡的类型是:ultralight c
读取ndef关键代码:
public String readNdef(Tag tag) {
String result = null;
Ndef ndef = Ndef.get(tag);
try {
ndef.connect();
NdefMessage msg = ndef.getNdefMessage();
result = new String(msg.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(ndef != null && ndef.isConnected()) {
ndef.close();
ndef = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
对nfc有意写了解的人就会知道传入的tag是靠 tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
这么来的,具体的就不多说了,相信大家网上已经搜到了好多
还有写入ndef数据的关键代码
public void writeNdef(Tag tag,String Text) {
Ndef ndef = Ndef.get(tag);
try {
ndef.connect();
byte[] data = Text.getBytes();
NdefMessage msg = new NdefMessage(
new NdefRecord[] { createMimeRecord(
"application/com.bjypc.han.googlejuesai", data)
});
ndef.writeNdefMessage(msg);
} catch (IOException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
} finally {
try {
if(ndef != null && ndef.isConnected()) {
ndef.close();
ndef = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
NdefRecord mimeRecord = new NdefRecord(
NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
return mimeRecord;
}
好了,到此为止我们就成功的读取或写入了ndef卡的ndef信息了,
希望能帮到大家!
转载于:https://www.cnblogs.com/riasky/p/3458828.html