本文說明進階 NFC 主題,例如使用各種標記技術、寫入 NFC 標記,以及前景調度,讓前景中的應用程式即使在其他應用程式篩選相同意圖時,也能處理意圖。
使用支援的代碼技術
使用 NFC 標記和 Android 裝置時,您在標記上讀取和寫入資料的主要格式是 NDEF。當裝置掃描含有 NDEF 資料的標記時,Android 會提供剖析訊息的支援,並盡可能在 NdefMessage 中傳送訊息。不過,有時掃描的標記不含 NDEF 資料,或 NDEF 資料無法對應至 MIME 類型或 URI。在這種情況下,您必須直接與標記建立通訊,並使用自己的通訊協定 (以原始位元組為單位) 讀取及寫入標記。Android 透過 android.nfc.tech 套件為這些用途提供一般支援,如表 1 所示。您可以使用 getTechList() 方法判斷標記支援的技術,並使用 android.nfc.tech 提供的其中一個類別建立對應的 TagTechnology 物件
表 1. 支援的標記技術
| 類別 | 說明 |
|---|---|
TagTechnology |
所有標記技術類別都必須實作的介面。 |
NfcA |
提供 NFC-A (ISO 14443-3A) 屬性和 I/O 作業的存取權。 |
NfcB |
提供 NFC-B (ISO 14443-3B) 屬性和 I/O 作業的存取權。 |
NfcF |
提供 NFC-F (JIS 6319-4) 屬性和 I/O 作業的存取權。 |
NfcV |
提供 NFC-V (ISO 15693) 屬性和 I/O 作業的存取權。 |
IsoDep |
提供 ISO-DEP (ISO 14443-4) 屬性和 I/O 作業的存取權。 |
Ndef |
提供 NDEF 資料的存取權,以及已格式化為 NDEF 的 NFC 標記作業。 |
NdefFormatable |
為可能可格式化為 NDEF 的標記提供格式作業。 |
Android 裝置不一定要支援下列標記技術。
表 2. 選用的支援代碼技術
| 類別 | 說明 |
|---|---|
MifareClassic |
如果這個 Android 裝置支援 MIFARE,則可存取 MIFARE Classic 屬性和 I/O 作業。 |
MifareUltralight |
如果這個 Android 裝置支援 MIFARE,則可存取 MIFARE Ultralight 屬性和 I/O 作業。 |
使用標記技術和 ACTION_TECH_DISCOVERED 意圖
當裝置掃描含有 NDEF 資料,但無法對應至 MIME 或 URI 的標記時,標記調度系統會嘗試使用 ACTION_TECH_DISCOVERED 意圖啟動活動。掃描含有非 NDEF 資料的標記時,也會使用 ACTION_TECH_DISCOVERED。有了這個備用方案,如果代碼調度系統無法剖析資料,您就能直接處理代碼上的資料。使用標記技術的基本步驟如下:
- 篩選
ACTION_TECH_DISCOVERED意圖,指定要處理的標記技術。詳情請參閱「篩選 NFC 意圖」。一般來說,如果 NDEF 訊息無法對應至 MIME 類型或 URI,或掃描的標記不含 NDEF 資料,標記調度系統會嘗試啟動ACTION_TECH_DISCOVERED意圖。如要進一步瞭解如何判斷,請參閱「代碼調度系統」。 - 應用程式收到意圖後,請從意圖取得
Tag物件:Kotlin
var tagFromIntent: Tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
Java
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
- 呼叫
android.nfc.tech套件中類別的其中一個get工廠方法,取得TagTechnology的例項。呼叫get工廠方法前,您可以先呼叫getTechList(),列舉標記支援的技術。舉例來說,如要從Tag取得MifareUltralight的例項,請執行下列操作:Kotlin
MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG))
Java
MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
讀取及寫入標記
如要讀取及寫入 NFC 標記,您必須從意圖取得標記,並與標記建立通訊。您必須定義自己的通訊協定堆疊,才能讀取及寫入資料至標記。不過請注意,直接使用標記時,您仍可讀取及寫入 NDEF 資料。您可以自行決定如何建構。以下範例說明如何使用 MIFARE Ultralight 標記。
Kotlin
package com.example.android.nfc import android.nfc.Tag import android.nfc.tech.MifareUltralight import java.io.IOException import java.nio.charset.Charset class MifareUltralightTagTester { fun writeTag(tag: Tag, tagText: String) { MifareUltralight.get(tag)?.use { ultralight -> ultralight.connect() Charset.forName("US-ASCII").also { usAscii -> ultralight.writePage(4, "abcd".toByteArray(usAscii)) ultralight.writePage(5, "efgh".toByteArray(usAscii)) ultralight.writePage(6, "ijkl".toByteArray(usAscii)) ultralight.writePage(7, "mnop".toByteArray(usAscii)) } } } fun readTag(tag: Tag): String? { return MifareUltralight.get(tag)?.use { mifare -> mifare.connect() val payload = mifare.readPages(4) String(payload, Charset.forName("US-ASCII")) } } }
Java
package com.example.android.nfc; import android.nfc.Tag; import android.nfc.tech.MifareUltralight; import android.util.Log; import java.io.IOException; import java.nio.charset.Charset; public class MifareUltralightTagTester { private static final String TAG = MifareUltralightTagTester.class.getSimpleName(); public void writeTag(Tag tag, String tagText) { MifareUltralight ultralight = MifareUltralight.get(tag); try { ultralight.connect(); ultralight.writePage(4, "abcd".getBytes(Charset.forName("US-ASCII"))); ultralight.writePage(5, "efgh".getBytes(Charset.forName("US-ASCII"))); ultralight.writePage(6, "ijkl".getBytes(Charset.forName("US-ASCII"))); ultralight.writePage(7, "mnop".getBytes(Charset.forName("US-ASCII"))); } catch (IOException e) { Log.e(TAG, "IOException while writing MifareUltralight...", e); } finally { try { ultralight.close(); } catch (IOException e) { Log.e(TAG, "IOException while closing MifareUltralight...", e); } } } public String readTag(Tag tag) { MifareUltralight mifare = MifareUltralight.get(tag); try { mifare.connect(); byte[] payload = mifare.readPages(4); return new String(payload, Charset.forName("US-ASCII")); } catch (IOException e) { Log.e(TAG, "IOException while reading MifareUltralight message...", e); } finally { if (mifare != null) { try { mifare.close(); } catch (IOException e) { Log.e(TAG, "Error closing tag...", e); } } } return null; } }
使用前景調度系統
前景調度系統可讓活動攔截意圖,並優先於處理相同意圖的其他活動。使用這個系統時,您必須建構一些資料結構,讓 Android 系統能夠將適當的意圖傳送至您的應用程式。如要啟用前景調度系統,請按照下列步驟操作:
- 在活動的
onCreate()方法中加入下列程式碼:- 建立可變動的
PendingIntent物件,讓 Android 系統在掃描標記時,能填入標記的詳細資料。Kotlin
val intent = Intent(this, javaClass).apply { addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) } var pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE)
Java
PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE);
- 宣告意圖篩選器,處理您要攔截的意圖。前景調度系統會檢查指定的意圖篩選器,以及裝置掃描標記時收到的意圖。如果相符,應用程式就會處理意圖。如果不相符,前景調度系統會改回使用意圖調度系統。指定意圖篩選器和技術篩選器的
null陣列,指定要篩選備用至TAG_DISCOVERED意圖的所有標記。以下程式碼片段會處理NDEF_DISCOVERED的所有 MIME 類型。您應該只處理需要的事件。Kotlin
val ndef = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED).apply { try { addDataType("*/*") /* Handles all MIME based dispatches. You should specify only the ones that you need. */ } catch (e: IntentFilter.MalformedMimeTypeException) { throw RuntimeException("fail", e) } } intentFiltersArray = arrayOf(ndef)
Java
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try { ndef.addDataType("*/*"); /* Handles all MIME based dispatches. You should specify only the ones that you need. */ } catch (MalformedMimeTypeException e) { throw new RuntimeException("fail", e); } intentFiltersArray = new IntentFilter[] {ndef, };
- 設定應用程式要處理的一系列標記技術。呼叫
Object.class.getName()方法,取得要支援的技術類別。Kotlin
techListsArray = arrayOf(arrayOf<String>(NfcF::class.java.name))
Java
techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
- 建立可變動的
- 覆寫下列活動生命週期回呼,並新增邏輯,在活動失去 (
onPause()) 和重新取得 (onResume()) 焦點時,啟用及停用前景調度。enableForegroundDispatch()必須從主執行緒呼叫,且只能在活動位於前景時呼叫 (在onResume()中呼叫可確保這一點)。您也必須實作onNewIntent回呼,處理掃描的 NFC 標記資料。Kotlin
public override fun onPause() { super.onPause() adapter.disableForegroundDispatch(this) } public override fun onResume() { super.onResume() adapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray) } public override fun onNewIntent(intent: Intent) { val tagFromIntent: Tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG) // do something with tagFromIntent }
Java
public void onPause() { super.onPause(); adapter.disableForegroundDispatch(this); } public void onResume() { super.onResume(); adapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray); } public void onNewIntent(Intent intent) { Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); // do something with tagFromIntent }