简介
将 NDEF 记录写入 NFC 标签需要Android 中采用不同的方法来确保可靠性并避免写入失败。较旧的基于 Intent 的系统经常会因读取中断和无提示错误而导致问题。
使用enableReaderMode API
较新的enableReaderMode API 提供了更强大的方法。它禁用系统通知,允许您的应用程序控制声音的时间并有效地处理读/写过程。通过这样做,您可以最大限度地减少写入失败和数据损坏。
示例代码
以下 Java 代码片段演示了如何使用enableReaderMode API:
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); // Rest of Activity setup } @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 protected void onPause() { super.onPause(); if(mNfcAdapter!= null) mNfcAdapter.disableReaderMode(this); } @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(); }); Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } catch (Exception e) { // Handle errors } finally { try { mNdef.close(); } catch (IOException e) { // Handle I/O failure or cancelled operation } } } } }
额外注意
以上是如何使用Android的enableReaderMode API将NDEF记录写入NFC标签?的详细内容。更多信息请关注PHP中文网其他相关文章!