Read NFC Tag from Intent - Android Network

Android examples for Network:NFC Tag

Description

Read NFC Tag from Intent

Demo Code


//package com.java2s;

import android.content.Intent;

import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;

import android.nfc.Tag;
import android.nfc.tech.Ndef;

import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class Main {
    private static final String TAG = "NFC Utils";

    public static String lerTag(Intent intent) {
        if (intent != null) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            Ndef ndef = Ndef.get(tag);/*from  ww  w  . j  a v  a  2  s . c  o m*/
            if (ndef == null) {
                return null;
            }

            NdefMessage ndefMessage = ndef.getCachedNdefMessage();

            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);
                    }
                }
            }
        }
        return null;
    }

    private static String readText(NdefRecord record)
            throws UnsupportedEncodingException {
        byte[] payload = record.getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8"
                : "UTF-16";
        int languageCodeLength = payload[0] & 0063;
        return new String(payload, languageCodeLength + 1, payload.length
                - languageCodeLength - 1, textEncoding);
    }
}

Related Tutorials