Parses an intent for NDEF messages, returns all that are found - Android Network

Android examples for Network:NFC Message

Description

Parses an intent for NDEF messages, returns all that are found

Demo Code


//package com.java2s;

import java.util.ArrayList;
import java.util.List;

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

import android.os.Parcelable;

public class Main {
    /**/*from w  ww.j av  a  2s.c  o  m*/
     * Parses an intent for NDEF messages, returns all that are found
     * 
     * @param intent
     * @return an empty list if there are no NDEF messages found
     */
    public static List<NdefMessage> getMessagesFromIntent(Intent intent) {
        List<NdefMessage> intentMessages = new ArrayList<NdefMessage>();
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            // Log.i(LOG_TAG, "Reading from NFC " + action);
            Parcelable[] rawMsgs = intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (rawMsgs != null) {
                for (Parcelable msg : rawMsgs) {
                    if (msg instanceof NdefMessage) {
                        intentMessages.add((NdefMessage) msg);
                    }
                }
            } else {
                // Unknown tag type
                byte[] empty = new byte[] {};
                final NdefRecord record = new NdefRecord(
                        NdefRecord.TNF_UNKNOWN, empty, empty, empty);
                final NdefMessage msg = new NdefMessage(
                        new NdefRecord[] { record });
                intentMessages = new ArrayList<NdefMessage>() {
                    {
                        add(msg);
                    }
                };
            }
        }
        return intentMessages;
    }
}

Related Tutorials