0

I have been spending very much time trying to send an url between a samsung galaxy s3 and a nexus s without any success. I have read the API many times. I have tried the example of sending a String with a Ndef message just using copy paste without success. Do they operate on the same protocol since they are running different Android versions? I am targeting API Version 16 and above. My code:

public class MainActivity extends Activity {
    NfcAdapter mNfcAdapter;
    NdefMessage mNdefMessage;
    TextView textView;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         textView = (TextView) findViewById(R.id.textView);
        // Check for available NFC Adapter
         mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
         NdefRecord uriRecord = NdefRecord.createUri(Uri.encode("http://www.google.com/"));
         mNdefMessage = new NdefMessage(new NdefRecord[] { uriRecord });
         mNfcAdapter.setNdefPushMessage(mNdefMessage, this, this);

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

I have tried with callback and without. Neither way works. The other phone does not react at all. I would like it to open a browser with the homepage. Any ideas? Thank you very much!

Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
Hans En
  • 906
  • 5
  • 15
  • 32

1 Answers1

0

That is the code working for me:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // ..
    // only try to set up NFC on API10+
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
        // Check for available NFC Adapter
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null) {
            nfcAdapter.setNdefPushMessage(
                    new NdefMessage(NdefRecord.createUri(Uri.encode("http://www.google.com/"))),
                    this);
        }
    }
}

Note that it's only running on API10+ and only if a NFC is available.

flx
  • 14,146
  • 11
  • 55
  • 70