将NDEF记录写入NDEF TAGKotlin

bqf10yzr  于 2023-11-21  发布在  Kotlin
关注(0)|答案(1)|浏览(141)

我应该准备一个演示应用程序,它应该读取Ndef记录并将其重写到卡上.我有3个主要功能:readNdef,writeNdef和readTag. readNdef和readTag工作正常.但当我尝试写新的Ndef记录它不能正常工作.它写记录,但改变他们的东西.我使用NdefRecord.createTextRecord方法.这种方法做一些转换.我想写令牌没有任何变化.

private fun readNdef(tag: Tag?) {
        val ndef = Ndef.get(tag)
        try {
            ndef.connect()
            val inNdef = ndef.ndefMessage
            Log.d("fdsfsdfsdf", inNdef.toString())
            val inNdefRecords = ndef.ndefMessage.records
            Log.d("fdsfsdfsdf", inNdefRecords.toString())
            // convert the payload to string and drop 3 characters to get
            // rid of the " en" prefix
            val payload = inNdefRecords[0].payload
            Log.d("fdsfsdfsdf", payload.toString())

            // figure out if we need to take out the " en" at the beginning
            val textEncoding = if (payload[0] and 128.toByte() == 0.toByte()) "UTF-8" else "UTF-16"
            val langCodeLength = payload[0] and 63.toByte()

            // create a string starting by skipping the first 3 characters
            // based on the language code length
            var inMessage = String(
                payload,
                langCodeLength + 1,
                payload.count() - langCodeLength - 1,
                charset(textEncoding)
            )

            // try to convert the message to json
            try {
                val json = inMessage
                Log.d("fdsfsdfsdf", json)
                //val json = JsonParser().parse(inMessage)

                // ... use json or whatever here
            } catch (error: Exception) {
                Log.d(
                    "fdsfsdfsdf",
                    "NFC tag data seems to invalid:\n\n$inMessage\n\n${error.localizedMessage}"
                )
            }

            // ... do whatever
        } catch (error: Exception) {
            Log.d("fdsfsdfsdf", "Error attempting to pull tag info: ${error.localizedMessage}")
        } finally {
            ndef.close()
        }
    }
fun readTag(tag: Tag?) {
        Coroutines.default(this@MainViewModel) {
            readNdef(tag)
            Log.d(TAG, "readTag(${tag} ${tag?.techList})")
            postNFCStatus(NFCStatus.Process)
            val stringBuilder: StringBuilder = StringBuilder()
            val id: ByteArray? = tag?.id
            Log.d("fdsfsdfsdf", "$id")
            stringBuilder.append("Tag ID (hex): ${bytesToHex(id!!)} \n")
            stringBuilder.append("Tag ID (dec): ${getDec(id)} \n")
            stringBuilder.append("Tag ID (reversed): ${getReversed(id)} \n")
            stringBuilder.append("Technologies: ")
            tag.techList.forEach { tech ->
                stringBuilder.append(tech.substring(prefix.length))
                stringBuilder.append(", ")
            }
            stringBuilder.delete(stringBuilder.length - 2, stringBuilder.length)
            tag.techList.forEach { tech ->
                if (tech.equals(MifareClassic::class.java.name)) {
                    stringBuilder.append('\n')
                    val mifareTag: MifareClassic = MifareClassic.get(tag)
                    val type: String
                    if (mifareTag.type == MifareClassic.TYPE_CLASSIC) type = "Classic"
                    else if (mifareTag.type == MifareClassic.TYPE_PLUS) type = "Plus"
                    else if (mifareTag.type == MifareClassic.TYPE_PRO) type = "Pro"
                    else type = "Unknown"
                    stringBuilder.append("Mifare Classic type: $type \n")
                    stringBuilder.append("Mifare size: ${mifareTag.size} bytes \n")
                    stringBuilder.append("Mifare sectors: ${mifareTag.sectorCount} \n")
                    stringBuilder.append("Mifare blocks: ${mifareTag.blockCount}")
                }
                if (tech.equals(MifareUltralight::class.java.name)) {
                    stringBuilder.append('\n');
                    val mifareUlTag: MifareUltralight = MifareUltralight.get(tag);
                    val type: String
                    if (mifareUlTag.type == MifareUltralight.TYPE_ULTRALIGHT) type =
                        "Ultralight"
                    else if (mifareUlTag.type == MifareUltralight.TYPE_ULTRALIGHT_C) type =
                        "Ultralight C"
                    else type = "Unkown"
                    stringBuilder.append("Mifare Ultralight type: ");
                    stringBuilder.append(type)
                }
            }
            Log.d(TAG, "Datum: $stringBuilder")
            Log.d(ContentValues.TAG, "dumpTagData Return \n $stringBuilder")
            postNFCStatus(NFCStatus.Read)
            liveTag.emit("${getDateTimeNow()} \n $stringBuilder")
        }
    }
fun writeNdef(tag: Tag?, context: Context) {
        val ndef = Ndef.get(tag)
        try {
            ndef.connect()
            val textRecord1 = NdefRecord.createTextRecord(
                "en",  // language code (ISO 639-1)
                "00000111111222222333333444444555555AABBEF"
                      //  context.getString(R.string.ndef_rcrd1) // text to send
            )
            val textRecord2 = NdefRecord.createTextRecord(
                "en",  // language code (ISO 639-1)
                "00000111111222222333333444444555555AABBEF"
                      //  context.getString(R.string.ndef_rcrd2) // text to send
            )
            val textRecord3 = NdefRecord.createTextRecord(
                "en",  // language code (ISO 639-1)
                "00000111111222222333333444444555555AABBEF"
                       // context.getString(R.string.ndef_rcrd3) // text to send
            )
            val textRecord4 = NdefRecord.createTextRecord(
                "en",  // language code (ISO 639-1)
                "00000111111222222333333444444555555AABBEF"
                        //context.getString(R.string.ndef_rcrd4) // text to send
            )
            val ndefMessage = NdefMessage(textRecord1, textRecord2, textRecord3, textRecord4)
            ndef.writeNdefMessage(ndefMessage)
            Coroutines.default(this@MainViewModel){
                postNFCStatus(NFCStatus.Write)
            }
            Log.d("fdsfsdfsdf","Edited: ${ndef.ndefMessage}")
        } catch (e: Exception) {
            Log.d("fdsfsdfsdf", "Error write: ${e.localizedMessage}")
        } finally {
            ndef.close()
        }
    }

我想写新的记录没有任何转换。

csga3l58

csga3l581#

不要使用Ndef文本记录格式,因为这会将语言编码添加到记录中。
使用MimeType记录代替MimeMime
例如

// Create Record
val textRecord1 = NdefRecord.createMime(
                "text/plain" // a standard mimeType
                "00000111111222222333333444444555555AABBEF".toByteArray()
            )

// Get String
val payloadString = inNdefRecords[0].payload.toString()

字符串
您可以使用标准的Mime类型(如text/plain)或自定义类型(如yourapp/text
我觉得你应该检查一下炸弹的有效载荷。
例如,检查getTnf()是否为NdefRecord.TNF_MIME_MEDIA

inNdefRecords[0].toMimeType()是您选择使用的mime类型

相关问题