如何实现两台Android 14设备间基于NFC的读写通信?
Android 14设备间NFC直接NDEF通信开发(已实现标签写入功能)
我正在开发一款Android应用,目标是实现两台Android 14设备间基于NFC的直接通信,完成设备间NDEF消息的读写操作。目前已实现向NFC标签写入NDEF消息的功能,核心代码片段如下:
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(); }
内容的提问来源于stack exchange,提问作者Komal
相关产品推荐
相关产品推荐

