Android NFC 读取 卡片ID

欢迎


首先

你需要一个权限

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

其次

初始化适配器 NfcAdapter PendingIntent

    Intent nfcIntent = new Intent(this, getClass());
    nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    mPendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
    String infoText = "看下这个支持nfc吗 或者 开了没";
    if (mAdapter == null) {
        Toast.makeText(getApplicationContext(), infoText, Toast.LENGTH_SHORT).show();
        }   

之后

重写onNewIntent()方法

   @Override
    protected void onNewIntent(Intent intent) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //获取 Tag 读取 ID 得到字节数组  转字符串 转码  得到卡号(默认16进制 这请自便)
        Long cardNo = Long.parseLong(flipHexStr(ByteArrayToHexString(tag.getId())), 16);
//        if (cardNo.toString().getBytes().length == 10) {
        num = cardNo.toString();
//        } else {
//        转的时候有个地方需要注意下 如果开头为零的话 会省略所以位数会改变
//            num = "0" + cardNo.toString();
//        }

        TextView textView = (TextView) findViewById(R.id.nfc_text);
        textView.setText(num);
        Toast.makeText(getApplicationContext(), num, Toast.LENGTH_SHORT).show();
    }

最后

息屏之类的操作


    @Override
    public void onPause() {
        super.onPause();
        if (mAdapter != null) {
            mAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
    }

差点忘了有个转码工具类 结束

package com.example.wwb.mynfctext;

/**
 * Created by wwb on 2017/6/5 0005.
 * for:不记得从哪复制过来的helper函数
 */

public class ByteArrayTohexHepler {

    public static String flipHexStr(String s) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i <= s.length() - 2; i = i + 2) {
            result.append(new StringBuilder(s.substring(i, i + 2)).reverse());
        }
        return result.reverse().toString();
    }

    // 16转10进制
    public static String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F"};
        StringBuilder out = new StringBuilder();


        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out.append(hex[i]);
            i = in & 0x0f;
            out.append(hex[i]);
        }
        return out.toString();
    }
}



仅作记录,关于nfc这块刷卡 适用范围挺广的 市面上还有一些近场通信模块可以DIY 也有简单的即插即用 且行且珍惜 自勉

猜你喜欢

转载自blog.csdn.net/qq_29578485/article/details/79195234