开发者

how do you read the unique ID of an NFC tag on android?

Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Log.i("tag ID", myTag.getId().toString());

This gives me开发者_开发百科 an ID like "[B@40521c40" but this ID changes every read.

Any help would be greatly appreciated.

Thanks.


you still need to convert the byte to string:

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();
}


I ran in to similar issue and could resolve it. The issue is the conversion to string.

myTag.getId() returns byte array. You should convert these bytes to hex string. I used the following function that I found here in 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);
}


Kotlin

I solved this by passing the byte-array ID to following function:

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
}

Source of this function in java: https://gist.github.com/luixal/5768921


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();

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜