第一步:添加NFC权限
<uses-permission android:name="android.permission.NFC"/>
第二步:配置过滤器
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
<action android:name="android.nfc.action.TAG_DISCOVERED" />
</intent-filter>
第三步:初始化NfcAdapter类
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this,"抱歉,不支持NFC功能",Toast.LENGTH_SHORT).show();
}else if (!nfcAdapter.isEnabled()) {
//进入设置菜单
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivity(intent);
}else {
// 操作nfc数据
Toast.makeText(this,"请将带NFC卡片靠近手机背面",Toast.LENGTH_SHORT).show();
pendingIntent = PendingIntent.getActivity(this,0,new Intent(this,this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
}
第四步:获取标签列表
当NFC靠近手机背面的时候,会触发onNewIntent方法
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag != null) {
for(String tech:tag.getTechList()) {
System.out.print(tech);
}
}
}
第五步:onResume()和onPause()的实现代码
@Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this,pendingIntent,TAGFILTERS,TECHLISTS);
}
}
@Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(this);
}
}
通过以上步骤,可以简单的获取到NFC标签的卡片的标签列表信息
附上打印结果:
android.nfc.tech.IsoDep
android.nfc.tech.NfcA
android.nfc.tech.NdefFormatable