How to create an NDEF message that erases a NFC ta

2019-09-21 05:55发布

I am creating an NFC application. I am a noob at Android this is my 2nd application. I was wondering if anyone knows how to create a message that erases the NFC tag. This function is seen in applications like TagWriter.

标签: android nfc ndef
1条回答
Evening l夕情丶
2楼-- · 2019-09-21 06:10

What exactly do you want to achieve? An NDEF message is a data packet that you store on an NFC tag, so "erasing" somewhat contradicts "creating an NDEF message". However, what you can do is create an NDEF message with a single empty NDEF record:

NdefMessage msg = new NdefMessage(new NdefRecord[] {
    new NdefRecord(NdefRecord.TNF_EMPTY, null, null, null)
});
ndefTag.writeNdefMessage(msg);

But keep in mind that writing this message to the tag will hide and partially overwrite any pre-existing NDEF messages on the tag, however it will not erase all data on the tag. For instance if a pre-existing message on the tag was longer than the new message, some parts of the old message's data may still remain stored on the tag.

So if you want to overwrite all data on the tag you might want to create a dummy record that contains as much data as can be stored on the tag (you can determine the maximum size of an NDEF message using Ndef.getMaxSize(), but you have to account for header bytes when creating your record). After writing that dummy record, you can again write the empty NDEF message as described above.

NdefMessage msg = new NdefMessage(new NdefRecord[] {
    new NdefRecord(NdefRecord.TNF_UNKNOWN, null, null,
                   new byte[ndefTag.getMaxSize() - messageOverhead])
});
ndefTag.writeNdefMessage(msg);
查看更多
登录 后发表回答