How can I make NFC tag scanning happen only in selected activities? Currently, scanning takes place in every activity and every time the phone is applied to the tag. I tried to solve the problem from this link but the application does not turn on at all. Android app enable NFC only for one Activity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.nfc_scanner">
<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.NFC_Scanner"
tools:targetApi="31">
<activity android:name=".MainActivity"
android:exported="true"
tools:ignore="WrongManifestParent">
<intent-filter>
<!-- MAIN represents that it is the Main Activity-->
<action android:name="android.intent.action.MAIN" />
<!-- Launcher Denotes that it will be the first launching activity-->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RentActivity"
tools:ignore="WrongManifestParent">
</activity>
<activity android:name=".AddingCostumesActivity" android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/tech_list" />
</activity>
</application>
<uses-permission android:name="android.permission.NFC"
tools:ignore="ManifestOrder" />
</manifest>
CodePudding user response:
So only the user can actually disable NFC by going to the settings BUT you emulate that by handling NFC in every Activity and just doing nothing when a Tag
is detected in Activities that you want it to look like NFC is disabled.
To do this I would use the better enableReaderMode
API Example as you can also turn off the NFC sound with that API (plus it is more reliable especially for writing and also automatically handles NFC in a non UI thread as per documentation and does not have pause
and resume
your app to send it NFC data).
This is very similar to the answer you linked to but also silences the detection sound.
So remove the manifest filter lines
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/tech_list" />
Implement enableReaderMode
in all Activity classes and if you want to make it look like NFC is disabled then use an onTagDiscovered
method of:-
public void onTagDiscovered(Tag tag) {
}