編輯:Android開發實例
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.
近場通信(NFC)是一個短范圍無線技術集合,通常需要4厘米或更短的距離才能初始化連接。NFC允許在NFC標簽和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).
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.
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一起工作的場景主要有兩個:
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 a ACTION_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 type TNF_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 an ACTION_NDEF_DISCOVERED intent along with other information about the tag, such as the payload. On the other hand, if it encounters a record of type TNF_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是縮短的格式(<domain_name>:<service_name)被編碼到NDEF類型中。
Android會把這個URN映射成以下格式的URI:vnd.android.nfc://ext/<domain_name>:<service_name>
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 <uses-permission> element to access the NFC hardware:
<uses-permission android:name="android.permission.NFC" />
2 The minimum SDK version that your application can support. API level 9 only supports limited tag dispatch via ACTION_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.
<uses-sdk android:minSdkVersion="10"/>
3 The uses-feature element so that your application shows up in Google Play only for devices that have NFC hardware:
<uses-feature android:name="android.hardware.nfc" android:required="true" />
1. 在<uses-permission>元素中聲明訪問NFC硬件:
<uses-permission android:name="android.permission.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消息推送給其他設備的方法。
<uses-sdkandroid:minSdkVersion="10"/>
3. 使用uses-feature元素,在Google Play中,以便你的應用程序能夠只針對有NFC硬件的設備來顯示。
<uses-featureandroid:name="android.hardware.nfc"android:required="true"/>
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:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" />
</intent-filter>
The following example filters for a URI in the form of http://developer.android.com/index.html.
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="http"
android:host="developer.android.com"
android:pathPrefix="/index.html" />
</intent-filter>
要過濾ACTION_NDEF_DISCOVERED類型的Intent,就要在清單中跟你想要過濾的數據一起來聲明該類型的Intent過濾器。
以下是過濾text/plain類型的MIME的ACTION_NDEF_DISCOVERED類型過濾器的聲明:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" />
</intent-filter>
以下示例使用http://developer.android.com/index.html格式的URI來過濾:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="http"
android:host="developer.android.com"
android:pathPrefix="/index.html" />
</intent-filter>
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 <project-root>/res/xml folder.
以下示例定義了所有的相關的技術。你可以根據需要刪除其中一些設置。然後把這個文件保存到<project-root>/res/xml文件夾中(你能夠把命名為任何你希望的名字):
- <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <tech-list>
- <tech>android.nfc.tech.IsoDep</tech>
- <tech>android.nfc.tech.NfcA</tech>
- <tech>android.nfc.tech.NfcB</tech>
- <tech>android.nfc.tech.NfcF</tech>
- <tech>android.nfc.tech.NfcV</tech>
- <tech>android.nfc.tech.Ndef</tech>
- <tech>android.nfc.tech.NdefFormatable</tech>
- <tech>android.nfc.tech.MifareClassic</tech>
- <tech>android.nfc.tech.MifareUltralight</tech>
- </tech-list>
- </resources>
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技術的標簽相匹配:
- <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <tech-list>
- <tech>android.nfc.tech.NfcA</tech>
- <tech>android.nfc.tech.Ndef</tech>
- </tech-list>
- </resources>
- <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <tech-list>
- <tech>android.nfc.tech.NfcB</tech>
- <tech>android.nfc.tech.Ndef</tech>
- </tech-list>
- </resources>
In your AndroidManifest.xml file, specify the resource file that you just created in the <meta-data> element inside the <activity> element like in the following example:
在你的AndroidManifest.xml文件中,要像向下列示例那樣,在<activity>元素內的<meta-data>元素中指定你創建的資源文件:
- <activity>
- ...
- <intent-filter>
- <action android:name="android.nfc.action.TECH_DISCOVERED"/>
- </intent-filter>
- <meta-data android:name="android.nfc.action.TECH_DISCOVERED"
- android:resource="@xml/nfc_tech_filter" />
- ...
- </activity>
To filter for ACTION_TAG_DISCOVERED use the following intent filter:
使用下列Intent過濾器來過濾ACTION_TAG_DISCOVERED類型的Intent:
- <intent-filter>
- <action android:name="android.nfc.action.TAG_DISCOVERED"/>
- </intent-filter>
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.
[email protected] android.nfc.NfcAdapter#EXTRA_ID
(optional): The low-level ID of the tag.
1. EXTRA_TAG(必須的):它是一個代表了被掃描到的標簽的Tag對象;
2. EXTRA_NDEF_MESSAGES(可選):它是一個解析來自標簽中的NDEF消息的數組。這個附加信息是強制在Intent對象上的;
3. [email protected] 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消息。
- public void onResume() {
- super.onResume();
- ...
- if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().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
- }
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 of TNF_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過濾器如下:
- <intent-filter>
- <action android:name="android.nfc.action.NDEF_DISCOVERED" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:scheme="http"
- android:host="developer.android.com"
- android:pathPrefix="/index.html" />
- </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過濾器如下:
- <intent-filter>
- <action android:name="android.nfc.action.NDEF_DISCOVERED" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:mimeType="application/vnd.com.example.android.beam" />
- </intent-filter>
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-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
對應的Intent過濾器如下:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
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:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http"
android:host="example.com"
android:pathPrefix="" />
</intent-filter>
對應的Intent過濾器如下:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http"
android:host="example.com"
android:pathPrefix="" />
</intent-filter>
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過濾器如下:
- <intent-filter>
- <action android:name="android.nfc.action.NDEF_DISCOVERED" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:scheme="vnd.android.nfc"
- android:host="ext"
- android:pathPrefix="/com.example:externalType"/>
- </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 the NdefMessage. This is because the Android system checks the first record of an NdefMessage 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())
- /**
- * The Android Application Record (AAR) is commented out. When a device
- * receives a push with an AAR in it, the application specified in the AAR
- * is guaranteed to run. The AAR overrides the tag dispatch system.
- * You can add it back in to guarantee that this
- * activity starts when receiving a beamed message. For now, this code
- * uses the tag dispatch system.
- */
- //,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);
- }
- /**
- * Parses the NDEF Message from the intent and prints to the TextView
- */
- 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過濾器,在技術上不是必須的:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="application/vnd.com.example.android.beam"/>
</intent-filter>
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記錄中嵌入標識信息,以及對應的過濾器。
2 Advanced NFC
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 by android.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標簽所支持的技術)
類
介紹
TagTechnology
所有的NFC標簽技術類必須實現的接口。
NfcA
提供對NFC-A(ISO 14443-3A)屬性和I/O操作的訪問。
NfcB
提供對NFC-B(ISO 14443-3B)屬性和I/O操作的訪問。
NfcF
提供對NFC-F(ISO 6319-4)屬性和I/O操作的訪問。
NfcV
提供對NFC-V(ISO 15693)屬性和I/O操作的訪問。
IsoDep
提供對NFC-A(ISO 14443-4)屬性和I/O操作的訪問。
Ndef
提供對NDEF格式的NFC標簽上的NDEF數據和操作的訪問。
NdefFormatable
提供了對可以被NDEF格式化的NFC標簽的格式化操作。
The following tag technlogies are not required to be supported by Android-powered devices.
Table 2. Optional supported tag technologies (表2.可選的NFC標簽所支持的技術)
類
介紹
MifareClassic
如果Android設備支持MIFARE,那麼它提供了對經典的MIFARE類型標簽屬性和I/O操作的訪問。
MifareUltralight
如果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超薄標簽來工作:
View Code? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103package
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;
publicclassMifareUltralightTagTester{
privatestaticfinalString TAG =MifareUltralightTagTester.
class
.getSimpleName();
publicvoid 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 closing MifareUltralight..."
, e);
}
finally
{
try
{
ultralight.close();
}
catch
(IOException e){
Log.e(TAG,
"IOException while closing MifareUltralight..."
, e);
}
}
}
publicString readTag(Tag tag){
MifareUltralight mifare =MifareUltralight.get(tag);
try
{
mifare.connect();
byte
[] payload = mifare.readPages(
4
);
returnnewString(payload,Charset.forName(
"US-ASCII"
));
}
catch
(IOException e){
Log.e(TAG,"IOException
while
writing MifareUltralight
message...", e);
}
finally
{
if
(mifare !=
null
){
try
{
mifare.close();
}
catch
(IOException e){
Log.e(TAG,
"Error closing tag..."
, e);
}
}
}
returnnull;
}
}
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("*/*"); /* Handles all MIME based dispatches.
You should specify only the ones that you need. */
}
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("*/*"); /* Handles all MIME based dispatches.
You should specify only the ones that you need. */
}
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
Android應用程序可以在許多不同地區的許多設備上運行。為了使應用程序更具交互性,應用程序應該處理以適合應用程序將要使用的語言環境方面的文字,數字,文件等。在本章中,我
Android應用程序可以在許多不同地區的許多設備上運行。為了使應用程序更具交互性,應用程序應該處理以適合應用程序將要使用的語言環境方面的文字,數字,文件等。在本章中,我
前面文章介紹了Activity以及Intent的使用,本文就來介紹Service。如果把Activity比喻為前台程序,那麼Service就是後台程序,Servi
Android作為一個偉大的系統,自然提供了設置默認打開程序的實現.在這篇文章中,我會介紹如何在Android系統中設置默認的程序. 在設置默認程序之前,無非有兩