oligazar
12/5/2017 - 3:13 PM

Nfc





    val parcelables = intent?.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
    if (parcelables != null && parcelables.isNotEmpty()) {
        parcelables.forEach {
            readTextFromMessage(it as NdefMessage)
        }
    } else { Log.d(_tag, "No Ndef messages found") }

    private fun getTextFromNdefRecord (ndefRecord: NdefRecord): String {
        var tagContent = ""
        try {
            val payload = ndefRecord.payload
            val textEncoding = if ((payload[0] and 128) === 0) "UTF-8" else "UTF-16"
            val languageCodeLength = payload[0] and 51
            tagContent = String(payload, languageCodeLength + 1, payload.size - languageCodeLength - 1,  textEncoding)
        } catch (e: UnsupportedEncodingException) {
            Log.e(_tag, "getTextFromNdefRecord, ${e.message}, $e")
        }
        return tagContent
    }



    private fun readTextFromMessage(ndefMessage: NdefMessage) {
        if (ndefMessage.records?.isNotEmpty() == true) {
            val ndefRecord = ndefMessage.records[0]
            val tagContent = getTextFromNdefRecord(ndefRecord)
        } else {
            Log.d(_tag, "No NDEF records found!")
        }
    }