如果您的应用已经有一个适用于 Android Beam(P2P 连接)的 MIME 类型“application/com.sticknotes.android”的意图过滤器,那么它也适用于包含具有相同 MIME 的 NDEF 消息的标签类型。 Android Beam 和标签发现都在接收/读取设备中生成ACTION_NDEF_DISCOVERED Intent。
要将这样的 NDEF 消息写入 MIFARE Classic 1K 标签,您可以创建一个简单的应用程序来为您执行此操作。在此应用的清单文件中放入:
<activity>
...
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
...
</activity>
并在项目的res/xml 文件夹中放置一个文件nfc_tech_filter.xml,其内容如下:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.MifareClassic</tech>
</tech-list>
</resources>
在应用程序的Activity 中输入:
onCreate(Bundle savedInstanceState) {
// put code here to set up your app
...
// create NDEF message
String mime = "application/com.sticknotes.android";
byte[] payload = ... ; // put your payload here
NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mime.toBytes(), null, payload);
NdefMessage ndef = new NdefMessage(new NdefRecord[] {ndef});
// write NDEF message
Intent intent = getIntent();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefFormatable nf = NdefFormatable.get(tag);
if (nf != null) {
// tag not yet formatted with NDEF
try {
nf.connect();
nf.format(ndef);
nf.close();
} catch (IOException e) {
// tag communication error occurred
}
} else {
Ndef n = Ndef.get(tag);
if (n != null && n.isWritable() ) {
// can write NDEF
try {
n.connect();
n.writeNdefMessage(ndef);
n.close();
} catch (IOException e) {
// tag communication error occurred
}
}
}
}
}
这会将 NDEF 消息格式化并写入未格式化(空白)的 MIFARE Classic 标签,或覆盖已使用 NDEF 格式化的标签。如果您想编写除 MIFARE Classic 之外的其他标签类型,请相应调整 nfc_tech_filter.xml。