write NFC Tech Tag - Android Network

Android examples for Network:NFC Tag

Description

write NFC Tech Tag

Demo Code


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.os.Parcelable;
import android.util.Log;

public class Main{
    private static final String TAG = "NfcFilter";
    /*from  w  ww.  j a va2s. c o  m*/
    public static boolean writeTechTag(Intent intent, String[] payload) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        MifareClassic mc = MifareClassic.get(tag);

        Charset utfEncoding = Charset.forName("UTF-8");
        byte[][] data = new byte[64][];
        int bIndex = 0; 
        int bCount = 0; 
        int sectorCount = mc.getSectorCount();
        boolean auth = false;
        int currentPosition = 0; 

        for (int i = 0; i < payload.length; i++) {

            payload[i] = StringUtil.addStrLenTo16(payload[i]);
            data[i] = payload[i].getBytes(utfEncoding);
        }

        try {
            mc.close();
            mc.connect();

            for (int i = 1; i < sectorCount; i++) {
                auth = mc.authenticateSectorWithKeyB(i,
                        MifareClassic.KEY_DEFAULT)
                        || mc.authenticateSectorWithKeyA(bIndex,
                                MifareClassic.KEY_DEFAULT);
                if (auth) {
                    bCount = mc.getBlockCountInSector(i);
                    bIndex = mc.sectorToBlock(i);

                    for (int j = 0; j < bCount - 1; j++) {

                        if (data[currentPosition] == null) {
                            break;
                        }
                        mc.writeBlock(bIndex, data[currentPosition]);
                        bIndex++;
                        currentPosition++;
                    }
                }
            }
            return true;
        } catch (IOException e) {
        } finally {
            try {
                mc.close();
            } catch (IOException e) {
            }
        }
        return false;
    }
}

Related Tutorials