0 Near Field Communicationhtml
Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices. java |
近場通訊(NFC)是一個短範圍無線技術集合,一般須要4釐米或更短的距離才能初始化鏈接。NFC容許在NFC標籤和Android設備之間或兩個Android設備之間共享小的數據的負載。android |
Tags can range in complexity. Simple tags offer just read and write semantics, sometimes with one-time-programmable areas to make the card read-only. More complex tags offer math operations, and have cryptographic hardware to authenticate access to a sector. The most sophisticated tags contain operating environments, allowing complex interactions with code executing on the tag. The data stored in the tag can also be written in a variety of formats, but many of the Android framework APIs are based around a NFC Forum standard called NDEF (NFC Data Exchange Format).web |
NFC標籤具備複雜的分類。簡單的NFC標籤只提供讀寫語法,某些時候一次只能以只讀的方式讀取卡片的可編程區域。複雜一點的NFC標籤提供了數學運算能力,並且有加密的硬件來認證對一個扇區的訪問。最複雜的NFC標籤包含了運算環境,容許在標籤上執行復雜的交互代碼。存儲在標籤中的數據也能夠用各類格式來編寫,可是大多數的Android框架API都使用基於NDEF(NFC Data Exchange Format)的標準。編程 |
This document describes the basic NFC tasks you perform in Android. It explains how to send and receive NFC data in the form of NDEF messages and describes the Android framework APIs that support these features. For more advanced topics, including a discussion of working with non-NDEF data, see Advanced NFC. api There are two major uses cases when working with NDEF data and Android:數組 Reading NDEF data from an NFC tag瀏覽器 Beaming NDEF messages from one device to another with Android Beam™數據結構 |
本文介紹在Android系經過你所能執行的基本任務。它解釋瞭如何用NDEF消息格式來發送和接收NFC數據,而且介紹了支持這些功能的Android框架API。有關更高級的話題,包括對非NDEF格式數據的討論,狀況「高級 NFC」 NDEF數據和Android一塊兒工做的場景主要有兩個:app 1. 從NFC標籤中讀取NDEF數據; 【讀數據】 2. 把NDEF消息從一個設備發送給另外一個設備。【數據傳遞】 |
Reading NDEF data from an NFC tag is handled with the tag dispatch system, which analyzes discovered NFC tags, appropriately categorizes the data, and starts an application that is interested in the categorized data. An application that wants to handle the scanned NFC tag can declare an intent filter and request to handle the data. |
從NFC標籤中讀取NDEF數據是用標籤調度系統來處理的,它會分析被發現的NFC標籤,對數據進行適當的分類,並啓動對該類數據感興趣的應用程序。想要處理被掃描到NFC標籤的應用程序會聲明一個Intent過濾器,並請求處理數據。 |
The Android Beam™ feature allows a device to push an NDEF message onto another device by physically tapping the devices together. This interaction provides an easier way to send data than other wireless technologies like Bluetooth, because with NFC, no manual device discovery or pairing is required. The connection is automatically started when two devices come into range. Android Beam is available through a set of NFC APIs, so any application can transmit information between devices. For example, the Contacts, Browser, and YouTube applications use Android Beam to share contacts, web pages, and videos with other devices. |
Android Beam™ 功能容許設備把一個NDEF消息推送到物理/硬件上相互監聽的另外一個設備上。這種交互提供了比其餘無線技術(如藍牙)更容易的發送數據的方法。由於NFC不須要手動的設備發現或配對要求,兩個設備在接近到必定範圍時會自動的鏈接。Android Beam經過一組NFC API來使用,以便應用程序可以在設備之間來傳輸信息。例如,通訊錄、瀏覽器以及YouTube等應用程序都使用Android Beam來跟其餘設備共享通訊錄、網頁和視頻。 |
Android-powered devices are usually looking for NFC tags when the screen is unlocked, unless NFC is disabled in the device's Settings menu. When an Android-powered device discovers an NFC tag, the desired behavior is to have the most appropriate activity handle the intent without asking the user what application to use. Because devices scan NFC tags at a very short range, it is likely that making users manually select an activity would force them to move the device away from the tag and break the connection. You should develop your activity to only handle the NFC tags that your activity cares about to prevent the Activity Chooser from appearing. |
一般,除非是在設備的設置菜單中NFC被禁用,不然Android設備會在非鎖屏的狀態下搜索NFC。當Android設備發現NFC標籤時,指望的行爲是用最合適的Activity來處理該Intent,而不是詢問用戶使用什麼應用程序。由於設備只能在很短的範圍內掃描到NFC標籤,強制的讓用戶手動的選擇一個Activity,會致使設備離開NFC標籤,從而中斷該鏈接。你應該開發你本身的Activity來處理你所關心的NFC標籤,從而阻止 選擇器的操做。 |
To help you with this goal, Android provides a special tag dispatch system that analyzes scanned NFC tags, parses them, and tries to locate applications that are interested in the scanned data. It does this by:
|
爲了幫助你達到這個目標,Android提供了特殊的標籤調度系統,來分析掃描到的NFC標籤,經過解析數據,在被掃描到的數據中嘗試找到感興趣的應用程序,具體作法以下: 1. 解析NFC標籤並搞清楚標籤中標識數據負載的MIME類型或URI; 2. 把MIME類型或URI以及數據負載封裝到一個Intent中。 3. 基於Intent來啓動Activity。 |
Before you begin writing your NFC applications, it is important to understand the different types of NFC tags, how the tag dispatch system parses NFC tags, and the special work that the tag dispatch system does when it detects an NDEF message. NFC tags come in a wide array of technologies and can also have data written to them in many different ways. Android has the most support for the NDEF standard, which is defined by the NFC Forum. |
開始編寫NFC應用程序以前,重要的是要理解不一樣類型的NFC標籤、標籤調度系統是如何解析NFC標籤的、以及在檢測到NDEF消息時,標籤調度系統所作的特定的工做等。NFC標籤涉及到普遍的技術,而且有不少不一樣的方法向標籤中寫入數據。Android支持由NFC Forum所定義的NDEF標準。 |
NDEF data is encapsulated inside a message (NdefMessage) that contains one or more records (NdefRecord). Each NDEF record must be well-formed according to the specification of the type of record that you want to create. Android also supports other types of tags that do not contain NDEF data, which you can work with by using the classes in the android.nfc.tech package. To learn more about these technologies, see the Advanced NFC topic. Working with these other types of tags involves writing your own protocol stack to communicate with the tags, so we recommend using NDEF when possible for ease of development and maximum support for Android-powered devices. |
NDEF數據被封裝在一個消息(NdefMessage)中,該消息中包含了一條或多條記錄(NdefRecord)。每一個NDEF記錄必須具備良好的你想要建立的記錄類型的規範的格式。Android也支持其餘的不包含NDEF數據類型的標籤,你可以使用android.nfc.tech包中的類來工做。要使用其餘類型標籤來工做,涉及到編寫本身的跟該標籤通訊的協議棧,所以咱們建議你儘量的使用NDEF,以便減小開發難度,而且最大化的支持Android設備。 |
Note:To download complete NDEF specifications, go to the NFC Forum Specification Download site and seeCreating common types of NDEF records for examples of how to construct NDEF records. |
注意:要下載完整的NDEF規範,請去「NFC論壇規範下載」網址來下載。 |
Now that you have some background in NFC tags, the following sections describe in more detail how Android handles NDEF formatted tags. When an Android-powered device scans an NFC tag containing NDEF formatted data, it parses the message and tries to figure out the data's MIME type or identifying URI. To do this, the system reads the first NdefRecord inside the NdefMessage to determine how to interpret the entire NDEF message (an NDEF message can have multiple NDEF records). In a well-formed NDEF message, the first NdefRecordcontains the following fields: |
如今,你已經具有了一些NFC標籤的背景知識,接下來要詳細的介紹Android是如何處理NDEF格式的標籤的。當Android設備掃描到包含NDEF格式數據的NFC標籤時,它會解析該消息,並嘗試搞清楚數據的MIME類型或URI標識。首先系統會讀取消息(NdefMessage)中的第一條NdefRecord,來判斷如何解釋整個NDEF消息(一個NDEF消息可以有多條NDEF記錄)。 在格式良好的NDEF消息中,第一條NdefRecord包含如下字段信息: |
3-bit TNF (Type Name Format) Indicates how to interpret the variable length type field. Valid values are described in described in Table 1. Variable length type Describes the type of the record. If using TNF_WELL_KNOWN, use this field to specify the Record Type Definition (RTD). Valid RTD values are described in Table 2. Variable length ID A unique identifier for the record. This field is not used often, but if you need to uniquely identify a tag, you can create an ID for it. Variable length payload The actual data payload that you want to read or write. An NDEF message can contain multiple NDEF records, so don't assume the full payload is in the first NDEF record of the NDEF message. |
3-bit TNF(類型名稱格式) 指示如何解釋可變長度類型字段,在下表1中介紹有效值。 可變長度類型 說明記錄的類型,若是使用TNF_WELL_KNOWN,那麼則使用這個字段來指定記錄的類型定義(RTD)。在下表2中定義了有效的RTD值。 可變長度ID 惟一標識該記錄。這個字段不常用,可是,若是須要惟一的標識一個標記,那麼就能夠爲該字段建立一個ID。 可變長度負載 你想讀/寫的實際的數據負載。一個NDEF消息可以包含多個NDEF記錄,所以不要覺得在NDEF消息的第一條NDEF記錄中包含了全部的負載。 |
The tag dispatch system uses the TNF and type fields to try to map a MIME type or URI to the NDEF message. If successful, it encapsulates that information inside of aACTION_NDEF_DISCOVERED intent along with the actual payload. However, there are cases when the tag dispatch system cannot determine the type of data based on the first NDEF record. This happens when the NDEF data cannot be mapped to a MIME type or URI, or when the NFC tag does not contain NDEF data to begin with. In such cases, a Tag object that has information about the tag's technologies and the payload are encapsulated inside of a ACTION_TECH_DISCOVERED intent instead. |
標籤調度系統使用TNF和類型字段來嘗試把MIME類型或URI映射到NDEF消息中。若是成功,它會把信息跟實際的負載一塊兒封裝到ACTION_NEDF_DISCOVERED類型的Intent中。可是,會有標籤調度系統不能根據第一條NDEF記錄來判斷數據類型的狀況,這樣就會有NDEF數據不能被映射到MIME類型或URI,或者是NFC標籤沒有包含NDEF開始數據的狀況發生。在這種狀況下,就會用一個標籤技術信息相關的Tag對象和封裝在ACTION_TECH_DISCOVERED類型Intent對象內部的負載來代替。 |
Table 1. describes how the tag dispatch system maps TNF and type fields to MIME types or URIs. It also describes which TNFs cannot be mapped to a MIME type or URI. In these cases, the tag dispatch system falls back toACTION_TECH_DISCOVERED. |
表1. 介紹標籤調度系統映射如何把TNF和類型字段映射到MIME型或URI上。同時也介紹了那種類型的TNF不能被映射到MIME類型或URI上。這種狀況下,標籤調度系統會退化到ACTION_TECH_DISCOVERED類型的Intent對象。 |
For example, if the tag dispatch system encounters a record of typeTNF_ABSOLUTE_URI, it maps the variable length type field of that record into a URI. The tag dispatch system encapsulates that URI in the data field of anACTION_NDEF_DISCOVERED intent along with other information about the tag, such as the payload. On the other hand, if it encounters a record of typeTNF_UNKNOWN, it creates an intent that encapsulates the tag's technologies instead. |
例如,若是標籤調度系統遇到一個TNF_ABSOLUTE_URI類型的記錄,它會把這個記錄的可變長度類型字段映射到一個URI中。標籤調度系統會把這個URI跟其餘相關的標籤的信息(如數據負載)一塊兒封裝到ACTION_NDEF_DISCOVERED的Intent對象中。在另外一方面,若是遇到了TNF_UNKNOWN類型,它會建立一個封裝了標籤技術信息的Intent對象來代替。 |
表1. 所支持的TNF和它們的映射
類型名稱格式(TNF) |
映射 |
TNF_ABSOLUTE_URI |
基於類型字段的URI |
TNF_EMPTY |
退化到ACTION_TECH_DISCOVERED類型的Intent對象 |
TNF_EXTERNAL_TYPE |
基於類型字段中URN的URI。URN是縮短的格式(: Android會把這個URN映射成如下格式的URI:vnd.android.nfc://ext/: |
TNF_MIME_MEDIA |
基於類型字段的MIME類型 |
TNF_UNCHANGED |
退化到ACTION_TECH_DISCOVERED類型的Intent對象 |
TNF_UNKNOWN |
退化到ACTION_TECH_DISCOVERED類型的Intent對象 |
TNF_WELL_KNOWN |
依賴你在類型字段中設置的記錄類型定義(RTD)的MIME類型或URI |
表2. TNF_WELL_KNOWN所支持的RTD和它們的映射
記錄類型定義(RTD) |
映射 |
RTD_ALTERNATIVE_CARRIER |
退化到ACTION_TECH_DISCOVERED類型的Intent對象 |
RTD_HANDOVER_CARRIER |
退化到ACTION_TECH_DISCOVERED類型的Intent對象 |
RTD_HANDOVER_REQUEST |
退化到ACTION_TECH_DISCOVERED類型的Intent對象 |
RTD_HANDOVER_SELECT |
退化到ACTION_TECH_DISCOVERED類型的Intent對象 |
RTD_SMART_POSTER |
基於負載解析的URI |
RTD_TEXT |
text/plain類型的MIME |
RTD_URI |
基於有效負載的URI |
When the tag dispatch system is done creating an intent that encapsulates the NFC tag and its identifying information, it sends the intent to an interested application that filters for the intent. If more than one application can handle the intent, the Activity Chooser is presented so the user can select the Activity. The tag dispatch system defines three intents, which are listed in order of highest to lowest priority:
|
當標籤調度系統完成對NFC標籤和它的標識信息封裝的Intent對象的建立時,它會把該Intent對象發送給感興趣的應用程序。若是有多個應用程序可以處理該Intent對象,就會顯示Activity選擇器,讓用戶選擇Activity。標籤調度系統定義了三種Intent對象,如下按照由高到低的優先級列出這三種Intent對象: 1. ACTION_NDEF_DISCOVERED: 這種Intent用於啓動包含NDEF負載和已知類型的標籤的Activity。這是最高優先級的Intent,而且標籤調度系統在任何其餘Intent以前,都會盡量的嘗試使用這種類型的Intent來啓動Activity。 2. ACTION_TECH_DISCOVERED: 若是沒有註冊處理ACTION_NDEF_DISCOVERED類型的Intent的Activity,那麼標籤調度系統會嘗試使用這種類型的Intent來啓動應用程序。若是被掃描到的標籤包含了不能被映射到MIME類型或URI的NDEF數據,或者沒有包含NDEF數據,可是是已知的標籤技術,那麼也會直接啓動這種類型的Intent對象(而不是先啓動ACTION_NDEF_DISCOVERED類型的Intent) 3. ACTION_TAB_DISCOVERED: 若是沒有處理ACTION_NDEF_DISCOVERED或ACTION_TECH_DISCOVERED類型Intent的Activity,就會啓動這種類型的Intent。 |
The basic way the tag dispatch system works is as follows:
|
標籤調度系統的基本工做方法以下: 1. 用解析NFC標籤時由標籤調度系統建立的Intent對象(ACTION_NDEF_DISCOVERED或ACTION_TECH_DISCOVERED)來嘗試啓動Activity; 2. 若是沒有對應的處理Intent的Activity,那麼就會嘗試使用下一個優先級的Intent(ACTION_TECH_DISCOVERED或ACTION_TAG_DISCOVERED)來啓動Activity,直到有對應的應用程序來處理這個Intent,或者是直到標籤調度系統嘗試了全部可能的Intent。 3. 若是沒有應用程序來處理任何類型的Intent,那麼就不作任何事情。 |
Whenever possible, work with NDEF messages and the ACTION_NDEF_DISCOVERED intent, because it is the most specific out of the three. This intent allows you to start your application at a more appropriate time than the other two intents, giving the user a better experience. |
在可能的狀況下,都會使用NDEF消息和ACTION_NDEF_DISCOVERED類型的Intent來工做,由於它是這三種Intent中最標準的。這種Intent與其餘兩種Intent相比,它會容許你在更加合適的時機來啓動你的應用程序,從而給用戶帶來更好的體驗。 |
圖1. 標籤調度系統 Tag Dispatch System
Before you can access a device's NFC hardware and properly handle NFC intents, declare these items in your AndroidManifest.xml file: |
在訪問設備的NFC硬件和正確的處理NFC的Intent以前,要在AndroidManifest.xml文件中進行如下聲明:
|
1 The NFC element to access the NFC hardware: 2 The minimum SDK version that your application can support. API level 9 only supports limited tag dispatch viaACTION_TAG_DISCOVERED, and only gives access to NDEF messages via the EXTRA_NDEF_MESSAGES extra. No other tag properties or I/O operations are accessible. API level 10 includes comprehensive reader/writer support as well as foreground NDEF pushing, and API level 14 provides an easier way to push NDEF messages to other devices with Android Beam and extra convenience methods to create NDEF records. 3 The uses-feature element so that your application shows up in Google Play only for devices that have NFC hardware: |
1. 在元素中聲明訪問NFC硬件:
2. 你的應用程序所支持的最小的SDK版本。API Level 9只經過ACTION_TAG_DISCOVERED來支持有限的標籤調度,而且只能經過EXTRA_NDEF_MESSAGES來訪問NDEF消息。沒有其餘的標籤屬性或I/O操做可用。API Level 10中包含了普遍的讀寫支持,從而更好的推進了NDEF的應用前景,而且API Leve 14用Android Beam和額外的方便的建立NDEF記錄的方法,向外提供了更容易的把NDEF消息推送給其餘設備的方法。
3. 使用uses-feature元素,在Google Play中,以便你的應用程序可以只針對有NFC硬件的設備來顯示。
|
If your application uses NFC functionality, but that functionality is not crucial to your application, you can omit the uses-feature element and check for NFC avalailbility at runtime by checking to see if getDefaultAdapter()is null. |
若是你的應用程序使用了NFC功能,可是相關的功能又不是你的應用程序的關鍵功能,你能夠忽略uses-feature元素,而且要在運行時經過調用getDefaultAdapter()方法來檢查NFC是否有效。 |
To start your application when an NFC tag that you want to handle is scanned, your application can filter for one, two, or all three of the NFC intents in the Android manifest.
|
要在你想要處理被掃描到的NFC標籤時啓動你的應用程序,能夠在你的應用程序的Android清單中針對一種、兩種或所有三種類型的NFC的Intent來過濾。
|
Because NFC tag deployments vary and are many times not under your control, this is not always possible, which is why you can fallback to the other two intents when necessary. When you have control over the types of tags and data written, it is recommended that you use NDEF to format your tags. The following sections describe how to filter for each type of intent. |
由於NFC標籤的多樣性,而且不少時候不在你的控制之下,所以在必要的時候你要回退到其餘兩種類型的Intent。在你可以控制標籤的類型和寫入的數據時,咱們建議你使用NDEF格式。下文將介紹如何過濾每種類型的Intent對象。 |
To filter for ACTION_NDEF_DISCOVERED intents, declare the intent filter along with the type of data that you want to filter for. The following example filters for ACTION_NDEF_DISCOVERED intents with a MIME type of text/plain:
The following example filters for a URI in the form ofhttp://developer.android.com/index.html.
android:host="developer.android.com" android:pathPrefix="/index.html" />
|
要過濾ACTION_NDEF_DISCOVERED類型的Intent,就要在清單中跟你想要過濾的數據一塊兒來聲明該類型的Intent過濾器。 如下是過濾text/plain類型的MIME的ACTION_NDEF_DISCOVERED類型過濾器的聲明:
如下示例使用http://developer.android.com/index.html格式的URI來過濾:
android:host="developer.android.com" android:pathPrefix="/index.html" />
|
If your activity filters for the ACTION_TECH_DISCOVERED intent, you must create an XML resource file that specifies the technologies that your activity supports within a tech-list set. Your activity is considered a match if a tech-list set is a subset of the technologies that are supported by the tag, which you can obtain by calling getTechList(). |
若是你的Activity要過濾ACTION_TECH_DISCOVERED類型的Intent,你必須建立一個XML資源文件,該文件在tech-list集合中指定你的Activity所支持的技術。若是tech-list集合是標籤所支持的技術的一個子集,那麼你的Activity被認爲是匹配的。經過調用getTechList()方法來得到標籤所支持的技術集合。 |
For example, if the tag that is scanned supports MifareClassic, NdefFormatable, and NfcA, your tech-list set must specify all three, two, or one of the technologies (and nothing else) in order for your activity to be matched. |
例如,若是掃描到的標籤支持MifareClassic、NdefFormatable和NfcA,那麼爲了跟它們匹配,tech-list集合就必須指定全部這三種技術,或者指定其中的兩種或一種。 |
The following sample defines all of the technologies. You can remove the ones that you do not need. Save this file (you can name it anything you wish) in the /res/xml folder. |
如下示例定義了全部的相關的技術。你能夠根據須要刪除其中一些設置。而後把這個文件保存到/res/xml文件夾中(你可以把命名爲任何你但願的名字): |
You can also specify multiple tech-list sets. Each of the tech-list sets is considered independently, and your activity is considered a match if any single tech-list set is a subset of the technologies that are returned by getTechList(). This provides AND and OR semantics for matching technologies. The following example matches tags that can support the NfcA and Ndef technologies or can support the NfcB and Ndef technologies: |
你也可以指定多個tech-list集合,每一個tech-list集合被認爲是獨立的,而且若是任何一個tech-list集合是由getTechList()返回的技術的子集,那麼你的Activity就被認爲是匹配的。 下列示例可以跟支持NfcA和Ndef技術NFC標籤或者跟支持NfcB和Ndef技術的標籤相匹配: |
In your AndroidManifest.xml file, specify the resource file that you just created in the element inside the element like in the following example: |
在你的AndroidManifest.xml文件中,要像向下列示例那樣,在元素內的元素中指定你建立的資源文件: |
To filter for ACTION_TAG_DISCOVERED use the following intent filter: |
使用下列Intent過濾器來過濾ACTION_TAG_DISCOVERED類型的Intent: |
If an activity starts because of an NFC intent, you can obtain information about the scanned NFC tag from the intent. Intents can contain the following extras depending on the tag that was scanned: |
若是由於NFC的Intent而啓動一個Activity,那麼你就可以從Intent中獲取被掃描到的NFC標籤的相關信息。根據被掃描到的標籤,Intent對象可以如下額外的信息: |
EXTRA_TAG (required): A Tag object representing the scanned tag. EXTRA_NDEF_MESSAGES (optional): An array of NDEF messages parsed from the tag. This extra is mandatory on intents. {@link android.nfc.NfcAdapter#EXTRA_ID (optional): The low-level ID of the tag. |
1. EXTRA_TAG(必須的):它是一個表明了被掃描到的標籤的Tag對象; 2. EXTRA_NDEF_MESSAGES(可選):它是一個解析來自標籤中的NDEF消息的數組。這個附加信息是強制在Intent對象上的; 3. {@link android.nfc.NfcAdapter#EXTRA_ID(可選):標籤的低級ID。 |
To obtain these extras, check to see if your activity was launched with one of the NFC intents to ensure that a tag was scanned, and then obtain the extras out of the intent. The following example checks for the ACTION_NDEF_DISCOVEREDintent and gets the NDEF messages from an intent extra. |
要獲取這些附加信息,就要確保你的Activity是被掃描到的NFC的Intent對象啓動的,而後才能得到Intent以外的附加信息。 下例檢查ACTION_NDEF_DISCOVERED類型的Intent,並從Intent對象的附加信息中獲取NDEF消息。 |
Alternatively, you can obtain a Tag object from the intent, which will contain the payload and allow you to enumerate the tag's technologies: Tag tag= intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); |
此外,你還可以從Intent對象中得到一個Tag對象,該對象包含了數據負載,並容許你列舉標籤的技術: Tag tag= intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); |
This section describes how to create common types of NDEF records to help you when writing to NFC tags or sending data with Android Beam. Starting with Android 4.0 (API level 14), thecreateUri() method is available to help you create URI records automatically. Starting in Android 4.1 (API level 16), createExternal()and createMime() are available to help you create MIME and external type NDEF records. Use these helper methods whenever possible to avoid mistakes when manually creating NDEF records. This section also describes how to create the corresponding intent filter for the record. All of these NDEF record examples should be in the first NDEF record of the NDEF message that you are writing to a tag or beaming. |
本節介紹如何建立通用的NDEF記錄類型,以便幫助你向NFC標籤寫入或用Android Beam發送數據。 從Android4.0(API Level14)開始,能夠用createUri()方法來幫助你自動的建立URI記錄。 從Android4.1(API Level 16)開始,能夠用createExternal()和createMime()方法來幫助你建立MIME和外部類型的NDEF記錄。 使用這些輔助方法會盡量的避免手動建立NDEF記錄的錯誤。 本節還要介紹如何建立NDEF記錄對應的Intent過濾器。全部的這些寫入或發送到NFC標籤的NDEF記錄例子都應該是NDEF消息的第一條記錄。 |
Note: We recommend that you use the RTD_URI type instead ofTNF_ABSOLUTE_URI, because it is more efficient. |
注意:咱們推薦你使用RTD_URI類型,而不是TNF_ABSOLUTE_URI, 由於它更高效。 |
You can create a TNF_ABSOLUTE_URI NDEF record in the following way: |
用下列方法建立一個TNF_ABSOLUTE_URI類型的NDEF記錄: |
NdefRecord uriRecord = new NdefRecord( NdefRecord.TNF_ABSOLUTE_URI ,"http://developer.android.com/index.html".getBytes(Charset.forName("US-ASCII")),new byte[0], new byte[0]);
The intent filter for the previous NDEF record would look like this: |
對應的Intent過濾器以下: |
<</span>intent-filter> <</span>action android:name="android.nfc.action.NDEF_DISCOVERED" /> <</span>category android:name="android.intent.category.DEFAULT" /> <</span>data android:scheme="http" android:host="developer.android.com" android:pathPrefix="/index.html" /> </</span>intent-filter>
1.4.2 TNF_MIME_MEDIA
You can create a TNF_MIME_MEDIA NDEF record in the following ways. Using the createMime() method: |
使用下列方法建立TNF_MIME_MEDIA類型的NDEF記錄。 使用createMime()方法: |
NdefRecord mimeRecord = NdefRecord.createMime("application/vnd.com.example.android.beam","Beam me up, Android".getBytes(Charset.forName("US-ASCII")));
Creating the NdefRecord manually: |
手動的建立NdefRecord: |
NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA ,"application/vnd.com.example.android.beam".getBytes(Charset.forName("US-ASCII")),
new byte[0], "Beam me up, Android!".getBytes(Charset.forName("US-ASCII")));
The intent filter for the previous NDEF records would look like this: |
對應的Intent過濾器以下: |
You can create a TNF_WELL_KNOWN NDEF record in the following way: public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) { byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII")); Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16"); byte[] textBytes = payload.getBytes(utfEncoding); int utfBit = encodeInUtf8 ? 0 : (1 << 7); char status = (char) (utfBit + langBytes.length); byte[] data = new byte[1 + langBytes.length + textBytes.length]; data[0] = (byte) status; System.arraycopy(langBytes, 0, data, 1, langBytes.length); System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length); NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data); return record; } |
用下列方法建立TNF_WELL_KNOWN類型的NDEF記錄: public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) { byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII")); Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16"); byte[] textBytes = payload.getBytes(utfEncoding); int utfBit = encodeInUtf8 ? 0 : (1 << 7); char status = (char) (utfBit + langBytes.length); byte[] data = new byte[1 + langBytes.length + textBytes.length]; data[0] = (byte) status; System.arraycopy(langBytes, 0, data, 1, langBytes.length); System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length); NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data); return record; } |
the intent filter would look like this:
|
對應的Intent過濾器以下:
|
1.4.4 TNF_WELL_KNOW和RTD_URI
You can create a TNF_WELL_KNOWN NDEF record in the following ways. Using the createUri(String) method: NdefRecord rtdUriRecord1=NdefRecord.createUri("http://example.com"); |
用下列方法建立TNF_WELL_KNOWN類型的NDEF記錄。 使用createUri(String)方法: NdefRecord rtdUriRecord1=NdefRecord.createUri("http://example.com"); |
Using the createUri(Uri) method: Uri uri = new Uri("http://example.com"); NdefRecord rtdUriRecord2 = NdefRecord.createUri(uri); |
使用createUri(Uri)方法: Uri uri = new Uri("http://example.com"); NdefRecord rtdUriRecord2 = NdefRecord.createUri(uri); |
Creating the NdefRecord manually: byte[] uriField = "example.com".getBytes(Charset.forName("US-ASCII")); byte[] payload = new byte[uriField.length + 1]; //add 1 for the URI Prefix byte payload[0] = 0x01; //prefixes http://www. to the URI System.arraycopy(uriField, 0, payload, 1, uriField.length); //appends URI to payload NdefRecord rtdUriRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload); |
手動的建立NdefRecord: byte[] uriField = "example.com".getBytes(Charset.forName("US-ASCII")); byte[] payload = new byte[uriField.length + 1]; //add 1 for the URI Prefix byte payload[0] = 0x01; //prefixes http://www. to the URI System.arraycopy(uriField, 0, payload, 1, uriField.length); //appends URI to payload NdefRecord rtdUriRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload); |
The intent filter for the previous NDEF records would look like this:
android:host="example.com" android:pathPrefix="" />
|
對應的Intent過濾器以下:
android:host="example.com" android:pathPrefix="" />
|
1.4.5 TNF_EXTERNAL_TYPE
You can create a TNF_EXTERNAL_TYPE NDEF record in the following ways: Using the createExternal() method: |
使用下列方法建立TNF_EXTERNAL_TYPE類型的記錄。 使用createExternal()方法: |
byte[] payload; //assign to your data String domain = "com.example"; //usually your app's package name String type = "externalType"; NdefRecord extRecord = NdefRecord.createExternal(domain, type, payload);
Creating the NdefRecord manually: |
手動的建立NdefRecord: |
byte[] payload; ... NdefRecord extRecord = new NdefRecord( NdefRecord.TNF_EXTERNAL_TYPE, "com.example:externalType", new byte[0], payload);
The intent filter for the previous NDEF records would look like this: |
對應的Intent過濾器以下: |
<</span>intent-filter> <</span>action android:name="android.nfc.action.NDEF_DISCOVERED" /> <</span>category android:name="android.intent.category.DEFAULT" /> <</span>data android:scheme="vnd.android.nfc" android:host="ext" android:pathPrefix="/com.example:externalType"/> </</span>intent-filter>
Use TNF_EXTERNAL_TYPE for more generic NFC tag deployments to better support both Android-powered and non-Android-powered devices. |
使用更加通常化的TNF_EXTERNAL_TYPE類型NFC部署,以便更好的支持Android設備和非Android設備。 |
Note: URNs for TNF_EXTERNAL_TYPE have a canonical format of:urn:nfc:ext:example.com:externalType, however the NFC Forum RTD specification declares that the urn:nfc:ext: portion of the URN must be ommitted from the NDEF record. So all you need to provide is the domain (example.com in the example) and type (externalType in the example) separated by a colon. When dispatching TNF_EXTERNAL_TYPE, Android converts the urn:nfc:ext:example.com:externalType URN to avnd.android.nfc://ext/example.com:externalType URI, which is what the intent filter in the example declares. |
注意:TNF_EXTERNAL_TYPE類型的URN包含如下格式: urn:nfc:ext:example.com.externalType,可是,NFC論壇的RTD規範聲明,URN的urn:nfc:ext:部分在NDEF記錄中必須忽略。所以你須要提供的全部信息是用「:」號把域名(示例中的example.com)和類型(示例中的externalType)分離開。在調度TNF_EXTERNAL_TYPE類型的記錄時,Android會把urn:nfc:ext:example.com:externalType的URN轉換成vnd.android.nfc://ext/example.com:externalType的URI,它是在示例中聲明的Intent過濾器。 |
Introduced in Android 4.0 (API level 14), an Android Application Record (AAR) provides a stronger certainty that your application is started when an NFC tag is scanned. An AAR has the package name of an application embedded inside an NDEF record. You can add an AAR to any NDEF record of your NDEF message, because Android searches the entire NDEF message for AARs. If it finds an AAR, it starts the application based on the package name inside the AAR. If the application is not present on the device, Google Play is launched to download the application. |
在Android4.0(API Level 14)中引入的Android應用程序記錄(AAR),提供了較強的在掃描到NFC標籤時,啓動應用程序的肯定性。AAR有嵌入到NDEF記錄內部的應用程序的包名。你可以把一個AAR添加到你的NDEF消息的任何記錄中,由於Android會針對AAR來搜索整個NDEF消息。若是它找到一個AAR,它就會基於AAR內部的包名來啓動應用程序。若是該應用程序不在當前的設備上,會啓動Google Play來下載對應的應用程序。 |
AARs are useful if you want to prevent other applications from filtering for the same intent and potentially handling specific tags that you have deployed. AARs are only supported at the application level, because of the package name constraint, and not at the Activity level as with intent filtering. If you want to handle an intent at the Activity level, use intent filters. If a tag contains an AAR, the tag dispatch system dispatches in the following manner: |
若是你想要防止其餘的應用對相同的Intent的過濾並潛在的處理你部署的特定的NFC標籤,那麼AAR是有用的。AAR僅在應用程序級被支持,由於包名的約束,並不能在Activity級別來過濾Intent。若是你想要在Activity級處理Intent,請使用Intent過濾器。 若是NFC標籤中包含了AAR,則NFC標籤調度系統會按照下列方式來調度: |
|
1. 一般,嘗試使用Intent過濾器來啓動一個Activity。若是跟該Intent匹配的Activity也跟AAR匹配,那麼就啓動該Activity。 2. 若是跟Intent隊形的Activity跟AAR不匹配,或者是有多個Activity可以處理該Intent,或者是沒有可以處理該Intent的Activity存在,那麼就啓動由AAR指定的應用程序。 3. 若是沒有跟該AAR對應的應用程序,那麼就會啓動Google Play來小組基於該AAR的應用程序。 |
Note: You can override AARs and the intent dispatch system with the foreground dispatch system, which allows a foreground activity to have priority when an NFC tag is discovered. With this method, the activity must be in the foreground to override AARs and the intent dispatch system. |
注意:你可以用前臺調度系統來重寫AAR和Intent調度系統,在NFC標籤被發現時。它容許優先使用前臺的Activity。用這種方法,Activity必須是在前臺來重寫AAR和Intent調度系統。 |
If you still want to filter for scanned tags that do not contain an AAR, you can declare intent filters as normal. This is useful if your application is interested in other tags that do not contain an AAR. For example, maybe you want to guarantee that your application handles proprietary tags that you deploy as well as general tags deployed by third parties. Keep in mind that AARs are specific to Android 4.0 devices or later, so when deploying tags, you most likely want to use a combination of AARs and MIME types/URIs to support the widest range of devices. In addition, when you deploy NFC tags, think about how you want to write your NFC tags to enable support for the most devices (Android-powered and other devices). You can do this by defining a relatively unique MIME type or URI to make it easier for applications to distinguish. |
若是你依然想要過濾掃描到的沒有包含AAR的NFC標籤,一般,你可以聲明Intent過濾器。若是你的應用程序對不包含AAR的其餘NFC標籤感興趣,這種作法是有用的。例如,你可能想要保證你的應用程序處理你部署的專用NFC標籤,以及由第三方部署的普通的NFC標籤。要記住AAR是在Android4.0之後才指定的,所以部署NFC標籤時,你極可能但願使用可以普遍支持AAR和MIME類型/URI的是設備。另外,在你部署NFC標籤時,還要想如何編寫你的NFC標籤,以便讓大多數設備(Android設備和其餘設備)支持。同過定義相對惟一的MIME類型或URI,讓應用程序更容易的區分,就能夠作到這一點。 |
Android provides a simple API to create an AAR,createApplicationRecord(). All you need to do is embed the AAR anywhere in your NdefMessage. You do not want to use the first record of your NdefMessage, unless the AAR is the only record in theNdefMessage. This is because the Android system checks the first record of anNdefMessage to determine the MIME type or URI of the tag, which is used to create an intent for applications to filter. The following code shows you how to create an AAR: |
Android提供了簡單的建立AAR的API:createApplicationRecord()。你須要作的全部工做就是把AAR嵌入到你的NdefMessage中。除非AAR是NdefMessage中的惟一記錄,不然不要把使用NdefMessage的第一條記錄。這是由於,Android系統會檢查NdefMessage的第一條記錄來判斷NFC標籤的MIME類型或URI,這些信息被用於建立對應應用程序的Intent對象。如下代碼演示瞭如何建立一個AAR: |
NdefMessage msg = new NdefMessage( new NdefRecord[] { ..., NdefRecord.createApplicationRecord("com.example.android.beam")}
Android Beam allows simple peer-to-peer data exchange between two Android-powered devices. The application that wants to beam data to another device must be in the foreground and the device receiving the data must not be locked. When the beaming device comes in close enough contact with a receiving device, the beaming device displays the "Touch to Beam" UI. The user can then choose whether or not to beam the message to the receiving device. |
Android Beam容許在兩個Android設備之間進行簡單的對等數據交換,想要把數據發送給另外一個設備的應用程序必須是在前臺,而且接收數據的設備必須不被鎖定。當發射設備跟接收設備的距離足夠近的時候,發射設備會顯示「Touch to Beam(觸摸發射)」的UI。而後,用戶可以選擇是否把消息發射給接收設備。 |
Note: Foreground NDEF pushing was available at API level 10, which provides similar functionality to Android Beam. These APIs have since been deprecated, but are available to support older devices. SeeenableForegroundNdefPush() for more information. |
注意:在API Level 10中能夠利用前臺的NDEF推送,它提供了與Android Beam相似的功能。這些API已通過時了,可是在一些老舊設備上還有效。更多的信息請看enableForegroundNdefPush()。 |
You can enable Android Beam for your application by calling one of the two methods:
|
經過調用下列兩個方法中的任意一個,就可以爲你的應用程序啓用Android Beam: 1. setNdefPushMessage():這個方法把接收到的NdefMessage對象做爲一個消息設置給Beam。當兩個設備足夠近的時候,就會自動的發送消息。 2. setNdefPushMessageCallback():接收包含createNdefMessage()方法的回調,當設備在發射數據的範圍內時,這個回調方法會被調用。回調會讓你只在須要的時候建立NDEF消息。 |
An activity can only push one NDEF message at a time, so setNdefPushMessageCallback() takes precedence over setNdefPushMessage() if both are set. To use Android Beam, the following general guidelines must be met:
|
一個Activity一次只能推送一條NDEF消息,所以若是同時使用了這兩種方法,那麼setNdefPushMessageCallback()方法的優先級要高於setNdefPushMessage()方法。要使用Android Beam,一般必須知足如下條件: 1. 發射數據的Activity必須是在前臺。兩個設備的屏幕都必須沒有被鎖定; 2. 必須發要發射的數據封裝到一個NdefMessage對象中; 3. 接收發射數據的NFC設備必須支持com.android.npp NDEF推送協議或是NFC組織的SNEP協議(簡單的NDEF交換協議)。在API Level9(Android2.3)到API Level 13(Android3.2)的設備上須要com.android.npp協議。在API Level 14(Android4.0)和之後的設備上,com.android.npp和SNEP都須要。 |
Note: If your activity enables Android Beam and is in the foreground, the standard intent dispatch system is disabled. However, if your activity also enables foreground dispatching, then it can still scan tags that match the intent filters set in the foreground dispatching. |
注意:若是在前臺的Activity啓用了Android Beam,那麼標準的Intent調度系統就會被禁用。可是,若是該Activity還啓用了前臺調度,那麼在前臺調度系統中,它依然可以掃描到跟Intent過濾器匹配的NFC標籤。 |
To enable Android Beam:
In general, you normally use setNdefPushMessage() if your Activity only needs to push the same NDEF message at all times, when two devices are in range to communicate. You usesetNdefPushMessageCallback when your application cares about the current context of the application and wants to push an NDEF message depending on what the user is doing in your application. |
啓用Android Beam: 1. 建立一個準備推送到另外一個設備上的包含NdefRecord的NdefMessage對象。 2. 調用帶有NdefMessage類型參數的setNdefPushMessage()方法,或者是在Activity的onCreate()方法中調用setNdefPushMessageCallback方法來傳遞實現NfcAdapter.CreateNdefMessageCallback接口的對象。這兩個方法都至少須要一個準備要啓用Android Beam的Activity,以及一個可選的其餘的活躍的Activity列表。 一般,若是你的Activity在任什麼時候候都值推送相同的NDEF消息,那麼當兩個設備在通訊範圍內的時候,使用setNdefPushMessage()就能夠了。當你的應用程序要關注應用程序的當前內容,並想要根據用戶在你的應用程序中的行爲來推送NDEF消息時,就要使用setNdefPushMessageCallback方法。 |
The following sample shows how a simple activity calls NfcAdapter.CreateNdefMessageCallback in theonCreate() method of an activity (see AndroidBeamDemo for the complete sample). This example also has methods to help you create a MIME record: |
下列示例代碼演示瞭如何在activity的onCreate()方法中調用NfcAdapter.CreateNdefMessageCallback方法(完整的示例請看AndroidBeamDemo)。這個示例中還有幫助建立MIME記錄的方法: |
package com.example.android.beam; import android.app.Activity; import android.content.Intent; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.NfcAdapter.CreateNdefMessageCallback; import android.nfc.NfcEvent; import android.os.Bundle; import android.os.Parcelable; import android.widget.TextView; import android.widget.Toast; import java.nio.charset.Charset; publicclassBeamextendsActivityimplementsCreateNdefMessageCallback{ NfcAdapter mNfcAdapter; TextView textView; @Override publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textView =(TextView) findViewById(R.id.textView); // Check for available NFC Adapter mNfcAdapter =NfcAdapter.getDefaultAdapter(this); if(mNfcAdapter ==null){ Toast.makeText(this,"NFC is not available",Toast.LENGTH_LONG).show(); finish(); return; } // Register callback mNfcAdapter.setNdefPushMessageCallback(this,this); } @Override publicNdefMessage createNdefMessage(NfcEventevent){ String text =("Beam me up, Android!\n\n"+ "Beam Time: "+System.currentTimeMillis()); NdefMessage msg =newNdefMessage( newNdefRecord[]{ createMime( "application/vnd.com.example.android.beam", text.getBytes()) //,NdefRecord.createApplicationRecord("com.example.android.beam") }); return msg; } @Override publicvoid onResume(){ super.onResume(); // Check to see that the Activity started due to an Android Beam if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())){ processIntent(getIntent()); } } @Override publicvoid onNewIntent(Intent intent){ // onResume gets called after this to handle the intent setIntent(intent); } void processIntent(Intent intent){ textView =(TextView) findViewById(R.id.textView); Parcelable[] rawMsgs = intent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES); // only one message sent during the beam NdefMessage msg =(NdefMessage) rawMsgs[0]; // record 0 contains the MIME type, record 1 is the AAR, if present textView.setText(newString(msg.getRecords()[0].getPayload())); } }
Note that this code comments out an AAR, which you can remove. If you enable the AAR, the application specified in the AAR always receives the Android Beam message. If the application is not present, Google Play is started to download the application. Therefore, the following intent filter is not technically necessary for Android 4.0 devices or later if the AAR is used: |
注意:上例代碼把AAR給註釋掉了,你能夠刪除它。若是你啓用了AAR,那麼該應用程序就會始終接收在AAR中指定的Android Beam消息。若是該應用程序不存在,Google Play就會啓動下載程序。所以,若是使用AAR,對於Android4.0之後的設備,下列的Intent過濾器,在技術上不是必須的: |
With this intent filter, the com.example.android.beam application now can be started when it scans an NFC tag or receives an Android Beam with an AAR of type com.example.android.beam, or when an NDEF formatted message contains a MIME record of type application/vnd.com.example.android.beam. |
有了這個Intent過濾器,com.example.android.beam應用就可以在如下狀況下被啓動: 1. 掃描到NFC標籤; 2. 接收到com.example.android.beam類型的AAR或NDEF消息中包含一條application/vnd.com.example.android.beam類型的MIME記錄的Android beam的時候。 |
Even though AARs guarantee an application is started or downloaded, intent filters are recommended, because they let you start an Activity of your choice in your application instead of always starting the main Activity within the package specified by an AAR. AARs do not have Activity level granularity. Also, because some Android-powered devices do not support AARs, you should also embed identifying information in the first NDEF record of your NDEF messages and filter for that as well, just in case. See Creating Common Types of NDEF records for more information on how to create records. |
即便經過AAR可以保證了一個應用程序被啓動或下載,可是仍是推薦使用Intent過濾器,由於它會讓你選擇啓動應用程序中Activity,而不是總啓動AAR中指定的應用程序包的主Activity。AAR沒有Activity級別的粒度。並且還有一些android設備不支持AAR,你還應該在NDEF消息的第一條NDEF記錄中嵌入標識信息,以及對應的過濾器。 |
This document describes advanced NFC topics, such as working with various tag technologies, writing to NFC tags, and foreground dispatching, which allows an application in the foreground to handle intents even when other applications filter for the same ones. |
本文介紹一些高級的NFC專題,如多樣的NFC標籤技術、編寫NFC標籤、以及前臺調度,前臺調度容許在前臺的應用程序優先調度Intent事件,即便還有其餘的過濾一樣的Intent事件的應用程序存在。 |
2.1 Android所支持的NFC標籤技術
When working with NFC tags and Android-powered devices, the main format you use to read and write data on tags is NDEF. When a device scans a tag with NDEF data, Android provides support in parsing the message and delivering it in an NdefMessage when possible. There are cases, however, when you scan a tag that does not contain NDEF data or when the NDEF data could not be mapped to a MIME type or URI. In these cases, you need to open communication directly with the tag and read and write to it with your own protocol (in raw bytes). Android provides generic support for these use cases with theandroid.nfc.tech package, which is described in Table 1. You can use the getTechList() method to determine the technologies supported by the tag and create the corresponding TagTechnologyobject with one of classes provided byandroid.nfc.tech |
在使用NFC標籤和Android設備來進行工做的時候,使用的讀寫NFC標籤上數據的主要格式是NDEF。當設備掃描到帶有NDEF的數據時,Android會提供對消息解析的支持,並在可能的時候,會以NdefMessage對象的形式來發送它。可是,有些狀況下,設備掃描到的NFC標籤沒有包含NDEF數據,或者該NDEF數據沒有被映射到MIME類型或URI。在這些狀況下,你須要打開跟NFC標籤的通訊,並用本身的協議(原始的字節形式)來讀寫它。Android用android.nfc.tech包提供了對這些狀況的通常性支持,這個包在下表1中介紹。你可以使用getTechList()方法來判斷NFC標籤所支持的的技術,而且用android.nfc.tech提供的一個類來建立對應的TagTechnology對象。 |
Table 1. Supported tag technologies (表1.NFC標籤所支持的技術)
類 |
介紹 |
全部的NFC標籤技術類必須實現的接口。 |
|
提供對NFC-A(ISO 14443-3A)屬性和I/O操做的訪問。 |
|
提供對NFC-B(ISO 14443-3B)屬性和I/O操做的訪問。 |
|
提供對NFC-F(ISO 6319-4)屬性和I/O操做的訪問。 |
|
提供對NFC-V(ISO 15693)屬性和I/O操做的訪問。 |
|
提供對NFC-A(ISO 14443-4)屬性和I/O操做的訪問。 |
|
提供對NDEF格式的NFC標籤上的NDEF數據和操做的訪問。 |
|
提供了對能夠被NDEF格式化的NFC標籤的格式化操做。 |
The following tag technlogies are not required to be supported by Android-powered devices.
Table 2. Optional supported tag technologies (表2.可選的NFC標籤所支持的技術)
類 |
介紹 |
若是Android設備支持MIFARE,那麼它提供了對經典的MIFARE類型標籤屬性和I/O操做的訪問。 |
|
若是Android設備支持MIFARE,那麼它提供了對超薄的MIFARE類型標籤屬性和I/O操做的訪問。 |
2.1.1 NFC標籤和ACTION_TECH_DISCOVERED類型的Intent協同工做
When a device scans a tag that has NDEF data on it, but could not be mapped to a MIME or URI, the tag dispatch system tries to start an activity with the ACTION_TECH_DISCOVEREDintent. The ACTION_TECH_DISCOVERED is also used when a tag with non-NDEF data is scanned. Having this fallback allows you to work with the data on the tag directly if the tag dispatch system could not parse it for you. The basic steps when working with tag technologies are as follows: |
當設備掃描到帶有NDEF數據的NFC標籤,但卻不能映射到MIME或URI時,NFC標籤調度系統就嘗試使用ACTION_TECH_DISCOVERED類型的Intent來啓動一個Activity。在被掃描到的NFC標籤上沒有NDEF數據時,也會使用ACTION_TECH_DISCOVERED類型的Intent。有了這種回退機制,若是調度系統不可以幫你解析數據,那麼你就能夠直接使用NFC標籤上數據來工做。基本步驟以下: |
|
1. 給你但願處理的NFC標籤指定ACTION_TECH_DISCOVERED類型的Intent過濾器。更多信息請看「NFC的Intent過濾」。一般,在NDEF消息不能被映射到MIME類型或URI時,或者被掃描到的NFC標籤不包含NDEF數據時,NFC標籤調度系統會嘗試啓動一個ACTION_TECH_DISCOVERED類型的Intent。更多信息,請看「NFC標籤調度系統」。 2. 應用程序接收到Intent對象時,從該Intent對象中獲取Tag對象: Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 3. 經過調用android.nfc.tech包中對應類的一個get工廠方法,來獲取一個TagTechnology對象實例。在調用get工廠方法以前,經過調用getTechList()方法來枚舉NFC標籤所支持的技術。例如,用下列方法從Tag對象中獲取MifareUltralight對象實例: MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)); |
2.1.2 讀寫NFC標籤
Reading and writing to an NFC tag involves obtaining the tag from the intent and opening communication with the tag. You must define your own protocol stack to read and write data to the tag. Keep in mind, however, that you can still read and write NDEF data when working directly with a tag. It is up to you how you want to structure things. The following example shows how to work with a MIFARE Ultralight tag. |
讀寫NFC標籤,要涉及到從Intent對象中獲取標籤,並要打開與標籤的通訊。要讀寫NFC標籤數據,你必需要定義本身的協議棧。可是,要記住在直接使用NFC標籤工做時,你依然可以讀寫NDEF數據。這是你想要如何構建的事情。下例演示瞭如何使用MIFARE超薄標籤來工做: |
2.2 使用前臺調度系統
The foreground dispatch system allows an activity to intercept an intent and claim priority over other activities that handle the same intent. Using this system involves constructing a few data structures for the Android system to be able to send the appropriate intents to your application. To enable the foreground dispatch system: |
前臺調度系統容許一個Activity攔截Intent對象,而且聲明該Activity的優先級要比其餘的處理相同Intent對象的Activity高。使用這個系統涉及到爲Android系統構建一些數據結構,以便可以把相應的Intent對象發送給你的應用程序,如下是啓用前臺調度系統的步驟: |
1 Add the following code in the onCreate() method of your activity:
PendingIntent pendingIntent =PendingIntent.getActivity( this,0,newIntent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
IntentFilter ndef =newIntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try{ ndef.addDataType("* } catch(MalformedMimeTypeException e){ thrownewRuntimeException("fail", e); } intentFiltersArray =newIntentFilter[]{ndef,};
techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
|
1. 在你的Activity的onCreate()方法中添加下列代碼: A. 建立一個PendingIntent對象,以便Android系統可以在掃描到NFC標籤時,用它來封裝NFC標籤的詳細信息。 PendingIntent pendingIntent =PendingIntent.getActivity( this,0,newIntent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0); B. 聲明你想要截獲處理的Intent對象的Intent過濾器。前臺調度系統會在設備掃描到NFC標籤時,用聲明的Intent過濾器來檢查接收到的Intent對象。若是匹配就會讓你的應用程序來處理這個Intent對象,若是不匹配,前臺調度系統會回退到Intent調度系統。若是Intent過濾器和技術過濾器的數組指定了null,那麼就說明你要過濾全部的退回到TAG_DISCOVERED類型的Intent對象的標籤。如下代碼會用於處理全部的NDEF_DISCOVERED的MIME類型。只有在須要的時候才作這種處理: IntentFilter ndef =newIntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try{ ndef.addDataType("* } catch(MalformedMimeTypeException e){ thrownewRuntimeException("fail", e); } intentFiltersArray =newIntentFilter[]{ndef,}; C. 創建一個應用程序但願處理的NFC標籤技術的數組。調用Object.class.getName()方法來獲取你想要支持的技術的類: techListsArray = new String[][] { new String[] { NfcF.class.getName() } }; |
2 Override the following activity lifecycle callbacks and add logic to enable and disable the foreground dispatch when the activity loses (onPause()) and regains (onResume()) focus. enableForegroundDispatch() must be called from the main thread and only when the activity is in the foreground (calling in onResume() guarantees this). You also need to implement the onNewIntent callback to process the data from the scanned NFC tag. publicvoid onPause(){ super.onPause(); mAdapter.disableForegroundDispatch(this); }
publicvoid onResume(){ super.onResume(); mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray); }
publicvoid onNewIntent(Intent intent){ Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); //do something with tagFromIntent }
|
2. 重寫下列Activity生命週期的回調方法,而且添加邏輯在Activity掛起(onPause())和得到焦點(onResume())時,來啓用和禁用前臺調度。enableForegroundDispatch()方法必須在主線程中被調用,而且只有在該Activity在前臺的時候(要保證在onResume()方法中調用這個方法)。你還須要實現onNewIntent回調方法來處理掃描到的NFC標籤的數據: publicvoid onPause(){ super.onPause(); mAdapter.disableForegroundDispatch(this); }
publicvoid onResume(){ super.onResume(); mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray); }
publicvoid onNewIntent(Intent intent){ Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); //do something with tagFromIntent } |
See the ForegroundDispatch sample from API Demos for the complete sample |
完整的示例請看API Demo中的ForegroundDispatch |