检测到 NFC 标签后启动我的应用程序,然后显示结果

Launch my app once NFC tag is detected, then display result

我已经按照本教程制作了一个可以读取 NFC 标签并显示其内容(一旦他被解析)的应用程序:https://medium.com/@ssaurel/create-a-nfc-reader-application-for-android-74cf24f38a6f 除了我有一个需要按下的按钮,如果你想要扫描 NFC 标签。

现在,在我的 AndroidManifest.xml 中,我添加了一个 intent 过滤器,以允许我的应用程序在从我的设备检测到 NFG 标签时启动:

    <activity android:name=".MainActivity" android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="http" />
            <data android:scheme="https" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="application/vnd.com.example" />
        </intent-filter>
        <meta-data android:name="android.nfc.action.TECH_DISCOVERED"
            android:resource="@xml/nfc_tech_filter" />
    </activity>

它启动了我的应用程序,但没有任何反应。我的意思是,我没有关于 NFC 标签的结果...... 如何在我的应用程序打开时获取标签的内容?

您需要从启动 Ativity 的 Intent 中获取信息。

https://developer.android.com/guide/topics/connectivity/nfc/nfc

If an activity starts because of an NFC intent, you can obtain information about the scanned NFC tag from the intent. Intents can contain the following extras depending on the tag that was scanned:

EXTRA_TAG (required): A Tag object representing the scanned tag.
EXTRA_NDEF_MESSAGES (optional): An array of NDEF messages parsed from the tag. This extra is mandatory on ACTION_NDEF_DISCOVERED intents.
EXTRA_ID (optional): The low-level ID of the tag.

所以:

override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    ...
    if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) {
        intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)?.also { rawMessages ->
            val messages: List<NdefMessage> = rawMessages.map { it as NdefMessage }
            // Process the messages array.
            ...
        }
    }
}

val tag: Tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)