create NFC Ndef Msg - Android Network

Android examples for Network:NFC Message

Description

create NFC Ndef Msg

Demo Code


import java.io.IOException;
import java.lang.reflect.Constructor;
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 android.util.Log;
import android.widget.Toast;

public class Main{
    private static final String TAG = "NFCUtil";
    private static final String DELIMETER = "-";
    public static NdefMessage createNdefMsg(int[] mGameMatrix) {
        NdefMessage ndefMsg = getIntArrayAsNdef(
                NdefRecord.TNF_MIME_MEDIA, "state/data", "", mGameMatrix,
                DELIMETER);//from w  w  w.ja  v a  2s  . co  m
        return ndefMsg;
    }
    public static NdefMessage createNdefMsg(int[] mGameMatrix,
            NdefRecord AAR) {
        NdefMessage ndefMsg = getIntArrayAsNdef(
                NdefRecord.TNF_MIME_MEDIA, "state/data", "", mGameMatrix,
                DELIMETER, AAR);

        return ndefMsg;
    }
    public static NdefMessage getIntArrayAsNdef(short tnf, String type,
            String id, int[] payload, String delimiter) {
        byte[] idBytes = id.getBytes();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < payload.length - 1; i++) {
            sb.append(payload[i] + "-");
        }
        sb.append(payload[payload.length - 1] + "");

        Log.d(TAG, "Payload for ndefmsg = " + sb.toString());

        byte[] payloadBytes = sb.toString().getBytes();
        byte[] typeBytes = type.getBytes();
        NdefRecord textRecord = new NdefRecord(tnf, typeBytes, idBytes,
                payloadBytes);
        return new NdefMessage(new NdefRecord[] { textRecord });
    }
    public static NdefMessage getIntArrayAsNdef(short tnf, String type,
            String id, int[] payload, String delimiter, NdefRecord AAR) {
        byte[] idBytes = id.getBytes();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < payload.length - 1; i++) {
            sb.append(payload[i] + "-");
        }
        sb.append(payload[payload.length - 1] + "");

        Log.d(TAG, "Payload for ndefmsg = " + sb.toString());

        byte[] payloadBytes = sb.toString().getBytes();
        byte[] typeBytes = type.getBytes();
        NdefRecord textRecord = new NdefRecord(tnf, typeBytes, idBytes,
                payloadBytes);
        return new NdefMessage(new NdefRecord[] { textRecord, AAR });
    }
}

Related Tutorials