在检测到nfc标记后启动我的应用程序,然后显示结果

6tqwzwtp  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(263)

我已经制作了一个应用程序,它可以读取nfc标记并显示其内容(一旦对其进行了解析),如下所示:https://medium.com/@ssaurel/create-a-nfc-reader-application-for-android-74cf24f38a6f只是我有一个按钮,如果你想扫描一个nfc标签,需要按下这个按钮。
现在,在我的androidmanifest.xml中,我添加了一个意图过滤器,允许在从我的设备检测到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标签的结果。。。如何在我的应用程序打开时获取标签的内容?

wtlkbnrh

wtlkbnrh1#

你需要从启动活动的意图中获得信息。
https://developer.android.com/guide/topics/connectivity/nfc/nfc
如果活动是因为nfc意图而启动的,则可以从该意图获取有关扫描的nfc标记的信息。根据扫描的标记,意图可以包含以下附加内容:

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)

相关问题