我发现 Android NFC API 文本和开发指南有点难以遵循,因此一些示例代码可能会有所帮助。这实际上是我在诺基亚 6212 设备中使用的 MIDP 代码的一个端口,所以我可能还没有正确理解有关 Android NFC API 的所有内容,但至少这对我有用。
首先我们创建一条 NDEF 记录:
private NdefRecord createRecord() throws UnsupportedEncodingException {
String text = "Hello, World!";
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte[1 + langLength + textLength];
// set status byte (see NDEF spec for actual bits)
payload[0] = (byte) langLength;
// copy langbytes and textbytes into payload
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT,
new byte[0],
payload);
return record;
}
然后我们将记录写入 NDEF 消息:
private void write(Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord() };
NdefMessage message = new NdefMessage(records);
// Get an instance of Ndef for the tag.
Ndef ndef = Ndef.get(tag);
// Enable I/O
ndef.connect();
// Write the message
ndef.writeNdefMessage(message);
// Close the connection
ndef.close();
}
要写入标签,显然需要 Tag 对象,可以从 Intent 中获取该对象。