【问题标题】:Launch my app once NFC tag is detected, then display result检测到 NFC 标签后启动我的应用程序,然后显示结果
【发布时间】:2020-02-13 10:30:14
【问题描述】:

我已经按照本教程创建了一个可以读取 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 标签的结果... 如何在我的应用打开时获取标签的内容?

【问题讨论】:

    标签: java android android-intent nfc


    【解决方案1】:

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

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

    如果 Activity 因 NFC Intent 而启动,您可以从 Intent 中获取有关已扫描 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)
    

    【讨论】:

    • 感谢您的回答!这真的很有帮助也很有趣
    • 当然,但最后我有一个问题啊哈!我只是在“onNewIntent”中放了一个Log.d,当检测到扫描时应用程序启动时他不显示。
    • 您也可以尝试onCreateonResumegetIntent
    • 谢谢!最后一个问题:为什么我的函数 onResume 在 onCreate 之后被调用?这没有意义,对吧?
    • 这是 Activity 生命周期developer.android.com/guide/components/activities/… Activity 经过 onCreate > onResume > onStart > "User Interactions" > onStop > onPause > onDestroy。
    猜你喜欢
    • 2014-12-28
    • 2016-06-05
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多