get NFC Ndef Messages from Intent - Android Network

Android examples for Network:NFC Message

Description

get NFC Ndef Messages 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.os.Parcelable;

public class Main {
    public static NdefMessage[] getNdefMessages(Intent intent) {
        NdefMessage[] msgs = null;/*from   ww w .ja v a  2s  .  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 {
                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 };
            }
        }
        return msgs;
    }
}

Related Tutorials