Matt
Matt

Reputation: 173

Getting the NFC Hardware ID In Android

I want to do something fairly straightforward, but I can't quite work out if the method in the Gingerbread API is for the ID of the token being scanned or the hardware on-board the Nexus S. What I want to be able to do is get the unique identifier of the NFC chip of the device, so I can register it (eg. when the device is waived over an RFID reader, I can associate the device being waived with an account). Is this possible with the current API methods available?

The piece of code that looks most promising (but I can't test because I don't have a device) is

byte[] tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);

Upvotes: 4

Views: 17268

Answers (4)

The incredible Jan
The incredible Jan

Reputation: 906

I'm pretty sure an "unique identifier of the NFC chip of the device" doesn't exist. There is no obvious reason why anybody could need it.

Upvotes: 0

Lior
Lior

Reputation: 7915

The intent NfcAdapter.ACTION_TAG_DISCOVERED will be automatically dispatched by the NFC controller when a tag is discovered.

  1. To handle such intent, you have to add an intent filter for this action android.nfc.action.TAG_DISCOVERED:

    < action android:name="android.nfc.action.TAG_DISCOVERED"/>
    < category android:name="android.intent.category.DEFAULT"/>
    
  2. Add the appropriate permission:

    < uses-permission android:name="android.permission.NFC" />
    
  3. Restrict your application only to supported devices:

    < uses-sdk android:minSdkVersion="9" />  
    < uses-feature android:name="android.hardware.nfc" />
    
  4. When you handle the intent, you can call the code you suggested:

    byte[] tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
    NdefMessage[] msgs = (NdefMessage[]) intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    

For more information visit:

  1. OpenIntents

  2. O'Reilly's online book - Chapter 18

Upvotes: 2

Adam Laurie
Adam Laurie

Reputation: 81

tagId is set to an array of bytes. You need to parse that array to a hex string. There's lots of ways to do that, but this code will do it without resorting to external libraries and it's easy to see what's going on:

String ByteArrayToHexString(byte [] inarray) 
    {
    int i, j, in;
    String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
    String out= "";

    for(j = 0 ; j < inarray.length ; ++j) 
        {
        in = (int) inarray[j] & 0xff;
        i = (in >> 4) & 0x0f;
        out += hex[i];
        i = in & 0x0f;
        out += hex[i];
        }
    return out;
}

Upvotes: 8

Robert
Robert

Reputation: 1266

In version 2.3.3 you have class Tag and if you'll get that object fron intent you can use method getId(),

Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

and if you need tag id from byte[] as "String" you have to parse it from byte to hex ;).

Upvotes: 2

Related Questions