Android NFC读卡

发布时间:2024年01月23日
NfcAdapter mNfcAdapter;
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);


  @Override
    protected void onResume() {
        super.onResume();
//        NfcInstance.onResume(MainActivity.this, getContext());
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected, tagDetected, ndefDetected};

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(this);

//        NfcInstance.onPause(MainActivity.this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        patchTag(tag);
        if (tag != null) {
            readFromNFC(tag, intent);
        }
//        NfcInstance.onNewIntent(intent);

    }

    public Tag patchTag(Tag oTag) {
        if (oTag == null)
            return null;

        String[] sTechList = oTag.getTechList();

        Parcel oParcel, nParcel;

        oParcel = Parcel.obtain();
        oTag.writeToParcel(oParcel, 0);
        oParcel.setDataPosition(0);

        int len = oParcel.readInt();
        byte[] id = null;
        if (len >= 0) {
            id = new byte[len];
            oParcel.readByteArray(id);
        }
        int[] oTechList = new int[oParcel.readInt()];
        oParcel.readIntArray(oTechList);
        Bundle[] oTechExtras = oParcel.createTypedArray(Bundle.CREATOR);
        int serviceHandle = oParcel.readInt();
        int isMock = oParcel.readInt();
        IBinder tagService;
        if (isMock == 0) {
            tagService = oParcel.readStrongBinder();
        } else {
            tagService = null;
        }
        oParcel.recycle();

        int nfca_idx = -1;
        int mc_idx = -1;

        for (int idx = 0; idx < sTechList.length; idx++) {
            if (sTechList[idx] == NfcA.class.getName()) {
                nfca_idx = idx;
            } else if (sTechList[idx] == MifareClassic.class.getName()) {
                mc_idx = idx;
            }
        }

        if (nfca_idx >= 0 && mc_idx >= 0 && oTechExtras[mc_idx] == null) {
            oTechExtras[mc_idx] = oTechExtras[nfca_idx];
        } else {
            return oTag;
        }

        nParcel = Parcel.obtain();
        nParcel.writeInt(id.length);
        nParcel.writeByteArray(id);
        nParcel.writeInt(oTechList.length);
        nParcel.writeIntArray(oTechList);
        nParcel.writeTypedArray(oTechExtras, 0);
        nParcel.writeInt(serviceHandle);
        nParcel.writeInt(isMock);
        if (isMock == 0) {
            nParcel.writeStrongBinder(tagService);
        }
        nParcel.setDataPosition(0);
        Tag nTag = Tag.CREATOR.createFromParcel(nParcel);
        nParcel.recycle();

        return nTag;
    }

    private static StringBuilder bytesToString(byte[] bs) {
        StringBuilder s = new StringBuilder();
        for (byte b : bs) {
            s.append(String.format("%02X", b));
        }
        return s;
    }

    private void readFromNFC(Tag tag, Intent intent) {

        try {
            byte[] id1 = tag.getId();
            StringBuffer stringBuffer = new StringBuffer();

            StringBuilder stringBuilder = bytesToString(id1);
            System.out.println("xxxxxxxxx record id1=" + new String(id1) + "stringBuilder=" + stringBuilder.toString());

            List<String> list = new ArrayList<>();

            for (int k = 0; k < 4; k++) {
                list.add(0, String.format("%02X", id1[k]));
            }

            for (int k = 0; k < list.size(); k++) {
                stringBuffer.append(list.get(k));
            }

            System.out.println("xxxxxxxxx record id1=" + new String(id1) + "stringBuffer=" + stringBuffer.toString());

        } catch (Exception e) {

        }
    }

import android.app.Activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.MifareClassic
import android.nfc.tech.NfcA
import android.os.Bundle
import android.os.IBinder
import android.os.Parcel

object NfcInstance {

    lateinit var mNfcAdapter: NfcAdapter

    @JvmStatic
    fun onCreate(context: Context) {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(context)
    }

    @JvmStatic
    fun onResume(activity: Activity, context: Context) {
        if (mNfcAdapter != null) {
            println("xxxxxxxxxxx onResume");
            val tagDetected = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)
            val ndefDetected = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
            val techDetected = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
            val nfcIntentFilter = arrayOf(techDetected, tagDetected, ndefDetected)

            val pendingIntent = PendingIntent.getActivity(
                context, 0, Intent(context, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0
            )
            if (mNfcAdapter != null) mNfcAdapter.enableForegroundDispatch(
                activity,
                pendingIntent,
                nfcIntentFilter,
                null
            )
        } else {
            println("xxxxxxxxxxx onResume null");
        }
    }

    @JvmStatic
    fun onPause(activity: Activity) {
        println("xxxxxxxxxxx onPause");
        if (mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(activity)
    }

    @JvmStatic
    fun onNewIntent(intent: Intent) {
        println("xxxxxxxxxxx onNewIntent");
        if (mNfcAdapter != null) {
            val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            patchTag(tag)
            tag?.let { readFromNFC(it, intent) }
        }
    }

    private fun bytesToString(bs: ByteArray): StringBuilder {
        val s = java.lang.StringBuilder()
        for (b in bs) {
            s.append(String.format("%02X", b))
        }
        return s
    }

    interface OnReadListener {
        fun onRead(value: String, sourceValue: String);
    }

    lateinit var listener: OnReadListener

    @JvmStatic
    fun setOnReadListener(listener: OnReadListener) {
        NfcInstance.listener = listener;
    }

    private fun readFromNFC(tag: Tag, intent: Intent) {
        try {
            val id1 = tag.id
            val stringBuffer = StringBuffer()
            val stringBuilder: StringBuilder = bytesToString(id1)
            println("xxxxxxxxx record id1=" + String(id1) + "stringBuilder=" + stringBuilder.toString())

            var mutableList = mutableListOf<String>()
            var index = 0;
            for (k in id1) {
                if (index < 4) {
                    var temp = String.format("%02X", k)
                    mutableList.add(temp)
                    index++
                    break
                }
            }
            mutableList = mutableList.asReversed();
            for (k in mutableList) {
                stringBuffer.append(k);
            }
            listener.onRead(stringBuffer.toString(), stringBuilder.toString())

            println("xxxxxxxxx record id1=" + String(id1) + "stringBuffer=" + stringBuffer.toString())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun patchTag(oTag: Tag?): Tag? {
        if (oTag == null) return null
        val sTechList = oTag.techList
        val oParcel: Parcel
        val nParcel: Parcel
        oParcel = Parcel.obtain()
        oTag.writeToParcel(oParcel, 0)
        oParcel.setDataPosition(0)
        val len = oParcel.readInt()
        var id: ByteArray? = null
        if (len >= 0) {
            id = ByteArray(len)
            oParcel.readByteArray(id)
        }
        val oTechList = IntArray(oParcel.readInt())
        oParcel.readIntArray(oTechList)
        val oTechExtras = oParcel.createTypedArray(Bundle.CREATOR)
        val serviceHandle = oParcel.readInt()
        val isMock = oParcel.readInt()
        val tagService: IBinder?
        tagService = if (isMock == 0) {
            oParcel.readStrongBinder()
        } else {
            null
        }
        oParcel.recycle()
        var nfca_idx = -1
        var mc_idx = -1
        for (idx in sTechList.indices) {
            if (sTechList[idx] === NfcA::class.java.name) {
                nfca_idx = idx
            } else if (sTechList[idx] === MifareClassic::class.java.name) {
                mc_idx = idx
            }
        }
        if (nfca_idx >= 0 && mc_idx >= 0 && oTechExtras!![mc_idx] == null) {
            oTechExtras[mc_idx] = oTechExtras[nfca_idx]
        } else {
            return oTag
        }
        nParcel = Parcel.obtain()
        nParcel.writeInt(id!!.size)
        nParcel.writeByteArray(id)
        nParcel.writeInt(oTechList.size)
        nParcel.writeIntArray(oTechList)
        nParcel.writeTypedArray(oTechExtras, 0)
        nParcel.writeInt(serviceHandle)
        nParcel.writeInt(isMock)
        if (isMock == 0) {
            nParcel.writeStrongBinder(tagService)
        }
        nParcel.setDataPosition(0)
        val nTag = Tag.CREATOR.createFromParcel(nParcel)
        nParcel.recycle()
        return nTag
    }
}

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

    <tech-list>
        <tech>android.nfc.tech.IsoDep</tech>
    </tech-list>
</resources>

<uses-permission android:name="android.permission.NFC" />

<uses-feature
    android:name="android.hardware.nfc"
    android:required="true" />

<activity
    android:launchMode="singleTask"
    android:name=".choose_role.ChooseRoleActivity"
    android:screenOrientation="landscape">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
        <action android:name="android.nfc.action.TECH_DISCOVERED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <meta-data
        android:name="android.nfc.action.TECH_DISCOVERED"
        android:resource="@xml/nfc_tech_filter" />
</activity>
文章来源:https://blog.csdn.net/qq_17524035/article/details/135763085
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。