Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> Android NFC Reference中英文對照

Android NFC Reference中英文對照

編輯:Android開發實例

0 Near Field Communication

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)的標准。

1 NFC Basic

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來跟其他設備共享通信錄、網頁和視頻。

 

 

1.1 NFC標簽調度系統   (The Tag Dispatch System)

 

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:

      
  1. Parsing the NFC tag and figuring out the MIME type or a        URI        that identifies the data payload in the tag.
      
  1. Encapsulating the MIME type or URI and the payload into        an intent. These first two steps are described in How NFC tags are mapped to MIME types and URIs.
  2.   
  3. Starts an        activity based on the intent. This is described in How NFC Tags are Dispatched to        Applications

為了幫助你達到這個目標,Android提供了特殊的標簽調度系統,來分析掃描到的NFC標簽,通過解析數據,在被掃描到的數據中嘗試找到感興趣的應用程序,具體做法如下:

1.   解析NFC標簽並搞清楚標簽中標識數據負載的MIME類型或URI;

2.   把MIME類型或URI以及數據負載封裝到一個Intent中。

3.   基於Intent來啟動Activity。

 

1.1.1 怎樣把NFC標簽映射到MIME類型和URI  (How NFC tags are mapped to MIME types and URIs)

 

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

 

1.1.2 應用程序如何調度NFC標簽(How NFC Tags are Dispatched to Applications)

 

 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:

      
  1. ACTION_NDEF_DISCOVERED: This intent is used to start an Activity when a tag        that contains an NDEF payload is scanned and is of a recognized type.        This is the highest priority intent, and the tag dispatch system tries        to start an Activity with this intent before any other intent, whenever        possible.
      
  1. ACTION_TECH_DISCOVERED: If no activities register to handle the        ACTION_NDEF_DISCOVERED intent, the tag dispatch system tries to start an        application with this intent. This intent is also directly started        (without starting ACTION_NDEF_DISCOVERED first) if the tag that is        scanned contains NDEF data that cannot be mapped to a MIME type or URI,        or if the tag does not contain NDEF data but is of a known tag        technology.
      
  1. ACTION_TAG_DISCOVERED: This intent is started if no activities handle the        ACTION_NDEF_DISCOVERED or ACTION_TECH_DISCOVERED intents.

 當標簽調度系統完成對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. Try to start an Activity with the intent that was        created by the tag dispatch system when parsing the NFC tag (either        ACTION_NDEF_DISCOVERED or ACTION_TECH_DISCOVERED).
  2.   
  3. If no activities        filter for that intent, try to start an Activity with the next lowest        priority intent (either ACTION_TECH_DISCOVERED or ACTION_TAG_DISCOVERED)        until an application filters for the intent or until the tag dispatch        system tries all possible intents.
  4.   
  5. If no        applications filter for any of the intents, do nothing.

    標簽調度系統的基本工作方法如下:

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

 

1.2 在Android的Manifest中申請NFC訪問

 

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是否有效。

1.3 過濾NFC的Intent (Filtering for NFC Intents)

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.

      
  1. However, you usually want to filter for        the ACTION_NDEF_DISCOVERED intent for the most control of when your application        starts.
  2.   
  3. The        ACTION_TECH_DISCOVERED intent is a fallback for        ACTION_NDEF_DISCOVERED when no applications filter for        ACTION_NDEF_DISCOVERED or for when the payload is not NDEF.
  4.   
  5. Filtering for ACTION_TAG_DISCOVERED is usually too general of a category to filter on. Many        applications will filter for ACTION_NDEF_DISCOVERED or        ACTION_TECH_DISCOVERED before ACTION_TAG_DISCOVERED, so your application        has a low probability of starting.  ACTION_TAG_DISCOVERED is only        available as a last resort for applications to filter for in the cases        where no other applications are installed to handle the        ACTION_NDEF_DISCOVERED or ACTION_TECH_DISCOVEREDintent.

 要在你想要處理被掃描到的NFC標簽時啟動你的應用程序,可以在你的應用程序的Android清單中針對一種、兩種或全部三種類型的NFC的Intent來過濾。

      
  1. 但是,通常想要在應用程序啟動時控制最常用的ACTION_NDEF_DISCOVERED類型的Intent。
  2.   
  3. 在沒有過濾ACTION_NDEF_DISCOVERED類型的Intent的應用程序,或數據負載不是NDEF時,才會從ACTION_NDEF_DISCOVERED類型的Intent回退到ACTION_TECH_DISCOVERED類型的Intent。
  4.   
  5. 通常ACTION_TAB_DISCOVERED是最一般化的過濾分類。很多應用程序都會在過濾ACTION_TAG_DISCOVERED之前,過濾ACTION_NDEF_DISCOVERED或ACTION_TECH_DISCOVERED,這樣就會降低你的應用程序被啟動的可能性。ACTION_TAG_DISCOVERED只是在沒有應用程序處理ACTION_NDEF_DISCOVERED或ACTION_TECH_DISCOVERED類型的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對象。

1.3.1  ACTION_NDEF_DISCOVERED

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>

1.3.2 ACTION_TECH_DISCOVERED

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文件夾中(你能夠把命名為任何你希望的名字):

 

  1. <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> 
  2.  
  3.  
  4.  
  5. <tech-list> 
  6.  
  7.  
  8.  
  9. <tech>android.nfc.tech.IsoDep</tech> 
  10.  
  11.  
  12.  
  13. <tech>android.nfc.tech.NfcA</tech> 
  14.  
  15.  
  16.  
  17. <tech>android.nfc.tech.NfcB</tech> 
  18.  
  19.  
  20.  
  21. <tech>android.nfc.tech.NfcF</tech> 
  22.  
  23.  
  24.  
  25. <tech>android.nfc.tech.NfcV</tech> 
  26.  
  27.  
  28.  
  29. <tech>android.nfc.tech.Ndef</tech> 
  30.  
  31.  
  32.  
  33. <tech>android.nfc.tech.NdefFormatable</tech> 
  34.  
  35.  
  36.  
  37. <tech>android.nfc.tech.MifareClassic</tech> 
  38.  
  39.  
  40.  
  41. <tech>android.nfc.tech.MifareUltralight</tech> 
  42.  
  43.  
  44.  
  45. </tech-list> 
  46.  
  47.  
  48.  
  49. </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技術的標簽相匹配:

 

  1. <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> 
  2.  
  3.  
  4.  
  5. <tech-list> 
  6.  
  7.  
  8.  
  9. <tech>android.nfc.tech.NfcA</tech> 
  10.  
  11.  
  12.  
  13. <tech>android.nfc.tech.Ndef</tech> 
  14.  
  15.  
  16.  
  17. </tech-list> 
  18.  
  19.  
  20.  
  21. </resources> 
  22.  
  23.  
  24.  
  25. <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> 
  26.  
  27.  
  28.  
  29. <tech-list> 
  30.  
  31.  
  32.  
  33. <tech>android.nfc.tech.NfcB</tech> 
  34.  
  35.  
  36.  
  37. <tech>android.nfc.tech.Ndef</tech> 
  38.  
  39.  
  40.  
  41. </tech-list> 
  42.  
  43.  
  44.  
  45. </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>元素中指定你創建的資源文件:

  1. <activity> 
  2.  
  3.  
  4.  
  5. ... 
  6.  
  7.  
  8.  
  9. <intent-filter> 
  10.  
  11.  
  12.  
  13. <action android:name="android.nfc.action.TECH_DISCOVERED"/> 
  14.  
  15.  
  16.  
  17. </intent-filter> 
  18.  
  19.  
  20.  
  21. <meta-data android:name="android.nfc.action.TECH_DISCOVERED" 
  22.  
  23.  
  24.  
  25. android:resource="@xml/nfc_tech_filter" /> 
  26.  
  27.  
  28.  
  29. ... 
  30.  
  31.  
  32.  
  33. </activity> 

1.3.3 ACTION_TAG_DISCOVERED

 

To filter for ACTION_TAG_DISCOVERED   use the following intent filter:

使用下列Intent過濾器來過濾ACTION_TAG_DISCOVERED類型的Intent:

 

  1. <intent-filter> 
  2. <action android:name="android.nfc.action.TAG_DISCOVERED"/> 
  3. </intent-filter> 

.3.4 從Intent中獲取信息  (Obtaining information from intents)

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消息。

 

  1. public void onResume() { 
  2. super.onResume(); 
  3. ... 
  4. if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) { 
  5.     Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); 
  6.     if (rawMsgs != null) { 
  7.         msgs = new NdefMessage[rawMsgs.length]; 
  8.         for (int i = 0; i < rawMsgs.length; i++) { 
  9.             msgs[i] = (NdefMessage) rawMsgs[i]; 
  10.         } 
  11.     } 
  12.  
  13. //process the msgs array 
  14.  

 

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);

1.4 創建通用的NDEF記錄類型 (Creating Common Types of NDEF Records)

 

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消息的第一條記錄。

1.4.1 TNF_ABSOLUTE_URI

 

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過濾器如下:

  1. <intent-filter> 
  2. <action android:name="android.nfc.action.NDEF_DISCOVERED" /> 
  3. <category android:name="android.intent.category.DEFAULT" /> 
  4. <data android:scheme="http" 
  5.            android:host="developer.android.com" 
  6.            android:pathPrefix="/index.html" /> 
  7. </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過濾器如下:

  1. <intent-filter> 
  2. <action android:name="android.nfc.action.NDEF_DISCOVERED" /> 
  3. <category android:name="android.intent.category.DEFAULT" /> 
  4. <data android:mimeType="application/vnd.com.example.android.beam" /> 
  5. </intent-filter> 

 

.4.3 TNF_WELL_KNOWN和RTD_TEXT

 

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()方法:

  1. byte[] payload; //assign to your data 
  2. String domain = "com.example"; //usually your app's package name 
  3. String type = "externalType"; 
  4. NdefRecord extRecord = NdefRecord.createExternal(domain, type, payload); 

Creating the NdefRecord   manually:

手動的創建NdefRecord:

  1. byte[] payload; 
  2. ... 
  3. NdefRecord extRecord = new NdefRecord( 
  4. NdefRecord.TNF_EXTERNAL_TYPE, "com.example:externalType", new byte[0], payload); 

The intent filter for the previous NDEF records would look   like this:

對應的Intent過濾器如下:

  1. <intent-filter> 
  2. <action android:name="android.nfc.action.NDEF_DISCOVERED" /> 
  3. <category android:name="android.intent.category.DEFAULT" /> 
  4. <data android:scheme="vnd.android.nfc" 
  5. android:host="ext" 
  6. android:pathPrefix="/com.example:externalType"/> 
  7. </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過濾器。

1.5 Android應用程序記錄(Android Application Record---AAR)

 

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. Try to start an Activity using an intent filter as         normal. If the Activity that matches the intent also matches the AAR,         start the Activity.
    2.    
    3. If the Activity         that filters for the intent does not match the AAR, if multiple         Activities can handle the intent, or if no Activity handles the intent,         start the application specified by the AAR.
    4.    
    5. If no         application can start with the AAR, go to Google Play to download the         application based on the AAR.
    6.   

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:

 

  1. NdefMessage msg = new NdefMessage( 
  2. new NdefRecord[] { 
  3. ..., 
  4. NdefRecord.createApplicationRecord("com.example.android.beam")} 

1.6 把NDEF消息發射到其他設備上

 

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:

      
  1. setNdefPushMessage(): Accepts an NdefMessage to set as the message to beam. Automatically        beams the message when two devices are in close enough proximity.
  2.   
  3. setNdefPushMessageCallback(): Accepts a        callback that contains a createNdefMessage() which is        called when a device is in range to beam data to. The callback lets you        create the NDEF message only when necessary.

通過調用下列兩個方法中的任意一個,就能夠為你的應用程序啟用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:

      
  1. The activity that is beaming the data must be in the        foreground. Both devices must have their screens unlocked.
  2.   
  3. You must        encapsulate the data that you are beaming in an NdefMessage object.
  4.   
  5. The NFC device        that is receiving the beamed data must support        the com.android.npp NDEF push protocol or NFC Forum's SNEP        (Simple NDEF Exchange Protocol). The com.android.npp protocol        is required for devices on API level 9 (Android 2.3) to API level 13        (Android 3.2). com.android.npp and SNEP are both required on        API level 14 (Android 4.0) and later.

一個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:

      
  1. Create an NdefMessage that contains the NdefRecords that you want to push onto the other device.
  2.   
  3. Call setNdefPushMessage() with        a NdefMessage or        call setNdefPushMessageCallback passing in        aNfcAdapter.CreateNdefMessageCallback object in        the onCreate() method of your activity. These methods require        at least one activity that you want to enable with Android Beam, along        with an optional list of other activities to activate.

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記錄的方法:

 

  1. package com.example.android.beam; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.Intent; 
  5. import android.nfc.NdefMessage; 
  6. import android.nfc.NdefRecord; 
  7. import android.nfc.NfcAdapter; 
  8. import android.nfc.NfcAdapter.CreateNdefMessageCallback; 
  9. import android.nfc.NfcEvent; 
  10. import android.os.Bundle; 
  11. import android.os.Parcelable; 
  12. import android.widget.TextView; 
  13. import android.widget.Toast; 
  14. import java.nio.charset.Charset; 
  15.  
  16. publicclassBeamextendsActivityimplementsCreateNdefMessageCallback{ 
  17. NfcAdapter mNfcAdapter; 
  18. TextView textView; 
  19.  
  20. @Override 
  21. publicvoid onCreate(Bundle savedInstanceState){ 
  22. super.onCreate(savedInstanceState); 
  23.  setContentView(R.layout.main); 
  24. TextView textView =(TextView) findViewById(R.id.textView); 
  25. // Check for available NFC Adapter 
  26.  mNfcAdapter =NfcAdapter.getDefaultAdapter(this); 
  27. if(mNfcAdapter ==null){ 
  28. Toast.makeText(this,"NFC is not available",Toast.LENGTH_LONG).show(); 
  29.  finish(); 
  30. return; 
  31. // Register callback 
  32.  mNfcAdapter.setNdefPushMessageCallback(this,this); 
  33.  
  34. @Override 
  35. publicNdefMessage createNdefMessage(NfcEventevent){ 
  36. String text =("Beam me up, Android!\n\n"+ 
  37. "Beam Time: "+System.currentTimeMillis()); 
  38. NdefMessage msg =newNdefMessage( 
  39. newNdefRecord[]{ createMime( 
  40. "application/vnd.com.example.android.beam", text.getBytes()) 
  41. /** 
  42.  * The Android Application Record (AAR) is commented out. When a device 
  43.  * receives a push with an AAR in it, the application specified in the AAR 
  44.  * is guaranteed to run. The AAR overrides the tag dispatch system. 
  45.  * You can add it back in to guarantee that this 
  46.  * activity starts when receiving a beamed message. For now, this code 
  47.  * uses the tag dispatch system. 
  48.  */ 
  49. //,NdefRecord.createApplicationRecord("com.example.android.beam") 
  50. }); 
  51. return msg; 
  52.  
  53. @Override 
  54. publicvoid onResume(){ 
  55. super.onResume(); 
  56. // Check to see that the Activity started due to an Android Beam 
  57. if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())){ 
  58.  processIntent(getIntent()); 
  59.  
  60. @Override 
  61. publicvoid onNewIntent(Intent intent){ 
  62. // onResume gets called after this to handle the intent 
  63.  setIntent(intent); 
  64.  
  65. /** 
  66.  * Parses the NDEF Message from the intent and prints to the TextView 
  67.  */ 
  68. void processIntent(Intent intent){ 
  69.  textView =(TextView) findViewById(R.id.textView); 
  70. Parcelable[] rawMsgs = intent.getParcelableArrayExtra( 
  71. NfcAdapter.EXTRA_NDEF_MESSAGES); 
  72. // only one message sent during the beam 
  73. NdefMessage msg =(NdefMessage) rawMsgs[0]; 
  74. // record 0 contains the MIME type, record 1 is the AAR, if present 
  75.  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. Filter for an ACTION_TECH_DISCOVERED         intent specifying the tag technologies that you want to handle. See Filtering for NFC intents for         more information. In general, the tag dispatch system tries to start a ACTION_TECH_DISCOVERED         intent when an NDEF message cannot be mapped to a MIME type or URI, or         if the tag scanned did not contain NDEF data. For more information on         how this is determined, see The Tag Dispatch System.
    2.   
      
         
    1. When your application receives the intent, obtain the         Tag object from the intent:
    2.   
      
         
    1. Obtain an instance of a TagTechnology, by calling one of         theget factory methods of the classes in the android.nfc.tech package. You can         enumerate the supported technologies of the tag by calling getTechList() before calling a get         factory method. For example, to obtain an instance of MifareUltralight from a Tag, do the following:
    2.   

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 103 package com.example.android.nfc;   import android.nfc.Tag;   import android.nfc.tech.MifareUltralight;   import android.util.Log;   import java.io.IOException;   import java.nio.charset.Charset;           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:

      
  1. Create a PendingIntent object so the Android system can populate it with the        details of the tag when it is scanned.

 PendingIntent pendingIntent   =PendingIntent.getActivity(

                 this,0,newIntent(this,   getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);

      
  1. Declare intent filters to handle the intents that you        want to intercept. The foreground dispatch system checks the specified        intent filters with the intent that is received when the device scans a        tag. If it matches, then your application handles the intent. If it does        not match, the foreground dispatch system falls back to the intent        dispatch system. Specifying a null array of intent filters and        technology filters, specifies that you want to filter for all tags that        fallback to the TAG_DISCOVERED intent. The code snippet below handles        all MIME types for NDEF_DISCOVERED. You should only handle the ones that        you need.

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,};

      
  1. Set up an array of tag technologies that your        application wants to handle. Call the Object.class.getName() method to        obtain the class of the technology that you want to support.

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

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved