如何将ndef记录写入nfc标记?

klh5stk1  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(525)

如何将ndef消息写入nfc标记?我必须更改清单文件吗?到目前为止,我有代码生成ndef消息:

public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    byte[] textBytes = payload.getBytes(utfEncoding);
    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);
    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
            NdefRecord.RTD_TEXT, new byte[0], data);
    return record;
}

如何发现标签?有人能帮我吗?

qacovj5a

qacovj5a1#

所以我会忽略什么谷歌文件阅读https://developer.android.com/guide/topics/connectivity/nfc/nfc 对于读/写https://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc#read-写,因为这提供了一个非常糟糕的用户体验,写标签,并导致许多失败的写,因为用户的行为。
为了使用android可靠地编写nfc,你应该使用更新的更好的 enableReaderMode 应用程序编程接口https://developer.android.com/reference/android/nfc/nfcadapter#enablereadermode(android.app.activity、%20android.nfc.nfcadapter.readercallback、%20int、%20android.os.bundle)
使用这个新的api可以减少很多失败的写入和损坏的卡,因为您可以控制何时发出通知声音。和老人在一起 Intent 基于系统的系统应用程序暂停你的应用程序,然后读取卡片并发出通知声音,然后用户在你的应用程序恢复之前使用卡片方式,并有机会处理卡片数据并写入卡片。
用新的 enableReaderMode 如果您打开系统通知声音,并且您的应用程序从未暂停以读取nfc卡,则您可以读取和写入该卡,然后当您成功写入该卡时,您可以自己发出通知声音。
因为错误是无声的,所以用户会一直尝试出示卡片,直到成功通知。附加的逻辑是不需要每次显示一张卡或显示不同的卡时都向其写入相同的消息。
一些示例代码(改编自我的应用程序,用于nfc低级读写(而非ndef标记技术))

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();
            // Work around for some broken Nfc firmware implementations that poll the card too fast
            options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);

            // Enable ReaderMode for all types of card and disable platform sounds
            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);
    }

   // This method is run in another thread when a card is discovered
   // !!!! This method cannot cannot direct interact with the UI Thread
   // Use `runOnUiThread` method to change the UI from this method
   public void onTagDiscovered(Tag tag) {

      // Read and or write to Tag here to the appropriate Tag Technology type class
      // in this example the card should be an Ndef Technology Type 
      Ndef mNdef = Ndef.get(tag);

      // Check that it is an Ndef capable card
      if (mNdef!= null) {

      // If we want to read
      // As we did not turn on the NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
      // We can get the cached Ndef message the system read for us.

      NdefMessage mNdefMessage = mNdef.getCachedNdefMessage();

      // Or if we want to write a Ndef message

      // Create a Ndef Record
      NdefRecord mRecord = NdefRecord.createTextRecord("en","English String");

      // Add to a NdefMessage
      NdefMessage mMsg = new NdefMessage(mRecord);

      // Catch errors
      try {
          mNdef.connect();
          mNdef.writeNdefMessage(mMsg);

          // Success if got to here
          runOnUiThread(() -> {
             Toast.makeText(getApplicationContext(),
               "Write to NFC Success",
               Toast.LENGTH_SHORT).show();
          });

          // Make a Sound
          try {
              Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
              Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
                  notification);
              r.play();
              } catch (Exception e) {
                 // Some error playing sound
              }

      } catch (FormatException e) {
        // if the NDEF Message to write is malformed
      } catch (TagLostException e) {
        // Tag went out of range before operations were complete
      } catch (IOException e){
        // if there is an I/O failure, or the operation is cancelled
      } finally {
        // Be nice and try and close the tag to
        // Disable I/O operations to the tag from this TagTechnology object, and release resources. 
         try {
                mNdef.close();
             } catch (IOException e) {
               // if there is an I/O failure, or the operation is cancelled
             }
      }

   }

}

相关问题