How can I send a text string to another device via NFC?

I want to create a mini app just to read an NFC tag and later send to another device on Android. That part is done already and I can read the tag and I can print the string on a EditText. But I also want to send the text that I have read from that tag to another device with NFC. How can I do that?

//I have this code here when a tag is discovered...
@Override
protected void onNewIntent(Intent intent) {
    if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
        String result = "";
        result = ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
        myTag = result;
        txtTag.setText(myTag);

    }
}

How can I send the text string to another device via NFC?

Upvotes: 5

Views: 10254

Answers (1)

Michael Roland
Michael Roland

Reputation: 40831

What you want to do is simply not possible with Android right no (and probably won't be in future).

You currently read the anti-collision identifier (UID, PUPI, or whatever it is called for that specific tag platform that you read):

result = ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));

The anti-collision identifier is part of a very low protocol layer. While Android does support host-based card emulation (see Android HCE), the Android API has no means to control such low-level parameters as the UID. Typically, its also not possible to change that information on NFC tags.

Note that if your tag also contains some high-level data in NDEF format you could obtain that using:

Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = null;
if ((rawMsgs != null) && (rawMsgs.length > 0)) {
    msg = (NdefMessage)rawMsgs[0];
}
if (msg != null) {
    // do something with the received message
}

Android does support storing these NDEF messages on (writable) NFC tags and it also supports sending NDEF messages to other NFC devices (see Beaming NDEF Messages to Other Devices).

  • E.g. to store an NDEF message on an NFC tag you could use:

    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    Ndef ndef = Ndef.get(tag);
    if (ndef != null) {
        try {
            ndef.connect();
            ndef.writeNdefMessage(msg);
        } finally {
            ndef.close();
        }
    } else {
        NdefFormatable ndefFormatable = NdefFormatable.get(tag);
        if (ndefFormatable != null) {
            try {
                ndefFormatable.connect();
                ndefFormatable.format(message);
            } finally {
                ndefFormatable.close();
            }
        }
    }
    
  • Or in order to send the message to another NFC device through peer-to-peer mode (Android Beam), you could use:

     NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
     nfcAdapter.setNdefPushMessage(msg, this);
    

Upvotes: 3

Related Questions