Search code examples
androidnfcnfc-p2p

Send a url between 2 NFC devices


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.


Solution

  • 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).