3

I have an android application with a webview in it.
When the webview is getting to url with certain text, e.g. ticket, then I would like to send the url to another NFC device through NFC.
I was able to send the url to the type 4 NFC tag, but I am not able to find out how to send it to other NFC device so that it will launch the browser with the url.
I was just using the following to create the NDEF

NdefRecord uriRecord = NdefRecord.createUri(url);
NdefMessage message = new NdefMessage(new NdefRecord[] {
            uriRecord            
});

and then use this to write

ndef.writeNdefMessage(message);

I am writing the app in ICS (on galaxy nexus) and trying to send to the galaxy s2 with 2.3.6.

Any help and pointer will be appreciated.

NFC guy
  • 10,151
  • 3
  • 27
  • 58
DaiLak
  • 746
  • 7
  • 10

1 Answers1

2

When sending an NDEF message to another phone, you don't use a tag read/write API such as Ndef. Instead, your NDEF message is delivered via NFC peer-to-peer. One way to do that is to use setNdefPushMessageCallback in your Activity's onCreate():

    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
    nfc.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback()
    {
        /*
         * (non-Javadoc)
         * @see android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage(android.nfc.NfcEvent)
         */
        @Override
        public NdefMessage createNdefMessage(NfcEvent event) 
        {
            NdefRecord uriRecord = NdefRecord.createUri(Uri.encode("http://www.google.com/"));
            return new NdefMessage(new NdefRecord[] { uriRecord });
        }

    }, this, this);  

The callback will be called when another NFC device comes near and a peer-to-peer connection is established. The callback then creates the NDEF message to be sent (in your case: the URL displayed in the webview).

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
NFC guy
  • 10,151
  • 3
  • 27
  • 58
  • Thank you, it works! I did find that the "connection" is kind of unstable between galaxy nexus 4.04 and galaxy S2 2.36. But in general, i was able to transfer the url. – DaiLak Mar 22 '12 at 19:28
  • You want to experiment somewhat with positioning the devices vertically relative to each other so the NFC antennas line up properly. – NFC guy Mar 22 '12 at 19:53
  • but how do you send multiple messages without disconnecting? – Pittfall Apr 24 '13 at 18:46
  • You can't :( That is a current limitation of the Android API, unfortunately. – NFC guy Apr 25 '13 at 10:16
  • @Pittfall you can only send one NdefMessage but it can contain multiple NDEF records. Maybe that helps... http://developer.android.com/reference/android/nfc/NdefMessage.html#NdefMessage(android.nfc.NdefRecord[]) – leo9r Sep 21 '13 at 10:03
  • setNdefPushMessageCallback is depracated – Dživo Jelić Jun 18 '22 at 10:48