get Ndef Messages - Android Network

Android examples for Network:NFC Message

Description

get Ndef Messages

Demo Code


import android.content.Context;
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.nfc.tech.NdefFormatable;
import android.os.Parcelable;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.logging.Logger;

public class Main{
    private static Logger LOG = Logger.getLogger(NfcUtils.class.getName());
    public static NdefMessage[] getNdefMessages(Intent intent) {
        // Parse the intent
        NdefMessage[] msgs = null;/*  w  w  w.  j  a  v a 2 s  . c o  m*/
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type
                byte[] empty = new byte[] {};
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,
                        empty, empty, empty);
                NdefMessage msg = new NdefMessage(
                        new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };
            }
        } else {
            LOG.severe("Unknown intent.");
        }
        return msgs;
    }
}

Related Tutorials