Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Nfc tags in android?

Tags:

android

nfc

How can i read and display the NDEF messages from NFC tags? Please help me. Can anyone provide the sample source code to read the Nfc tag?

like image 246
Santhosh Avatar asked Dec 04 '22 06:12

Santhosh


2 Answers

1) The general description of the NFC on android is here
2) The NFCDemo is here
3) Very good information are also here
4) Also the book "Programming Android" from "Zigurd Mednieks" has a chapter about the NFC

BR
STeN

like image 115
STeN Avatar answered Dec 28 '22 12:12

STeN


We have two option to read the nfc card.

  1. Read from cache

       Ndef ndef = Ndef.get(tag);
        if (ndef == null) {
            // NDEF is not supported by this Tag. 
            return null;
        }
    
        NdefMessage ndefMessage = ndef.getCachedNdefMessage();
    
        if (ndefMessage == null) {
            mTextView.setText("The tag is empty !");
            return null;
        }
    
        NdefRecord[] records = ndefMessage.getRecords();
        for (NdefRecord ndefRecord : records) {
            if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
                try {
                    return readText(ndefRecord);
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "Unsupported Encoding", e);
                }
            }
        }
    
  2. Read directly by using

public void readFromTag(Intent intent){

    Ndef ndef = Ndef.get(detectedTag);


    try{
        ndef.connect();

        txtType.setText(ndef.getType().toString());
        txtSize.setText(String.valueOf(ndef.getMaxSize()));
        txtWrite.setText(ndef.isWritable() ? "True" : "False");
        Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

        if (messages != null) {
            NdefMessage[] ndefMessages = new NdefMessage[messages.length];
            for (int i = 0; i < messages.length; i++) {
                ndefMessages[i] = (NdefMessage) messages[i];
            }
            NdefRecord record = ndefMessages[0].getRecords()[0];

            byte[] payload = record.getPayload();
            String text = new String(payload);
            txtRead.setText(text);


            ndef.close();

        }
    }
    catch (Exception e) {
        Toast.makeText(getApplicationContext(), "Cannot Read From Tag.", Toast.LENGTH_LONG).show();
    }
}
like image 21
Ranjith Subramaniam Avatar answered Dec 28 '22 12:12

Ranjith Subramaniam