Skip to content

Instantly share code, notes, and snippets.

@pjwelcome
Created July 26, 2017 18:42
Show Gist options
  • Save pjwelcome/09aa1d64af307f0b49135e0b48fe634a to your computer and use it in GitHub Desktop.
Save pjwelcome/09aa1d64af307f0b49135e0b48fe634a to your computer and use it in GitHub Desktop.
private fun writeMessageToTag(nfcMessage: NdefMessage, tag: Tag?): Boolean {
try {
val nDefTag = Ndef.get(tag)
nDefTag?.let {
it.connect()
if (it.maxSize < nfcMessage.toByteArray().size) {
//Message to large to write to NFC tag
return false
}
if (it.isWritable) {
it.writeNdefMessage(nfcMessage)
it.close()
//Message is written to tag
return true
} else {
//NFC tag is read-only
return false
}
}
val nDefFormatableTag = NdefFormatable.get(tag)
nDefFormatableTag?.let {
try {
it.connect()
it.format(nfcMessage)
it.close()
//The data is written to the tag
return true
} catch (e: IOException) {
//Failed to format tag
return false
}
}
//NDEF is not supported
return false
} catch (e: Exception) {
//Write operation has failed
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment