android - 如何检测NFC标签移除事件?

标签 android kotlin callback nfc contactless-smartcard

我开发了一个 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()))

请注意,需要相应地定义nfcAdaptertag。回调函数将在主(UI)线程上调用。

关于android - 如何检测NFC标签移除事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590033/

相关文章:

android - android Spinner 中的数据绑定(bind)错误

java - Android 在使用 Retrofit 多部分上传图像时遇到问题?

android - 如何使用 Kotlin 通过 POST 方法发送 HTTP 请求

android - 是否可以统计我打开谷歌的次数?

android - 在 Android 中处理大型数据库

kotlin - 有官方的Kotlin风格指南吗?

java - Kotlin 获取类型为字符串

node.js - 仅使用一个回调并行运行异步

jquery - 在回调中重新初始化 jquery Accordion

javascript - 防止启动后立即触发停止事件的优雅方法