来自 NFC 标签的意外文本

unexpected text from the NFC tag

我是第一次使用 NFC 制作应用程序。 在我的标签中,我有数据 MimeType 记录类型(application/json
数据:"My text" ).

这是我的代码:

private fun processIntent(checkIntent: Intent) {

    if (checkIntent.action == NfcAdapter.ACTION_NDEF_DISCOVERED) {

        // pobieranie wiadomości NDEF z taga NFC
        val rawMessages = checkIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)

        // wiadomość NDEF zawiera wszystkie rekordy z tagu NFC
        var ndefMsg = rawMessages[0] as NdefMessage

        // pojedynczy 1 rekord z tagu NFC ( indeks 0 to 1 rekord, indeks 1 to 2 rekord itd. )
        var ndefRecord = ndefMsg.records[0]

        // jeśli 1 rekord nie jest pusty to pobierz PAYLOAD ( dane ) i wyświetl go
        // jeśli 1 rekord jest pusty wyświetl błąd
        if(ndefRecord.toMimeType() != null)
        {
            Log.v("processIntent", ndefRecord.payload.toString())
            var payload = ndefRecord.payload.toString()


            textView.text = payload
            var i = 2
        }
        else
        {
            Log.e("processIntent", "ERROR A1")
        }

    }
}

在 LogCat 我得到了这个:

V/processIntent: [B@82162f9

我怎样才能用这个(应该是 "My text")发短信?

在这种情况下,ndefRecord.payloadByteArray,因此您看到的是 Object 类型的默认打印输出([B 用于字节数组; @82162f9 为内存地址)。

您需要将其转换为 String。这取决于标签数据的编码方式,这取决于标签创建者。但是,假设它是 UTF-8 或 ASCII,您可以只使用 String 构造函数:

val payloadString = String(ndefRecord.payload, StandardCharsets.US_ASCII)
val payloadString = String(ndefRecord.payload, StandardCharsets.UTF_8)

例如:

if (rawMessages != null) {
    val messages = arrayOfNulls<NdefMessage?>(rawMessages.size)
    for (i in rawMessages.indices) {
        messages[i] = rawMessages[i] as NdefMessage;
    }         
    processNdefMessages(messages)
}

和:

private fun processNdefMessages(ndefMessages: Array<NdefMessage?>) {
    for (curMsg in ndefMessages) {
        if (curMsg != null) {

            logMessage("Message", curMsg.toString())
            logMessage("Records", curMsg.records.size.toString())

            for (curRecord in curMsg.records) {
                if (curRecord.toUri() != null) {
                    logMessage("- URI", curRecord.toUri().toString())
                } else {
                    logMessage("- Contents", curRecord.payload.contentToString())
                }
            }
        }
    }
}