Android实现读取NFC卡的编号

【Android实现读取NFC卡的编号】本文实例为大家分享了Android读取NFC卡的编号具体代码,供大家参考,具体内容如下
NFC相关androidManifest文件设置:
一、权限:
二、sdk级别限制:
三、特殊功能限制这个生命可以让你的应用在google play上被声明使用者必须拥有nfc功能。


上面的android:resource="@xml/nfc_tech_filter"是对tech类型的过滤条件,在res文件夹新建一个xml文件夹,新建nfc_tech_filter.xml文件。
android.nfc.tech.IsoDepandroid.nfc.tech.NfcAandroid.nfc.tech.NfcBandroid.nfc.tech.NfcFandroid.nfc.tech.NfcVandroid.nfc.tech.Ndefandroid.nfc.tech.NdefFormatableandroid.nfc.tech.MifareClassicandroid.nfc.tech.MifareUltralight

下面是封装了读取NFC卡号的一个类:
class NFCCard { private Activity context; private PendingIntent pendingIntent; private NfcAdapter adapter; private IntentFilter[] intentFilters; private String[][] techLists; private final char[] HEX_EXCHANGE = { '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; public NFCCard(Context context) {this.context = (Activity) context; } void init() { adapter = NfcAdapter.getDefaultAdapter(context); // 创建一个PendingIntent对象,当Android系统扫描到标签时,则会填充到这个对象。pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, context.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED); try {ndef.addDataType("*/*"); } catch (MalformedMimeTypeException e) {throw new RuntimeException("fail", e); }intentFilters = new IntentFilter[] { ndef, }; techLists = new String[][] { new String[] { MifareClassic.class.getName() } }; } public boolean open() {// TODO 打开NfcAdapter,已打开则返回true。应在onResume()中调用if (adapter != null)adapter.enableForegroundDispatch(context, pendingIntent,intentFilters, techLists); return adapter.isEnabled(); } public boolean close() {// TODO 关闭NfcAdapter,已关闭则返回trueif (adapter != null)adapter.disableForegroundDispatch(context); return !adapter.isEnabled(); } public String getId(Intent intent) {// TODO 获取NFC卡的编号。应在onNewIntent()中调用Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); return toHexString(tagFromIntent.getId(), 0,tagFromIntent.getId().length); } private String toHexString(byte[] d, int s, int n) {// TODO 转换为十六进制形式的字符串final char[] ret = new char[n * 2]; final int e = s + n; int x = 0; for (int i = s; i < e; ++i) {final byte v = d[i]; ret[x++] = HEX_EXCHANGE[0x0F & (v >> 4)]; ret[x++] = HEX_EXCHANGE[0x0F & v]; }return new String(ret); }

需要注意的是,上面配置文件中有一个“ android:launchMode="singleTask"”,这是设置应用为单任务。代码中的getId(Intent intent)必须要在Activity的onNewIntent(Intent intent)中执行。因为系统检测到NFC卡的时候,会自动生成封装了相应Tag的Intent,当应用在接收到Intent的时候,默认情况下是启动自己的Activity,这样就会致使每次接收到Intent都会启动新的Activity。把应用设置为单任务后,就可以避免这种情况的发生。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读