NFC call On New Intent - Android Network

Android examples for Network:NFC

Description

NFC call On New Intent

Demo Code


//package com.java2s;
import java.io.IOException;

import android.app.Activity;

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 LOG_TAG = "NfcUtils";
    public static final String TAG = "NFC";

    public static String callOnNewIntent(boolean writeMode, Intent intent,
            Activity activity, String message) {
        // NDEF exchange mode
        if (!writeMode
                && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent
                        .getAction())) {
            NdefMessage[] msgs = getNdefMessages(intent);
            return readNDEFmsg(msgs[0]);
        }//from   www  . ja  v a  2 s.  com

        // Tag writing mode
        if (writeMode
                && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent
                        .getAction())) {
            Tag detectedTag = intent
                    .getParcelableExtra(NfcAdapter.EXTRA_TAG);
            writeTag(activity, getMessageAsNdef(message), detectedTag);
        }

        return null;
    }

    public static NdefMessage[] getNdefMessages(Intent intent) {
        // Parse the intent
        NdefMessage[] msgs = null;
        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 {
                // Unknown tag type
                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 };
            }
        } else {
            Log.d(TAG, "Unknown intent.");
        }
        return msgs;
    }

    public static String readNDEFmsg(final NdefMessage msg) {
        return new String(msg.getRecords()[0].getPayload());
    }

    /**
     * Write an NDEF message to a Tag
     * 
     * @param message
     * @param tag
     * @return true if successful, false if not written to
     */
    public static boolean writeTag(NdefMessage message, Tag tag) {
        int size = message.toByteArray().length;
        try {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();
                if (!ndef.isWritable()) {
                    Log.e(LOG_TAG,
                            "Not writing to tag- tag is not writable");
                    return false;
                }
                if (ndef.getMaxSize() < size) {
                    Log.e(LOG_TAG,
                            "Not writing to tag- message exceeds the max tag size of "
                                    + ndef.getMaxSize());
                    return false;
                }
                ndef.writeNdefMessage(message);
                return true;
            } else {
                NdefFormatable format = NdefFormatable.get(tag);
                if (format != null) {
                    try {
                        format.connect();
                        format.format(message);
                        return true;
                    } catch (IOException e) {
                        Log.e(LOG_TAG, "Not writing to tag", e);
                        return false;
                    }
                } else {
                    Log.e(LOG_TAG, "Not writing to tag- undefined format");
                    return false;
                }
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Not writing to tag", e);
            return false;
        }
    }

    public static boolean writeTag(Activity activity, NdefMessage message,
            Tag tag) {
        int size = message.toByteArray().length;

        try {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();

                if (!ndef.isWritable()) {
                    toast(activity, "Tag is read-only.");
                    return false;
                }
                if (ndef.getMaxSize() < size) {
                    toast(activity, "Tag capacity is " + ndef.getMaxSize()
                            + " bytes, message is " + size + " bytes.");
                    return false;
                }

                ndef.writeNdefMessage(message);
                toast(activity, "Wrote message to pre-formatted tag.");
                return true;
            } else {
                NdefFormatable format = NdefFormatable.get(tag);
                if (format != null) {
                    try {
                        format.connect();
                        format.format(message);
                        toast(activity, "Formatted tag and wrote message");
                        return true;
                    } catch (IOException e) {
                        toast(activity, "Failed to format tag.");
                        return false;
                    }
                } else {
                    toast(activity, "Tag doesn't support NDEF.");
                    return false;
                }
            }
        } catch (Exception e) {
            toast(activity, "Failed to write tag");
        }

        return false;
    }

    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 });
    }

    private static void toast(Activity activity, String text) {
        Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
    }
}

Related Tutorials