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

问题描述 投票:1回答:1

我开发了一款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()的内容,但我找不到任何关于如何使用它的例子。如何才能使上述回调起作用?

android kotlin callback nfc contactless-smartcard
1个回答
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)线程上调用回调函数。

© www.soinside.com 2019 - 2024. All rights reserved.