read NFC Tech Card Content - Android Network

Android examples for Network:NFC

Description

read NFC Tech Card Content

Demo Code


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

import android.content.Intent;

import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;

import android.util.Log;

public class Main {
    private static final String TAG = "NfcFilter";

    public static String[] readTechCardContent(Intent intent) {
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        MifareClassic mc = MifareClassic.get(tagFromIntent);
        String[] message = null; 
        int bCount = 0; 
        int bIndex = 0; 
        byte[][] data = null;
        int currentPosition = 4; 

        try {/* w  w  w  .j a v  a 2 s .  c om*/
            mc.connect();
            int sectorCount = mc.getSectorCount(); 
            data = new byte[64][];
            for (int i = 1; i < sectorCount; i++) {
                boolean auth = mc.authenticateSectorWithKeyB(i,
                        MifareClassic.KEY_DEFAULT)
                        || mc.authenticateSectorWithKeyA(bIndex,
                                MifareClassic.KEY_DEFAULT);
                if (auth) {
                    bCount = mc.getBlockCountInSector(i);
                    bIndex = mc.sectorToBlock(i);
                    try {
                        for (int j = 0; j < bCount - 1; j++) {
                            byte[] data1 = mc.readBlock(bIndex);
                            data[currentPosition] = data1;
                            bIndex++;
                        }
                        //                  Log.d(TAG, "index" + bIndex);
                    } catch (IOException e) {
                        Log.e(TAG, "??????????", e);
                    }
                } else {
                    Log.i(TAG, "????????" + i + "??");
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "?NFC??????", e);
        } finally {
            try {
                mc.close();
            } catch (IOException e) {
                Log.e(TAG, "nfc????", e);
            }
        }

        message = new String[data.length];
        for (int i = 0; i < data.length; i++) {
            if (data[i] != null) {
                try {
                    message[i] = new String(data[i], "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }

        return message;
    }
}

Related Tutorials