为什么NFC_TAG即使应用程序关闭也会被发现?

Why NFC_TAG keep discovered even the app closed?

提问人:SenjaKids 提问时间:11/1/2023 最后编辑:Mark RotteveelSenjaKids 更新时间:11/1/2023 访问量:43

问:

我希望我的应用只在特定片段中开始扫描。但目前我的应用程序即使在应用程序关闭时也会继续检测 NFC 标签。如何将其设置为仅扫描特定片段/活动中的 NFC?

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.NFC" />
    <uses-feature
        android:name="android.hardware.nfc"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Testing"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTask"
            android:label="@string/app_name">
            <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.TAG_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>
java android NFC

评论


答:

1赞 Andrew 11/1/2023 #1

请勿使用清单 Intent 过滤器来检测代码,它们现在主要用于在应用未运行/在前台运行时通过 NFC 启动/重启应用。

请改用前台调度方法,例如 (Docs) 和 An Example,该方法仅在应用位于前台时处于活动状态enableReaderMode

此外,NFC 实际上只与 Activity 关联,而不是 Fragments,但您可以使其仅在显示某个 Fragment 时才显示为活动状态。您可以通过检测 Activity 中的标签来执行此操作,但如果未显示正确的 Fragment,则无需对检测到的 Tag 执行任何操作。当显示要处理 NFC 的 Fragment 时,请设置一个 Flag,该 Flag 会更改 Tag 处理代码的行为,以实际执行某些操作。

评论

0赞 SenjaKids 11/2/2023
感谢您的解释和您提供的文档。它真的帮助了我
0赞 Hatem Darwish 11/1/2023 #2

您只需在暂停特定活动时调用此按钮即可。

nfcAdapter.disableForegroundDispatch(getActivity());