问题描述
下面的 readData
方法的目的是返回 NDEF 消息,无论标签支持 NDEF 格式还是“NDEF Formatable”。
class WritableTag (tag: Tag) {
private val NDEF = Ndef::class.java.canonicalName
private val NDEF_FORMATABLE = NdefFormatable::class.java.canonicalName
private val ndef: Ndef?
private val ndefFormatable: NdefFormatable?
val tagId: String?
get() {
if (ndef != null) {
return Tools.byteArrayToHex(ndef.tag.id)
} else if (ndefFormatable != null) {
return Tools.byteArrayToHex(ndefFormatable.tag.id)
}
return null
}
init {
val technologies = tag.techList
val tagTechs = Arrays.asList(*technologies)
if (tagTechs.contains(NDEF)) {
Log.i("WritableTag","contains ndef")
ndef = Ndef.get(tag)
ndefFormatable = null
} else if (tagTechs.contains(NDEF_FORMATABLE)) {
Log.i("WritableTag","contains ndef_formatable")
ndefFormatable = NdefFormatable.get(tag)
ndef = null
} else {
throw FormatException("Tag doesn't support ndef")
}
}
fun readData(): NdefMessage {
if (ndef != null) {
ndef.connect()
if (ndef.isConnected) {
return ndef.ndefMessage
}
} else if (ndefFormatable != null) {
ndefFormatable.connect()
if (ndefFormatable.isConnected) {
return ndefFormatable.ndefMessage // Unresolved reference: ndefMessage
}
}
throw Exception("Cannot read ndef message")
}
}
我可以从 ndefMessage
标签中获取 ndef
,但不能从 ndefFormatable
标签中获取。这怎么可能?
解决方法
由于 ndefFormatable
标记的状态不适合存储 ndefMessage
,因此需要对其进行格式化以存储 ndefMessage
。
无法从 ndefMessage
标签读取 ndefFormatable
,它基本上是一张空白卡,表示如果设置为存储它们,它可以存储 ndefMessage
。
你所能做的就是format
它然后write
一个ndefMessage