Android Kotlin - 如何在 Activity 中读取 NFC 标签

Tob*_*Alt 4 android nfc kotlin ndef

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

我想要实现的是,只有我当前的活动是以文本/纯格式从 NFC 标签读取 NDEF 消息。

所以第一个问题:是否有必要在我的清单中列出意图过滤器?

<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />

<category android:name="android.intent.category.DEFAULT" />

<data android:mimeType="text/plain" />
Run Code Online (Sandbox Code Playgroud)

我认为这是没有必要的,因为我不想通过NFC 标签事件启动我的应用程序,对吗?

第二个问题:如何保持 NFC 读取逻辑/功能与我的应用程序/活动相关?

<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
Run Code Online (Sandbox Code Playgroud)

我转到当前的 Activity 并在 Create 时初始化 NFC 适配器:

mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
Run Code Online (Sandbox Code Playgroud)

读取 nfc 标签 NDEF 消息的下一步是什么?在调度前台发现与意图相关的内容:

 @Override
protected void onNewIntent(Intent intent) { 

    handleIntent(intent);
}
Run Code Online (Sandbox Code Playgroud)

如果有人有一个想法/示例(Kotlin)如何从活动中读取 NFC 标签而不需要启动/发送 NFC 操作之类的东西,那就太好了。

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

kco*_*ock 5

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

如果您只寻找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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)