i have succeeded to write informations into my nfc card but now it does not work anymore, here is my code:
public void writeTag(MifareUltralight mifareUlTag) {
try {
mifareUlTag.connect();
String val=getRandomString();
// mifareUlTag.writePage(4, "rfa".getBytes(Charset.forName("US-ASCII")));
// mifareUlTag.writePage(5, "nfc".getBytes(Charset.forName("US-ASCII")));
mifareUlTag.writePage(10, val.getBytes(Charset.forName("US-ASCII")));
//mifareUlTag.writePage(7, " now".getBytes(Charset.forName("US-ASCII")));
} catch (IOException e) {
Log.e(TAG, "IOException while writing MifareUltralight...", e);
} finally {
try {
mifareUlTag.close();
} catch (IOException e) {
Log.e(TAG, "IOException while closing MifareUltralight...", e);
}
}
}
the error that happens is: android.nfc.TagLostException: Tag was lost
the getRandomString
method is a function whiche returns a random string of 3 characters. my card is working again because i can read his number.
I found that with real users it was very easy to get TagLostException
or IOException
with enableForegroundDispatch
when doing anything other than reading Ndef data, especially trying to write data.
The reason is simple, with enableForegroundDispatch
you don't control the notification sound.
Users were hearing and removing the Tag from the RF field too early, with enableForegroundDispatch
the sound is generated when the system NFC App has detected a Tag, it then has to craft the Intent
, pause and resume your App to be able to deliver that Intent
, your App has to process that Intent
and then start writing to the Tag.
I found it much more reliable to use enableReaderMode
where you can turn off the System App notification sound and make your own sound when you have finished writing to the Tag. enableReaderMode
also does not pause and resume your App but instead the Tag reading is handled in a new thread, this is generally less overhead and quicker thus lead to a lower chance of errors like TagLostException
Of course these errors can still be generated and your code has to handle these and with enableReaderMode
you can generate a "failure" sound to prompt the user to represent the Tag or as I do be silent on any error and just retry the write when the Tag is presented again.
enableReaderMode
just provides a more robust and less confusing interaction for the user than enableForegroundDispatch
update:
Have you tried writing 4 chars as the data send must be 4 bytes, you are probably not sending enough data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.