如何在安卓系统上读取NFC标签的唯一ID?

问题描述 投票:14回答:3
Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Log.i("tag ID", myTag.getId().toString());

这给了我一个ID,如"[B@40521c40",但这个ID每次读取都会改变。

任何帮助将是非常感激的。

谢谢。

android nfc
3个回答
15
投票

你仍然需要将字节转换为字符串。

private String bytesToHexString(byte[] src) {
    StringBuilder stringBuilder = new StringBuilder("0x");
    if (src == null || src.length <= 0) {
        return null;
    }

    char[] buffer = new char[2];
    for (int i = 0; i < src.length; i++) {
        buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);  
        buffer[1] = Character.forDigit(src[i] & 0x0F, 16);  
        System.out.println(buffer);
        stringBuilder.append(buffer);
    }

    return stringBuilder.toString();
}

6
投票

我也遇到过类似的问题,但可以解决。问题是转换为字符串。

myTag.getId()返回的是字节数组。你应该将这些字节转换为十六进制字符串。我使用了我在stackoverflow.com找到的以下函数

    final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for ( int j = 0; j < bytes.length; j++ ) {
        v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

1
投票

Kotlin

我通过将字节数组ID传递给以下函数来解决这个问题。

private fun ByteArrayToHexString(inarray: ByteArray): String? {
    var i: Int
    var j: Int
    var `in`: Int
    val hex = arrayOf(
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F"
    )
    var out = ""
    j = 0
    while (j < inarray.size) {
        `in` = inarray[j].toInt() and 0xff
        i = `in` shr 4 and 0x0f
        out += hex[i]
        i = `in` and 0x0f
        out += hex[i]
        ++j
    }
    return out
}

这个函数的java源码:https:/gist.github.comluixal5768921。


0
投票
public String getHexValue(final byte[] buffer) {
if (buffer == null || buffer.length == 0) {
    return ("0x" + "[none]");
}

final StringBuffer sb = new StringBuffer();
sb.append("0x");
for (int i = 0; i < buffer.length - 1; i++) {
    sb.append(String.format("%02X%s", buffer[i], ""));
}
sb.append(String.format("%02X", buffer[buffer.length - 1]));

return sb.toString();

}

© www.soinside.com 2019 - 2024. All rights reserved.