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.csdn.net/download/zhangxiangliang2/9995799