Activity里面的核心代码:
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
@Override
public void onNewIntent(Intent intent) {
{
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Log.d("content",readTag(tagFromIntent));
}
}
/**
* 启动Activity,界面可见时
*/
@Override
protected void onStart() {
super.onStart();
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
//一旦截获NFC消息,就会通过PendingIntent调用窗口
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
}
/**
* 获得焦点
*/
@Override
public void onResume() {
super.onResume();
//设置处理优于所有其他NFC的处理
if (mNfcAdapter != null)
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
/**
* 暂停Activity,界面获取焦点
*/
@Override
public void onPause() {
super.onPause();
//恢复默认状态
if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
}
其中用到的核心方法readTag()来自我的工具类MyNfcUtil,最后添加权限即可,
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
使用tag.getTechList()的获取安卓设备的NFC功能能够支持的Tag标签类型:
android.nfc.tech.NfcA
android.nfc.tech.MifareClassic
android.nfc.tech.NdefFormatable
我的手机只支持以上三种类型, 其中MifareClassic也称M1卡,正好我手里有这种卡,使用安卓设备读取获得卡的id为byte[]数组,转换为十六进制,然后转换为十进制,为0094319031,不足十位补0,这就是我最后需要使用的卡片ID。
总结:使用安卓设备NFC读取标签信息过程如下:在Activity里面重写相应的方法,进行开启关闭NFC的相关操作,然后调用我的工具类MyNfcUtil来获取标签信息,最后在配置文件里面添加NFC权限即可。
最后介绍一个NFC读取MifareClassic标签的项目,传送门,据说是个老外搞的,参考下。
源码地址http://download.youkuaiyun.com/download/zhangxiangliang2/9995799