APPFORUM2014 Helping the developer community build next-generation, multi-platform apps. SCHAUMBURG, ILLINOIS SEPTEMBER 8-10
NFC OVERVIEW Chuck Bolen Chief Architect Enterprise Mobile Computing APPFORUM2014
Agenda Overview of NFC Reading Writing NFC tags from your Android Applications Using Android Beam in your Application Magic Trick using Android Beam
What is Near Field Communication? Set of standards to establish radio communication between a device and tag or two devices by touching them together Based on 13.56 MHz RFID technologies Short-range (<4cm) wireless technology Range can be a feature for security / privacy Low data-rates (106-424 kbit/s) No connection setup / limited or no user interaction required 4
NFC Components Passive tags Powered NFC devices 6
NFC Tags NFC Tags vary in shape and complexity of capability Basic tags offer just read and write semantics, sometimes with one-time-programmable Generally 100s of bytes of data depending on type More complex have cryptographic hardware to authenticate access to a sector. The data stored in the tag can be written in a variety of proprietary formats Most of the Android framework APIs are based around a NFC Forum standard format called NDEF (NFC Data Exchange Format)
What do NFC tags look like? Standardized: NFC Forum Type 1 4 Also common: Mifare 8 2011 Nokia Nokia NFC Development v2.0.4 November 10, 2011 Andreas Jakl Tag embedded in a creditcard style event badge
What do NFC tags look like? Backside reveals the antenna and chip 9 2011 Nokia Nokia NFC Development v2.0.4 November 10, 2011 Andreas Jakl
Operating Modes of NFC Reader / Writer NFC Applications NFC APIs Peer to Peer NFC Service Base Band Card Emulation NFC Controller Antenna
What can you do with NFC? Enable Admin mode in your applications Transfer receipt to customer Field Service worker check in when at customer site Store service data on tag attached to a piece of equipment Record location of guards during rounds NFC App Ideas Customer Loyalty cards Utility Meter reading Disable WiFi, enable BT when delivery driver enters truck Transfer url for YouTube video clip of product demo to customer smartphone Automatically Configure device settings
NFC Support in Android Reading NDEF data from an NFC tag Supports most common tag technologies Reading raw bytes from a non NDEF tag Tag Technology Specific Beaming NDEF messages from one device to another with Android Beam (peer to peer) Host Based Card Emulation
NFC Data Exchange (NDEF) Format NDEF Message Record 1 Record 2... Record n Header Payload Type Name Format (TNF) Value TNF Type ID Length Empty NFC Well Known MIME Absolute URI External 0x00 0x01 0x02 0x03 0x04
Well Know NDEF Record Types NDEF Record Type Description Specification Reference Sp Smart Poster NFC Forum Smart Poster RTD T Text NFC Forum Text RTD U URI NFC Forum URI RTD Gc Generic Control NFC Forum Generic Control RTD** Hr Handover Request NFC Forum Connection Handover Specification Hs Handover Select NFC Forum Connection Handover Specification Hc Handover Carrier NFC Forum Connection Handover Specification Sig Signature NFC Forum Signature RTD
NFC Tag Intent Dispatch System Android system is always looking for NFC tags Application don t need to directly read Tags When a tag is read the system launches the corresponding application automatically Based on TNF and Type An application that wants to handle discovered NFC tags register an intent filter for the type of Data/Tags they want to handle
NFC Demo NDEF MESSAGE 0x01 =TNF well known U = URI developer.motorolasoluti ons.com/community/and roid
Card Emulation Card Emulation with a Secure Element Host-based Card Emulation
Intent Refresher (very high level) Intents are messages between applications and/or the Android OS Activities, services, and broadcast receivers are activated through intents Primary method for inter-process communication within Android Intents can indicate an operation to be performed or an indication of something that has happened Sending ACTION_CALL dials a phone number ACTION_BATTERY_LOW intent broadcast when battery is low Additional data can be passed with the Intent as a name-value pair, referred to as extras For example, ACTION_TIMEZONE_CHANGED intent has a "time-zone" extra that identifies the new time zone The extra for ACTION_CALL is the number to dial An application registers a filter in its AndroidManifext.xml to indicate which Intents it handles
How NFC Tags are Dispatched to Applications Intent ACTION_NDEF_DISCOVERED ACTION_TECH_DISCOVERED ACTION_TAG_DISCOVERED Description Sent to application is registered to handle the MIME/URI type of the payload data discovered Sent if no Application is registered to handle the MIME/URI type of the NDEF payload or if the tag does not contain NDEF data but is of a known tag technology. This intent is started if no activities handle the ACTION_NDEF_DISCOVERED or ACTION_TECH_DISCOVERED Intents
Tag Dispatch System
Android Application Records (AAR) Bypasses tag dispatch logic to ensure specific application is started when an NFC tag is scanned An AAR has the package name of an application embedded inside an NDEF record Uses TNF External type An AAR can be in any NDEF record of an NDEF message 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. Introduced in Android 4.0 (API level 14)
Foreground Dispatch system You can override AARs and the intent dispatch system with the Foreground dispatch system Allows the foreground activity to have priority when an NFC tag is discovered Useful for Writing or Formatting a tag See the ForegroundDispatch sample from API Demos for a complete sample.
Working with Non NDEF Tags ACTION_TAG_DISCOVERED sent to application when tag of registered technology is read Applications communication directly with the tag and read/write to it with their own protocol (raw bytes) Android provides TagTechnology classes for working with specific tag types For more details see http://developer.android.com/guide/topics/connectivit y/nfc/advanced-nfc.html
Specifying Technologies an Activity Supports Tech-list XML resource file in in the <project-root>/res/xml folder <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>
OK, Lets get to some Code!! Reading and Writing NFC Tags in Android
NFC Elements in the Android Manifest Permission to access the NFC hardware: <uses-permission android:name="android.permission.nfc" /> Minimum SDK Version at least 10 <uses-sdk android:minsdkversion="10"/> Advertise required uses of NFC HW feature [optional] <uses-feature android:name="android.hardware.nfc" android:required="true" /> Alternatively check for NFC availability at runtime by checking to see if, getdefaultadapter() is null.
Creating Common Types of NDEF Records Use the Helpers within NFCRecord Class Method createapplicationrecord(string packagename) createexternal(string domain, String type, byte[] data) createmime(string mimetype, byte[] mimedata) createuri(string uristring) createuri(uri uri) Description Create a new Android Application Record (AAR) Create a new NDEF Record containing external (application-specific) data Create a new NDEF Record containing MIME data. Create a new NDEF Record containing a URI Create a new NDEF Record containing a URI
How to write an NDEF message Error Checking omitted for clarity public void onnewintent(intent intent) { //Foreground dispatch discovered tag with ACTION_NDEF_TAG Intent Tag tag = intent.getparcelableextra(nfcadapter.extra_tag); // Easy way: creates a URI record NdefRecord.createUri("http://www.motorolasolutions.com"); // Create a message from the record NdefMessage ndefmessage = new NdefMessage(uriRecord); // Error Checking, i.e. is tag NDEF formatted, omitted Ndef ndef = Ndef.get(tag); ndef.connect(); } ndef.writendefmessage(message); ndef.close(); 32
Registering for Intent Filters Inside <Activity> section of AndroidManifest.xml Filter for ACTION_NDEF_DISCOVERED 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> Filter for ACTION_NDEF_DISCOVERED with a filters for a URI in the form of http://developer.motorolasolutions.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.motorolasolutions.com" android:pathprefix="/index.html" /> </intent-filter>
Obtaining Information from Intents When activity starts due to an NFC intent, you can obtain information about the scanned NFC tag from the intent extra data EXTRA_TAG A Tag object representing the scanned tag EXTRA_NDEF_MESSAGES An array of NDEF messages parsed from the tag (minimum of one) Mandatory for ACTION_NDEF_DISCOVERED intents Optional for ACTION_TECH_DISCOVERED and ACTION_TAG_DISCOVERED
Android Beam (Peer to Peer) The idea behind Beam: share what s shown on screen Bring two NFC-capable devices in range Either user can touch to send Data that application selected is transferred On screen data (i.e. a photo) Context Settings NFC needs to be enabled in settings
Please Don t Do This!! The magic of beam is that is does not require user interaction it Just Works 20
How to Integrate Android Beam Android Beam data flow Device A Activity X Sending Application Data (NDEF) Device B Activity Y Receiving Application startactivity(nfcintent); NFC Service NFC Service Data (NDEF) NFC Data (NDEF) 39
How to pass the NDEF message Use the setndefpushmessage... APIs NfcAdapter.setNdefPushMessage(NdefMessage msg, Activity activity, Activity...); OR NfcAdapter.setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity...); 40
How to pass the NDEF message Use the setndefpushmessage... APIs public class X extends Activity implements NfcAdapter.CreateNdefMessageCallback { protected void oncreate() { NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this); } // Set the callback adapter.setndefpushmessagecallback(this, this); // Alternatively, use the static set function: // adapter.setndefpushmessage(msg, this); 41
How to pass the NDEF message Use the setndefpushmessage... APIs // Called when the NFC link comes up, don't block or sleep! public NdefMessage createndefmessage() { // Create NDEF message msg with payload byte[] payload = new byte[] ({0x00, 0x01}); NdefRecord mimerecord = NdefRecord.createMime( application.vnd/mime, payload); } return new NdefMessage(mimeRecord); 30
Sending a file over Bluetooth is Hard? 43
Android Beam for Media Initiate with NFC but move data over Bluetooth Uses Bluetooth Secure Simple Pairing to silently create connection and transfer file Send photos, videos any files with Android Beam Introduced in Jellybean 44
Beam Push Application flow How it works Device A Sending Application setbeampushuris(uri[]); Device B Receiving Application startactivity() with ACTION_VIEW Intent NFC Service NFC Service Stores binary data in file Mac AddressNFC Bluetooth Binary data 45
NFC Beam Example protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this); // Create Uri for a file Uri MyUri = Uri.parse("file:///" + Environment.getExternalStorageDirectory().getAbsolutePath() + "//test.jpg ); // Set the Uri to be Beamed over BT adapter.setbeampushuris(new Uri[] {MyUri}, this); Notes: URI(s) are only made available for Beam when the specified activity(s) are in resumed (foreground) state. Recommended approach is to call this method during your Activity's oncreate(bundle)
Beam Demo
Beam Demo
Beam Demo
More Information Android NFC Developer Guide http://developer.android.com/guide/topics/connectivity/nfc/index.html NFC Forum http://www.nfc-forum.org/home/ Professional NFC Application Development for Android, Vedat Coskun Kerem Ok, Busra Ozdenizci Wrox publisher, ISBN: 978-1-118-38009-3
THANK YOU APPFORUM2014