Search code examples
androidandroid-intentnfcintentfilterforeground-service

Android'd ForegroundDispatch for NFC


What is the purpose of foreground dispatch and how does it differ from adding intent-filters in the AndroidManifest? Currently I can read from and write to NFC tags and I haven't written any foreground dispatch code.


Solution

  • It mostly depends on your requirements. When you register an IntentFilter in the manifest, you specify an Activity that will be started and given the detected tag data in the Intent. This means that your app can be started at any time to handle the tag. For instance, the user can be on the launcher and hold a tag to their phone, and have your app as an option to handle the NFC detection event.

    However, assume you have a scenario where it only makes sense to detect the tag while your application is in the foreground. For instance, maybe your app requires the user to be logged in in order to do something with the tag data. In that case, you can use the foreground dispatch mechanism, and start it from any of your Activity classes to receive a result only when your app is active.

    It's quite similar to BroadcastReceivers, which can also either be something dynamically registered, or specified in the manifest. In the former case, the lifecycle of the receiver is under your control. In the latter case, you're saying that your app may be started at any time.