如何将 NDEF 记录写入 NFC 标签
了解问题
NDEF,或NFC 数据交换格式,用于在 NFC 标签上存储数据。要将 NDEF 记录写入 NFC 标签,您需要:
使用enableReaderMode API写入NDEF记录
之前使用基于Intent的NFC操作的方法引入了限制和用户体验问题。为了解决这些问题,推荐的新方法是使用enableReaderMode API。
此 API 提供对 NFC 读取器的直接控制,允许您:
示例实现
下面是实现此方法的代码片段:
public class NFCActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback { private NfcAdapter mNfcAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nfc); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); } @Override protected void onResume() { super.onResume(); if (mNfcAdapter != null) { Bundle options = new Bundle(); options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250); mNfcAdapter.enableReaderMode(this, this, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NFC_B | NfcAdapter.FLAG_READER_NFC_F | NfcAdapter.FLAG_READER_NFC_V | NfcAdapter.FLAG_READER_NFC_BARCODE | NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS, options); } } @Override public void onTagDiscovered(Tag tag) { Ndef mNdef = Ndef.get(tag); if (mNdef != null) { NdefRecord mRecord = NdefRecord.createTextRecord("en", "English String"); NdefMessage mMsg = new NdefMessage(mRecord); try { mNdef.connect(); mNdef.writeNdefMessage(mMsg); runOnUiThread(() -> { Toast.makeText(getApplicationContext(), "Write to NFC Success", Toast.LENGTH_SHORT).show(); }); try { Uri notification = RingtoneManager. getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } catch (Exception e) { // Handle error playing sound } } catch (Exception e) { // Handle errors } finally { try { mNdef.close(); } catch (Exception e) { // Handle error closing tag } } } } }
此方法可确保更可靠且用户友好的 NFC 书写体验。
以上是如何使用enableReaderMode API将NDEF记录写入NFC标签?的详细内容。更多信息请关注PHP中文网其他相关文章!