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

时间:2019-02-08 10:08:02

标签: 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()的内容,但找不到有关如何使用它的任何示例。如何使上述回调起作用?

1 个答案:

答案 0 :(得分:1)

OnTagRemovedListener接口用于指定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)线程上调用。