I'm developing an Android app to enable NFC-based communication between two Android 14 devices. The goal is to read and write NDEF messages directly between the devices. I've implemented a method to write NDEF messages to NFC tags, as shown in the code snippet below.
private void writeNdefMessage(Tag tag, String message) {
Ndef ndef = Ndef.get(tag);
NdefRecord record = NdefRecord.createTextRecord("en", message);
NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{record});
try {
if (ndef != null) {
ndef.connect();
if (!ndef.isWritable()) {
runOnUiThread(() -> Toast.makeText(this, "This tag is read-only.", Toast.LENGTH_SHORT).show());
return;
}
ndef.writeNdefMessage(ndefMessage);
runOnUiThread(() -> Toast.makeText(this, "Message written to the tag!", Toast.LENGTH_SHORT).show());
} else {
// Attempt to format the tag
if (formatTag(tag, ndefMessage)) {
runOnUiThread(() -> Toast.makeText(this, "Tag formatted and message written!", Toast.LENGTH_SHORT).show());
} else {
runOnUiThread(() -> Toast.makeText(this, "This tag does not support NDEF and cannot be formatted.", Toast.LENGTH_SHORT).show());
}
}
} catch (IOException | FormatException e) {
runOnUiThread(() -> Toast.makeText(this, "Write failed: " + e.getMessage(), Toast.LENGTH_SHORT).show());
} finally {
try {
if (ndef != null) ndef.close();
} catch (IOException e) {
e.printStackTrace();
}
}
playBeep();
}