From 714060093b3e7a40d5346a83b067b598c1987265 Mon Sep 17 00:00:00 2001 From: Jay Newstrom Date: Tue, 22 Sep 2020 21:06:12 -0500 Subject: [PATCH] Write application record to NFC tags. (#969) * Write application record to NFC tags. Relates to #876 This fixes an issue where on certain devices a dialog was showing up when scanning the NFC tags. After this change, scanned NFC tags go directly into the home assistant android companion app. I also tested on an iOS device to ensure the written NFC tag is correctly read. * Add fallback to old version if the message is too large. --- .../companion/android/nfc/NFCUtil.kt | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/io/homeassistant/companion/android/nfc/NFCUtil.kt b/app/src/main/java/io/homeassistant/companion/android/nfc/NFCUtil.kt index e65f347ef..a73a1c789 100644 --- a/app/src/main/java/io/homeassistant/companion/android/nfc/NFCUtil.kt +++ b/app/src/main/java/io/homeassistant/companion/android/nfc/NFCUtil.kt @@ -10,16 +10,19 @@ import android.nfc.NfcAdapter import android.nfc.Tag import android.nfc.tech.Ndef import android.nfc.tech.NdefFormatable +import io.homeassistant.companion.android.BuildConfig import java.io.IOException object NFCUtil { @Throws(Exception::class) fun createNFCMessage(url: String, intent: Intent?): Boolean { val nfcRecord = NdefRecord.createUri(url) - val nfcMessage = NdefMessage(arrayOf(nfcRecord)) + val applicationRecord = NdefRecord.createApplicationRecord(BuildConfig.APPLICATION_ID) + val nfcMessage = NdefMessage(arrayOf(nfcRecord, applicationRecord)) + val nfcFallbackMessage = NdefMessage(arrayOf(nfcRecord)) intent?.let { val tag = it.getParcelableExtra(NfcAdapter.EXTRA_TAG) - return writeMessageToTag(nfcMessage, tag) + return writeMessageToTag(nfcMessage, nfcFallbackMessage, tag) } return false } @@ -42,17 +45,25 @@ object NFCUtil { } @Throws(Exception::class) - private fun writeMessageToTag(nfcMessage: NdefMessage, tag: Tag?): Boolean { + private fun writeMessageToTag( + nfcMessage: NdefMessage, + fallbackMessage: NdefMessage, + tag: Tag? + ): Boolean { val nDefTag = Ndef.get(tag) nDefTag?.let { it.connect() + var messageToWrite = nfcMessage if (it.maxSize < nfcMessage.toByteArray().size) { + messageToWrite = fallbackMessage + } + if (it.maxSize < fallbackMessage.toByteArray().size) { // Message to large to write to NFC tag throw Exception("Message is too large") } return if (it.isWritable) { - it.writeNdefMessage(nfcMessage) + it.writeNdefMessage(messageToWrite) it.close() // Message is written to tag true