卡模拟:将具有NFC功能的设备模拟成一张标签或者非接触卡。
常见的应用场景:读卡、写卡和分享内容。有三种数据过滤器,分别为:ACTION_NDEF_DISCOVERED,ACTION_TECH_DISCOVERED,ACTION_TAG_DISCOVERED。
ACTION_ NDEF_ DISCOVERED:当系统检测到tag中含有NDEF格式的数据时,且系统中有activity声明可以接受包含NDEF数据的Intent的时候,系统会优先发出这个action的intent。
ACTION_ TECH_ DISCOVERED:当没有任何一个activity声明自己可以响应ACTION_NDEF_DISCOVERED时,系统会尝试发出TECH的intent.即便你的tag中所包含的数据是NDEF的,但是如果这个数据的MIME type或URI不能和任何一个activity所声明的想吻合,系统也一样会尝试发出tech格式的intent,而不是NDEF.
ACTION_TAG_DISCOVERED:当系统发现前两个intent在系统中无人会接受的时候,就只好发这个默认的TAG类型。
NFC常见的数据格式(TechList):
android.nfc.tech.IsoDep
android.nfc.tech.NfcA
android.nfc.tech.NfcB
android.nfc.tech.NfcF
android.nfc.tech.NfcV
android.nfc.tech.Ndef
android.nfc.tech.NdefFormatable
android.nfc.tech.MifareUltralight
android.nfc.tech.MifareClassic
在res下新建xml,然后新建一个xxx.xml的文件将上方内容copy即可。然后在AndroidManifest.xml中,添加NFC权限:
后将要做NFC功能的界面的launchMode设置为singleTop类型,然后添加meta-data内容,如下:
android:name=“android.nfc.action.TECH_DISCOVERED” android:resource="@xml/nfc_tech_filter"/> 然后在activity中oncreate和onresume中初始化NFC。 private void initNfc() { defaultAdapter = NfcAdapter.getDefaultAdapter(this); if (null == defaultAdapter) { Toast.makeText(this, “当前设备不支持NFC功能”, Toast.LENGTH_SHORT).show(); return; } try { if (!defaultAdapter.isEnabled()) { Toast.makeText(this, “请打开NFC功能”, Toast.LENGTH_SHORT).show(); return; } } catch (Exception e) { return; } mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0); } 然后重写onNewInstance方法中通过 判断当前具备NFC功能的标签属于那种格式协议的。ndef格式举例: if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) { Log.e("===========", "processIntent:2 "); Tag tag = intent.getParcelableExtra(defaultAdapter.EXTRA_TAG); if (tag == null) return; String[] techList = tag.getTechList(); byte[] id = tag.getId(); tagIdStr = “ID:” + Utils.bytesToHexString(id) + “n”; tagIdStr += “type:” + tag.describeContents() + “n”; boolean is15693 = false; for (String tecj : techList) { tagIdStr += tecj + “n”; if (tecj.equals(“android.nfc.tech.NfcV”)) { is15693 = true; } } }



