parse NFC Ndef Msg - Android Network

Android examples for Network:NFC Message

Description

parse NFC Ndef Msg

Demo Code


//package com.java2s;

import java.io.UnsupportedEncodingException;

import java.util.Arrays;

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

public class Main {
    public final static String[] tagInfo = new String[] { "request",
            "ssid", "password" };

    private static String[] parseNdefMsg(NdefMessage nMsg) {

        NdefRecord[] records = nMsg.getRecords();

        String[] text = new String[tagInfo.length];

        int i = 0;

        for (final NdefRecord record : records) {
            //parse...

            if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN
                    && Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) {

                try {

                    if (i >= tagInfo.length)
                        break;

                    byte[] payload = record.getPayload();

                    String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8"
                            : "UTF-16";
                    int languageCodeLength = payload[0] & 0077;
                    String languageCode = new String(payload, 1,
                            languageCodeLength, "US-ASCII");

                    text[i] = new String(payload, languageCodeLength + 1,
                            payload.length - languageCodeLength - 1,
                            textEncoding);

                    i++;//  www .ja v a  2  s  .c o m

                } catch (UnsupportedEncodingException e) {
                    // should never happen unless we get a malformed tag.
                    throw new IllegalArgumentException(e);

                }

            }

        }

        return text;
    }
}

Related Tutorials