← Back to the chapter · Previous detail · Next detail →
Technical detail · NFC Tag Programming
Android NDEF write pattern
Android NFC writing should happen in a foreground workflow where the user intentionally taps a tag while the app is ready to write. The app should check whether the tag already supports NDEF, whether it is writable, whether the message fits, and whether a newly formatted tag is needed.
NdefMessage buildMessage(String assetUrl, String label) {
NdefRecord uri = NdefRecord.createUri(assetUrl);
NdefRecord text = NdefRecord.createTextRecord("en", label);
return new NdefMessage(new NdefRecord[] { uri, text });
}
boolean writeMessage(Tag tag, NdefMessage message) throws Exception {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
try {
if (!ndef.isWritable()) return false;
if (message.toByteArray().length > ndef.getMaxSize()) return false;
ndef.writeNdefMessage(message);
return true;
} finally {
ndef.close();
}
}
NdefFormatable formatable = NdefFormatable.get(tag);
if (formatable == null) return false;
formatable.connect();
try {
formatable.format(message);
return true;
} finally {
formatable.close();
}
}
Use an explicit write state in the UI so the user knows when to hold the tag steady. Handle TagLostException and repeat the write only after the user taps again. Validate the read-back message before showing success. Avoid writing credentials or secrets to NDEF records. Use the tag as a reference to authenticated app or backend policy.