首页 > 解决方案 > NFC读卡时,会自行打开应用,请问如何解决?

问题描述

当 NFC 读取卡时,它会自行打开应用程序,但我只想在打开此应用程序时读取 NFC

 <activity
            android:name="MyActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustResize">
            <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_intent_filter

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <tech-list>
        <tech>android.nfc.tech.IsoDep</tech>
    </tech-list>
</resources>

标签: androidandroid-studionfcndefcardreader

解决方案


答案是不要将intent-filterand tech-filter 放在清单中,这就是导致 NFC 服务在读取匹配的 NFC 卡时打开您的应用程序的原因。

所以从清单中删除

<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" />

当您的应用程序已经运行并在前台时,只需在您的活动(以及禁用的方法)中使用 nfcAdapter.enableForegroundDispatch甚至更好的 API 来读取 NFC 卡nfcAdapter.enableReaderModeonResumeonPause


推荐阅读