zoukankan      html  css  js  c++  java
  • 9、NFC技术:NDEF文本格式解析

    NDEF文本格式规范

          不管什么格式的数据本质上都是由一些字节组成的。对于NDEF文本格式来说。这些数据的第1个字节描述了数据的状态,然后若干个字节描述文本的语言编码,最后剩余字节表示文本数据。这些数据格式由NFC Forum的相关规范定义,可以从下面的地址下载相关的规范。

    http://www.nfc-forum.org/specs/spec_dashboard

    NDEF文本数据格式
    状态字节编码格式
    判断数据是否为NDEF格式

          获取NFC标签中的数据要通过NdefRecord.getPayload方法完成。当然,在处理这些数据之前,最好判断一下NdefRecord对象中存储的是不是NDEF文本格式数据。

    判断的标准有如下两个

     TNF(类型名格式,Type Name Format)必须是NdefRecord.TNF_WELL_KNOWN。

     可变的长度类型必须是NdefRecord.RTD_TEXT。

     
     1 import java.util.Arrays;
     2 import android.nfc.NdefRecord;
     3 
     4 /**
     5  * 将NDEFRecord 文本数据解析出来,生成TextRecord对象
     6  * @author dr
     7  *
     8  */
     9 public class TextRecord {
    10     // 解析出来文本放到该对象中。
    11     private final String mText;
    12 
    13     private TextRecord(String text) {
    14         mText = text;
    15     }
    16 
    17     public String getText() {
    18         return mText;
    19     }
    20 
    21     /**
    22      * 解析 ndefRecord 文本数据
    23      * @param ndefRecord
    24      * @return
    25      */
    26     public static TextRecord parse(NdefRecord ndefRecord) {
    27         // verify tnf   得到TNF的值
    28         if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
    29             return null;
    30         }
    31         // 得到字节数组进行判断
    32         if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
    33             return null;
    34         }
    35 
    36         try {
    37             // 获得一个字节流
    38             byte[] payload = ndefRecord.getPayload();
    39             // payload[0]取第一个字节。 0x80:十六进制(最高位是1剩下全是0)
    40             String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8"
    41                     : "UTF-16";
    42             // 获得语言编码长度
    43             int languageCodeLength = payload[0] & 0x3f;
    44             // 获得语言编码
    45             String languageCode = new String(payload, 1, languageCodeLength,
    46                     "US-ASCII");
    47             //
    48             String text = new String(payload, languageCodeLength + 1,
    49                     payload.length - languageCodeLength - 1, textEncoding);
    50 
    51             return new TextRecord(text);
    52 
    53         } catch (Exception e) {
    54             throw new IllegalArgumentException();
    55         }
    56     }
    57 
    58 }
  • 相关阅读:
    BFS visit tree
    Kth Largest Element in an Array 解答
    Merge k Sorted Lists 解答
    Median of Two Sorted Arrays 解答
    Maximal Square 解答
    Best Time to Buy and Sell Stock III 解答
    Best Time to Buy and Sell Stock II 解答
    Best Time to Buy and Sell Stock 解答
    Triangle 解答
    Unique Binary Search Trees II 解答
  • 原文地址:https://www.cnblogs.com/androidsj/p/3856427.html
Copyright © 2011-2022 走看看