Search code examples
androidnfcnfc-p2pandroid-beam

Android NFC restart App


I use NFC to send text records from my app on device Nr.1 to my app on device Nr.2. Then the device is in touch, on both devices popup "touch to beam" UI. If I touch and beam message on device Nr.1 (sending part ot the pair) - message sent, everything working is just fine. But if I touch "touch to beam" UI on device Nr.2 (which should receive message) - then my app on device Nr. 1 is reloaded. Logcat is show nothing wrong, no errors. Seems, is that case app get some kind of empty NFC message? But why it's just do nothing on that? Why reload? I'm using ForegroundDispatch, create "text/plain" filters programatically, without manifest.

How I can handle this situation, then the users press wrong side of "touch to beam" UI??


Solution

  • If you do not set up Android Beam in your app, Android's default behavior upon beaming is to instruct the other device to either open that same app (first activity that filters for MAIN/LAUNCHER intents of an app with the same package name as the app on the source device), or if your app is not installed, open the Play Store listing. This is done by sending an AAR (+ a Play Store link?) over Beam.

    So in your case, clicking the Beam UI on device 2 causes the AAR to be sent to device 1. As a result, your app will be (re-)opened on device 1. In order to overcome this, you can do the following:

    1. Enable foreground dispatch for the activity on device 1, so that the received NDEF message is immediately processed by your app. I'm not sure if this collides with the Beam UI though.
    2. Change the NDEF message sent by device 2 to something that does not contain an AAR using the Beam API.