首页 > 代码库 > Android -- 读取NFC卡号
Android -- 读取NFC卡号
1. menifest文件中需要添加:
<uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="true" />
在activity中添加:
<intent-filter> <action android:name="android.nfc.action.TAG_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
2. 初始化时代码:
Intent nfcIntent = new Intent(this, getClass()); nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); mPendingIntent = PendingIntent.getActivity(this, 0,nfcIntent , 0); mAdapter = NfcAdapter.getDefaultAdapter(this); if (mAdapter == null) { Toast.makeText(getApplicationContext(), "NFC feature is supported on this device.", Toast.LENGTH_SHORT).show(); return; }
需要Override的函数:
private NfcAdapter mAdapter; private PendingIntent mPendingIntent; @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) protected void onResume() { super.onResume(); mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null); } @Override protected void onNewIntent(Intent intent){ getTagInfo(intent); } @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) private void getTagInfo(Intent intent) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); byte[] tagId = tag.getId(); String str = ByteArrayToHexString(tagId); str = flipHexStr(str); Long cardNo = Long.parseLong(str, 16); String ignoreOperationId = m_operationid; if(m_isOnline){ // if select all , pass in the operation id encoded in ticket // there should NOT be many operations, take the only one new CardValidationAsyncTask().execute(cardNo.toString()); } } @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) @Override protected void onPause() { super.onPause(); if (mAdapter != null) { mAdapter.disableForegroundDispatch(this); } }
以下为helper函数:
private 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(); } private 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" }; String out = ""; for (j = 0; j < inarray.length; ++j) { in = (int) inarray[j] & 0xff; i = (in >> 4) & 0x0f; out += hex[i]; i = in & 0x0f; out += hex[i]; } return out; }
Android -- 读取NFC卡号
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。