我在这里找到了一些关于使用 Android 读取 NFC 标签的最新帖子。 我得到的结论是,执行 NFC 读取操作会触发分离的 Intent 。
我想要实现的是,只有我当前的 Activity 是以文本/纯格式从 NFC 标签读取 NDEF 消息。
那么第一个问题: 是否有必要在我的 list 中列出 intent-filter?
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
我认为这不是必需的,因为我不想想通过 NFC 标签事件启动我的应用,对吧?
第二个问题:如何让我的 NFC 读取逻辑/功能与我的应用/Activity 相关?
之后
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
我转到我当前的 Activity 并在创建时初始化 NFC 适配器:
mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
读取 nfc 标签 NDEF 消息的下一步是什么? 在 dispatch 前台发现了一些与 intent 相关的东西:
@Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
如果有人有想法/示例(Kotlin)如何读取 NFC 标签,那就太好了 来自 没有诸如启动/发送 NFC 操作之类的 Activity 。
在 iOS 中,例如在 VC 中需要时有一个简单的 NFC session 。
最佳答案
正确,如果您只想在 Activity
处于前台时接收标签,您可以在运行时注册。您正在寻找的是 NfcAdapter
上的 enableForegroundDispatch
方法。您可以为要过滤的特定类型的标签注册一个 PendingIntent
,您的 Activity
将在 onNewIntent 中收到一个
每当检测到标签时。 Intent
()
如果您只寻找 IsoDep
兼容的 NFC 标签,Kotlin 中的一个简单示例会是什么样子:
override fun onResume() {
super.onResume()
NfcAdapter.getDefaultAdapter(this)?.let { nfcAdapter ->
// An Intent to start your current Activity. Flag to singleTop
// to imply that it should only be delivered to the current
// instance rather than starting a new instance of the Activity.
val launchIntent = Intent(this, this.javaClass)
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
// Supply this launch intent as the PendingIntent, set to cancel
// one if it's already in progress. It never should be.
val pendingIntent = PendingIntent.getActivity(
this, 0, launchIntent, PendingIntent.FLAG_CANCEL_CURRENT
)
// Define your filters and desired technology types
val filters = arrayOf(IntentFilter(ACTION_TECH_DISCOVERED))
val techTypes = arrayOf(arrayOf(IsoDep::class.java.name))
// And enable your Activity to receive NFC events. Note that there
// is no need to manually disable dispatch in onPause() as the system
// very strictly performs this for you. You only need to disable
// dispatch if you don't want to receive tags while resumed.
nfcAdapter.enableForegroundDispatch(
this, pendingIntent, filters, techTypes
)
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (NfcAdapter.ACTION_TECH_DISCOVERED == intent.action) {
val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
IsoDep.get(tag)?.let { isoDepTag ->
// Handle the tag here
}
}
}
关于Android Kotlin - 如何读取 Activity 内的 NFC 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52763896/