从NFC标签读取数据

4

可能是重复问题:
Android NDEF记录负载上的奇怪字符

我正在尝试从NFC标签读取一些纯文本。我的代码如下:

public void processReadIntent(Intent intent){

    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
            NfcAdapter.EXTRA_NDEF_MESSAGES);

    NdefMessage msg = (NdefMessage) rawMsgs[0];
    // record 0 contains the MIME type, record 1 is the AAR, if present
    Log.d("msg", msg.getRecords()[0].getPayload().toString());

    String PatientId=new String(msg.getRecords()[0].getPayload());     
    String UserName="nurse";
    String Password="nurse";

   Toast.makeText(getApplicationContext(), PatientId, Toast.LENGTH_LONG).show();

    //tv.setText(new String(msg.getRecords()[0].getPayload()));
}

但是,我读取数据时发现我的目标数据以“en”开头,这是个问题。
例如:如果我的真实数据是“John”,在读取时会看到它被显示成“enjohn”。
我知道“en”是语言首部。但是,我该如何去掉它呢?
我尝试使用子字符串,但是之后仍然无法工作...
你有任何关于如何去掉这个语言头的想法吗?
1个回答

9
也许你也有这里所述的问题,并且想要了解如何正确读取NFC标签,可以参考这里。以下内容摘自第二个链接。
 try
{
        byte[] payload = record.getPayload();

        /*
     * payload[0] contains the "Status Byte Encodings" field, per the
     * NFC Forum "Text Record Type Definition" section 3.2.1.
     *
     * bit7 is the Text Encoding Field.
     *
     * if (Bit_7 == 0): The text is encoded in UTF-8 if (Bit_7 == 1):
     * The text is encoded in UTF16
     *
     * Bit_6 is reserved for future use and must be set to zero.
     *
     * Bits 5 to 0 are the length of the IANA language code.
     */

         //Get the Text Encoding
        String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";

        //Get the Language Code
        int languageCodeLength = payload[0] & 0077;
        String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        //Get the Text
        String text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

    return new TextRecord(text, languageCode);
}
catch(Exception e)
{
        throw new RuntimeException("Record Parsing Failure!!");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接