我开发了一个 Android 应用程序,用于通过 NFC 在非接触式智能卡上读取/写入。我需要检测卡何时被拉出范围。我尝试使用
NFCAdapter.OnTagRemovedListener{
card_connected2.visibility = View.VISIBLE
card_connectedgreen.visibility = View.GONE
Toast.makeText(this@InquiryActivity, "card is disconnected", Toast.LENGTH_LONG).show()
}
但这似乎是错误的并且不起作用。我还阅读了有关 NfcAdapter.ignore()
的内容,但我找不到任何有关如何使用它的示例。我怎样才能让上面的回调起作用?
最佳答案
OnTagRemovedListener
接口(interface)用于指定 NfcAdapter.ignore()
方法的回调。因此,您需要使用所需的回调调用 ignore()
。例如,如果您想执行上面的代码,并且去抖超时为 1000 毫秒,您可以使用如下内容:
// nfcAdapter: your instance of the NfcAdapter
// tag: the tag handle that you obtained from the NFC intent or the onTagDetected() callback
nfcAdapter.ignore(tag, 1000, NfcAdapter.OnTagRemovedListener {
card_connected2.visibility = View.VISIBLE
card_connectedgreen.visibility = View.GONE
Toast.makeText(this@InquiryActivity, "card is disconnected", Toast.LENGTH_LONG).show()
}, Handler(Looper.getMainLooper()))
请注意,需要相应地定义nfcAdapter
和tag
。回调函数将在主(UI)线程上调用。
关于android - 如何检测NFC标签移除事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590033/