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?
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
We have two option to read the nfc card.
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);
}
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With