android - 方法 NdefRecord.createTextRecord ("en", "string") 在 API 级别 21 以下不工作

标签 android nfc backwards-compatibility ndef

当我在装有 Android Lollipop (5.x) 或 Marshmallow (6.0) 的设备上使用时,这段代码工作正常:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public NdefMessage createNdfMessage(String content) {
    NdefRecord record = NdefRecord.createTextRecord("en", content);
    NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
    return msg;
}

但是当我在装有 Android 4.2.2(API 级别 17)的设备上尝试此操作时,我的应用程序崩溃了。我如何使用此代码在低于 21 的 API 级别(这是方法 NdefRecord.createTextRecord 可用的 API 级别)上创建文本记录?

最佳答案

方法 NdefRecord.createTextRecord() 是在 API 级别 21 中引入的。因此,它在低于该 API 级别的平台上不可用。但是,您可以轻松地自己组装文本记录。文本记录的有效负载由状态字节、语言代码字段和文本字段组成:

+-------------+---------------+--------------------------+
| Status byte | Language code | Text                     |
| (1 byte)    | (n byte)      | (m byte)                 |
+-------------+---------------+--------------------------+
  • The status byte indicates the character encoding of the text field (0 = UTF-8, 1 = UTF-16) in bit 7 and the length n of the language code in bits 5..0. Bit 6 must always be zero.
  • The language code filed contains an IANA language code encoded in US-ASCII (e.g. "en").

You could create the Text record using this method:

public static NdefRecord createTextRecord(String language, String text) {
    byte[] languageBytes;
    byte[] textBytes;
    try {
        languageBytes = language.getBytes("US-ASCII");
        textBytes = text.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(e);
    }

    byte[] recordPayload = new byte[1 + (languageBytes.length & 0x03F) + textBytes.length];

    recordPayload[0] = (byte)(languageBytes.length & 0x03F);
    System.arraycopy(languageBytes, 0, recordPayload, 1, languageBytes.length & 0x03F);
    System.arraycopy(textBytes, 0, recordPayload, 1 + (languageBytes.length & 0x03F), textBytes.length);

    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, null, recordPayload);
}

NdefRecord r = createTextRecord("en", content);

关于android - 方法 NdefRecord.createTextRecord ("en", "string") 在 API 级别 21 以下不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37875323/

相关文章:

android - 缺少蓝牙权限 - 但我的应用没有使用它

android - 如何获取对 ConnectivityService 对象的引用?

当我点击第三次点击时,Android TabActivity 会调用 onDestroyView

android - 应用程序关闭时是否可以读取 NFC 标签? - chariotsolutions phonegap-nfc 插件

android - 奇巧 : How to route APDUs to the SIM

node.js - 在 “new Buffer(str)” 和 “Buffer.from(str)” 之间选择

安卓图形 View : setMinX(0) not working and produces negative x axis values

android - 如何通过 NFC 读取信用卡的响应

c# - Protobuf-net 枚举向后兼容性

android - 旧版 Android 操作系统不支持 getSize(),getWidth()/getHeight() 已弃用