Android Application Development of NFC Reader-Writer Mode
1. Android NFC 讀寫模式開發
Android Application Development of NFC Reader-Writer Mode
Chun-Kai Wang (王雋凱)
IDSL - Dept. of IM - NTUST
2. NFC Reader/Writer Mode
▪ Description from Android Developers:
▪ “Reader/writer mode, allowing the NFC device to read
and/or write passive NFC tags and stickers.”
2
3. NFC Tags
▪ NFC Tag 用於 NFC 通訊中小資料的互動,可以儲存如 URL、手機號碼
或其他文字資訊。NFC Forum 定義了四種不同的 Tag 類型:
▪ 除了 NFC Forum 定義的 Tag 類型外,其他廠商也提供了其他自訂的私
有 Tag 類型。其中,用的最廣的是 NXP 的 MIFARE Classic Tag。
3
4. Types of NFC Tag
NFC Forum Platform
NXP Specific
Platform
Type 1 Tag Type 2 Tag Type 3 Tag Type 4 Tag
Type MIFARE
Classic Tag
Compatible
Products
Broadcom
Topaz
NXP Mifare
Ultralight, NXP
Mifare
Ultralight C,
NXP NTAG203
Sony FeliCa NXP DESFire /
NXP SmartMX-
JCOP
NXP MIFARE
Classic 1k / NXP
MIFARE Classic
4k / NXP
MIFARE Classic
Mini
Memory Size 96 Bytes 48 Bytes / 144
Bytes
1, 4, 9 KB 4 KB /32 KB 768 Bytes /
3584 Bytes /
192 Bytes
Unit Price Low Low High Medium I High Low
Data Access Read/Write or
Read-Only
Read/Write or
Read-Only
Read/Write or
Read-Only
Read/Write or
Read-Only
Read/Write or
Read-only
4
10. Reading NDEF-formatted Tag
▪ 讀取 NFC Tag 的操作主要包含以下步驟:
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
// 1. 定義 Tag 物件
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// 2. 取得 NDEF Message
// your code in here...
// 3. 解析 NDEF Message
// your code in here...
// 4. 真實資料展示和進一步操作
// your code in here...
}
10
11. Getting NDEF Message from Tag
▪ Android 裝置掃描到的 NFC Tag 資料會以兩種方式儲存在 Intent :
▪ EXTRA_TAG:表示是一個 Tag 型態的物件。
▪ EXTRA_NDEF_MESSAGES:表示是 NDEF 型態的資料。
▪ 以下程式碼先檢查接收到的 Intent 是否為 ACTION_NDEF_DISCOVERED,
然後取出 EXTRA_NDEF_MESSAGES 形式的資料。
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent().getAction())) {
Parcelable[] rawMsgs =
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
}
//process the msgs array
11
12. Parsing NDEF Message
▪ NDEF Message 是由一系列的 Records 所組成。
▪ Records 可以是 MIME-type media、URIs 或 RTDs (Record Type
Definitions) 類型。
12
14. Writing NDEF-formatted Tag
▪ 寫入 NFC Tag 的操作主要包含以下步驟:
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
// 1. 定義 Tag 物件
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// 2. 建立 NDEF Record
// your code in here...
// 3. 建立 NDEF Message (包含一或多個 NDEF Record)
// your code in here...
// 4. 將 NDEF Message 寫入 Tag
// your code in here...
}
14
15. Creating Common Types of NDEF Records
▪ 建立 TNF_ABSOLUTE_URI 型態的 Record:
▪ 建立 TNF_MIME_MEDIA 型態的 Record:
▪ 使用 createMime() 靜態建構函式:
▪ 使用 NdefRecord 建構函式:
15