From a intent received for a NFC event, this method create an intent for another activity/service with the content of the NFC tag. - Android Network

Android examples for Network:NFC Tag

Description

From a intent received for a NFC event, this method create an intent for another activity/service with the content of the NFC tag.

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.Context;
import android.content.Intent;
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;

import android.util.Log;

public class Main {
    public static final String MIME_TEXT_PLAIN = "text/plain";
    public static final String TAG = "NFC";
    public static final String NFC_EXTRA_TAG = "NFCTag";
    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;

    /**/*from w w  w. j a v  a 2s. c  o  m*/
     * From a intent received for a NFC event, this method create an intent for another activity/service with
     * the content of the NFC tag.
     * The NFC type must be NDEF, else it will return NULL.
     * @param intent The intent with NFC info.
     * @param appContext The application context.
     * @param dest The destination service class.
     * @return the intent for the service, or null if not of NDEF type.
     */
    public static Intent reforgeIntent(Intent intent, Context appContext,
            Class<?> dest) {
        Intent outIntent = null;
        String action = intent.getAction();
        System.out.println(":::reforge:::");
        //we must read the message
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            System.out.println("NDEF");
            String type = intent.getType();
            if (MIME_TEXT_PLAIN.equals(type)) {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                lastDetectedTag = tag;
                outIntent = new Intent(appContext, dest);
                outIntent.putExtra(NFC_EXTRA_TAG, tag);
                write(messageToSend);
                return outIntent;
            } else {
                Log.d(TAG, "Wrong mime type: " + type);
            }
            //if tech is discovered instead
        } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
            System.out.println("TECH");
            // In case we would still use the Tech Discovered Intent
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            lastDetectedTag = tag;
            String[] techList = lastDetectedTag.getTechList();
            String searchedTech = Ndef.class.getName();
            for (String tech : techList) {
                if (searchedTech.equals(tech)) {
                    outIntent = new Intent(appContext, dest);
                    outIntent.putExtra(NFC_EXTRA_TAG, tag);
                    write(messageToSend);
                    return outIntent;
                }
            }
        }

        System.out.println("NOT FOUND");
        return outIntent;

    }

    public void write(Activity activity) {
        // Write to a tag for as long as the dialog is shown.
        disableNdefExchangeMode(activity);
        enableTagWriteMode(activity);

        //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