在 NFC 标签扫描期间,onNewIntent() 内的intent.getAction() 为 null

2024-05-14

这是我第一次使用 NFC 标签。我在清单中声明了 NFC 扫描活动:

    <activity
        android:name=".main.NFCScanActivity"
        android:theme="@android:style/Theme.Holo.Light"
        android:launchMode="singleTop"
        android:exported="true">
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/plain" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.nfc.action.TECH_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <meta-data android:name="android.nfc.action.TECH_DISCOVERED"
            android:resource="@xml/nfc_tech_filter" />
    </activity>

这是 nfc_tech_filter.xml 文件:

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
    <tech>android.nfc.tech.IsoDep</tech>
    <tech>android.nfc.tech.NfcA</tech>
    <tech>android.nfc.tech.NfcB</tech>
    <tech>android.nfc.tech.NfcF</tech>
    <tech>android.nfc.tech.NfcV</tech>
    <tech>android.nfc.tech.Ndef</tech>
    <tech>android.nfc.tech.NdefFormatable</tech>
    <tech>android.nfc.tech.MifareClassic</tech>
    <tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>

每当我扫描标签时,都会调用 onNewIntent() ,但是当我尝试在 onNewIntent 中调用intent.getAction() 时,该值始终为 null。

@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}
private void handleIntent(Intent intent) {
    String action = intent.getAction(); // action here is null
}

当您的应用程序位于前台时想要处理 NFC 时,使用 2 个前台 NFC API 之一更为正常。通常,Manifest NFC 条目仅用于通过 NFC 触发器启动您的应用程序。

enableReaderMode是 2 个前台 NFC Api 中更好、更新的一个还是较旧的enableForegroundDispatch

使用示例启用阅读器模式 https://stackoverflow.com/a/64921434/2373819

如果使用 NFC 的清单条目,您应该真正处理以下内容的返回getIntent你的Activity https://developer.android.com/reference/android/app/Activity#getIntent() in onCreate查看这是否是从 NFC 触发器创建的 Intent。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 NFC 标签扫描期间,onNewIntent() 内的intent.getAction() 为 null 的相关文章

随机推荐