Android Kotlin - 如何读取内部的 NFC 标签 Activity

Android Kotlin - How to read NFC tag inside Activity

我在这里找到了一些关于使用 Android 读取 NFC 标签的最新帖子。 我得到的结论是,执行 NFC 读取操作会触发分离的意图。

我想要实现的是只有我当前的activity正在从text/plain格式的NFC标签读取NDEF消息。

那么第一个问题: 是否有必要在我的清单中列出 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 读数 logic/functions 与我的 app/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);
}

如果有人知道 idea/example (Kotlin) 如何读取 NFC 标签就好了 来自 activity 没有 诸如 launching/beaming NFC 动作之类的东西。

在 iOS 例如VC 中需要时有一个简单的 NFC 会话。

正确,如果您只想在 Activity 处于前台时接收标签,您可以在运行时注册。您正在寻找的是 NfcAdapter 上的 enableForegroundDispatch 方法。您可以为要过滤的特定类型的标签注册 PendingIntent,只要检测到标签,您的 Activity 就会在 onNewIntent() 中收到 Intent

Kotlin 中的一个简单示例,如果您只寻找 IsoDep 兼容的 NFC 标签,它会是什么样子:

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
        }
    }
}