Write a NFC message - Android Network

Android examples for Network:NFC Message

Description

Write a NFC message

Demo Code


//package com.java2s;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import android.app.Activity;
import android.app.PendingIntent;

import android.content.IntentFilter;

import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;

public class Main {
    private static boolean mWriteMode = false;
    private static NfcAdapter mNfcAdapter;
    private static PendingIntent mNfcPendingIntent;
    private static IntentFilter[] mWriteTagFilters;
    private static IntentFilter[] mNdefExchangeFilters;
    private static Tag lastDetectedTag = null;
    private static String messageToSend = null;

    public void write(Activity activity) {
        // Write to a tag for as long as the dialog is shown.
        disableNdefExchangeMode(activity);
        enableTagWriteMode(activity);//from w  w  w. j a  v  a 2 s .c om

        //TODO (je crois qu'il n'y a pas besoin de faire ?a, il faut utiliser l'autre truc set...)

        disableTagWriteMode(activity);
        enableNdefExchangeMode(activity);

    }

    /**
     * Write a NFC message with Mifare classic.
     * @param text
     * @throws IOException
     * @throws FormatException
     */
    public static void write(String text) {
        messageToSend = text; //act as a buffer
        if (lastDetectedTag == null) {
            return;
        }

        try {
            NdefRecord[] records = { createRecord(messageToSend) };
            messageToSend = null;

            NdefMessage message = new NdefMessage(records);
            Ndef ndef = Ndef.get(lastDetectedTag);
            ndef.connect();
            ndef.writeNdefMessage(message);
            ndef.close();
        } catch (IOException ioe) {
            System.err.println("IOE : " + ioe.getMessage());
        } catch (FormatException fex) {
            System.err.println("FEX : " + fex.getMessage());
        }
    }

    private static void disableNdefExchangeMode(Activity activity) {
        mNfcAdapter.disableForegroundNdefPush(activity);
        mNfcAdapter.disableForegroundDispatch(activity);
    }

    private void enableTagWriteMode(Activity activity) {
        mWriteMode = true;
        IntentFilter tagDetected = new IntentFilter(
                NfcAdapter.ACTION_TAG_DISCOVERED);
        mWriteTagFilters = new IntentFilter[] { tagDetected };
        mNfcAdapter.enableForegroundDispatch(activity, mNfcPendingIntent,
                mWriteTagFilters, null);
    }

    private void disableTagWriteMode(Activity activity) {
        mWriteMode = false;
        mNfcAdapter.disableForegroundDispatch(activity);
    }

    private static void enableNdefExchangeMode(Activity activity) {
        mNfcAdapter
                .enableForegroundNdefPush(activity, getMessageAsNdef(""));
        mNfcAdapter.enableForegroundDispatch(activity, mNfcPendingIntent,
                mNdefExchangeFilters, null);
    }

    /**
     * Creates a custom MIME type encapsulated in an NDEF record for a given
     * payload
     * 
     * @param mimeType
     */
    public static NdefRecord createRecord(String mimeType, byte[] payload) {
        byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
        NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                mimeBytes, new byte[0], payload);
        return mimeRecord;
    }

    private static NdefRecord createRecord(String text)
            throws UnsupportedEncodingException {

        //create the message in according with the standard
        String lang = "en";
        byte[] textBytes = text.getBytes();
        byte[] langBytes = lang.getBytes("US-ASCII");
        int langLength = langBytes.length;
        int textLength = textBytes.length;

        byte[] payload = new byte[1 + langLength + textLength];
        payload[0] = (byte) langLength;

        // copy langbytes and textbytes into payload
        System.arraycopy(langBytes, 0, payload, 1, langLength);
        System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);

        NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                NdefRecord.RTD_TEXT, new byte[0], payload);
        return recordNFC;
    }

    public static NdefMessage getMessageAsNdef(String message) {
        byte[] textBytes = message.getBytes();
        NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                "text/plain".getBytes(), new byte[] {}, textBytes);
        return new NdefMessage(new NdefRecord[] { textRecord });
    }
}

Related Tutorials