Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NFC in background

my App already handles WIFI/Bluetooth connect/disconnect in background and performs background tasks based on those events. Now I want to do the same thing with NFC but the all samples I've found so far are starting an activity when NFC tag is discovered.

I already tried to register a receiver for NDEF_DISCOVERED but it was not working...

 <receiver android:name="com.mxp.time.receivers.NfcReceiver" >
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
        </intent-filter>
    </receiver>

Actually I already read that this is not possible because of the fallback stragegy of android. The only solution I found so far is to define an activity without an UI and do polling on the connected tag. I really don't like this technique because it would require to keep this activity open which would cause an increased battery use

Can anyone help me with this?

Cheers, Stefan

like image 620
stefan Avatar asked Jun 23 '26 20:06

stefan


1 Answers

No, that's not possible. NFC on Android was designed as a form of (intentional) user-interaction (and consequently uses user-visible activities). After all, that's what NFC tags are supposed to be used for.

Consequently, android.nfc.action.*_DISCOVERED intents are only sent to activities, they cannot be received though broadcast receivers. So the only possibility to receive them and make it seem to happen in the background is to use an activity without a UI that then forwards these events to your background tasks.

In case of the NDEF_DISCOVERED intent (with associated data), there is typically no need to keep the activity open to perform polling. Instead you could register the activity to be launched upon that specific intent. Btw. as Android is polling for tags anyways while the screen is on, there should not be much difference in battery usage when an activity is registered for receiving NFC events.

like image 191
Michael Roland Avatar answered Jun 26 '26 06:06

Michael Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!