Android NFC Workshop MobDevCon 2013


Published on

Slides from the NFC kickstarter workshop at MobDevCon 2013

Source code is available on github :

Any questions please shout me on twitter! @jameselsey1986

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • My name is James Elsey, I ’ m a software developer at Smart421 working on a variety of enterprise java applications, and more recently mobile applications.
  • I ’ m currently working at O2…
  • … Working with this stuff
  • … But secretly love doing this stuff
  • Todays session will take just over an hour, we have a lot to get through, and time permitting we can achieve this. We have about 10 minutes of slides, and then will jump into some coding At the end of the session I ’ ll take QA, and provide links to the slides, source code, references, and my details should you have anything you want to ask me about Firstly we ’ ll cover some of the basics of NFC and the NDEF format, then we ’ ll jump in to reading/writing plain text tags. We ’ ll then have a look at writing URI tags. After that we ’ ll discuss a few of the NFC goodies that have been introduced with Ice cream sandwich such as android application records for ensuring that your app is launched or downloaded, and then beaming data between devices. AAR for zxing :
  • So, what is an NFC tag? They look very similar to RFID tags that you may have seen on the back of CDs and DVDs whilst browsing at your favourite music store. They often come in sticker format but you can also buy wristbands, keyrings, business cards etc with NFC tags embedded. NFC != RFID RFID has a greater range , meters rather than centimeters RFID is one way, you read a tag and that is it NFC 3 modes: Read/write – for tags Peer to peer – Android beaming. 4.1 jelly bean introduced advanced beaming where a bluetooth connection is established to transfer more data Card Emulation
  • In 2004 Sony, Nokia and Phillips founded the NFC forum Now has over 170 members, including : Google Intel HP LG Various financial companies Visa Barclaycard American Express Mastercard Proxama are also a member of the forum
  • In 2007 the NFC Forum published the specification for 4 types of NFC tags. The key differences between the tags are their memory sizes and read/write speeds. Probably most likely to use type 2 tags Type 2 tags come in 2 flavours, 48 bytes and 144 bytes. The white tags are type2 144. Usages Type 1 - Type 2 - Mifare Ultralight – Cheap and often disposable, used in Football world cup 2006 Germany - NTAG203, according to ZipNFC (sellers) is by far the most popular tag. Type 3 – Type 4 - NXP DESFire – Oyster card (was using Mifare classic)
  • As you can see there are some variations of type 2 tags. The ultralight tags generally speaking wont have enough space to store an AAR unless the package name is really short. NTAG203’s are the white round stickers, they’re good general purpose tags with enough capacity to store AARs and urls.
  • There are typically 1 NDEF Message in a tag and for the most part you can safely work against this assumption The NDEF message may have multiple NDEF Records in a tag Identifier - Rarely used, but can be used to uniquely identify your tag 3-bit TNF (Type Name Format) Indicates how to interpret the variable length type field. Valid values are described in described in Table 1 . such as TNF_WELL_KNOWN or TNF_MIME_MEDIA 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 . such as RTD_URI or RTD_TEXT 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.
  • Responsible for working out what to do with a tag when it is discovered Parsing the NFC tag and figuring out the MIME type or a URI that identifies the data payload in the tag. 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 . Starts an activity based on the intent. This is described in How NFC Tags are Dispatched to Applications .
  • IF an NDEF tag is discovered, android checks to see if anything is registered to handle NDEF discovered, otherwise it checks TECH_DISCOVERED
  • Firstly you need to add the uses-permission into the manifest to request usage of the hardware Next you need to set the minSDK level (2.3 - 2.3.2 Gingerbread) - 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. (2.3.3 - 2.3.4 Gingerbread MR1) - API level 10 includes comprehensive reader/writer support as well as foreground NDEF pushing (4.0 - 4.0.2 Ice Cream Sandwich) - 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. Lastly, you can optionally set : <uses-feature android:name="android.hardware.nfc" android:required="true" /> This means that only devices with NFC hardware can download your app from the app store, you may like to omit this if NFC isn't critical to your app
  • Grab the intent, we need to see the intent that invoked our application, was it a launcher? Was it a tag? Check if the intent has the action of ACTION_NDEF_DISCOVERED, if its not, we ’ re not interested Get the ndef messages from the extras bundle and then begin to extract the payloads
  • Use android studio, cutting edge IDE released during Google I/O 2013 (early access preview however) Create a new project via the wizard, may have to fiddle with setup values or move project around after creating in an empty directory Setup manifest: <uses-permission android:name="android.permission.NFC" /> (this should be put in by the project wizard) <uses-sdk android:minSdkVersion="10"/> Deploy app to device Scan a tag Notice how it displays the activity chooser - This is a massive NOOB ERROR and completely goes against the principle of simplicity for NFC Create an activity to handle plain text tags Add this into manifest <activity android:name="com.mobdevcon.nfckickstarter.PlainTextTagReader"> <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> </intent-filter> </activity> Scan again and notice how the app now loads for a plain text tag Explain how the activity starts, then we check intent for action, then check extras and begin to decode the messages
  • Same process for writing the tag as the plain text example Only different is the RTD
  • Check if application is already installed by searching for package name If installed, invoke the application If not installed, direct to app on market place Excellent mechanism for promoting your app via tags (conferences etc) Embed an android application record into the ndef message
  • Show how to use
  • AAR working ok? That means you should have ZXing, great, now bookmark this to read on the train home later : Youtube google i/o video
  • Beaming is basically Peer to peer NFC, which was introduced in Ice cream sandwich. Used for exchange of data between android devices Very useful for exchanging data between the same application running on multiple devices, such as sharing contacts and urls. The application receiving the beam must be in the foreground, and the device not locked When the devices come in close contact, the “ touch to beam ” ui is displayed Relatively simple to use in comparison to existing NFC topics we ’ ve covered
  • Avoid the intent chooser, the idea of nfc is to be quick and seamless Write protect tags where possible to prevent hijacking Rule of thumb, i/o should not be on the main thread! Use wrapper libraries such as Ndef tools to avoid using such low level APIs.
  • at work Put an nfc on your laptop, that enables silent mode, turns on wifi In the car Put an nfc sticker on the dash, enables GPS and bluetooth In your wallet Run out of business cards? Ready made vCard good to go In the gym Create an nfc keyring that enables airplane mode and starts your favourite playlist
  • You’re probably all thinking “where can I get some tags from”? We’ve bought from rapid nfc and have found them to be good (disclaimer, we’re not connected with RapidNfc in any way, just found them to be a good place to get tags from!) Feel free to take away the place mats for your own use too.
  • Android NFC Workshop MobDevCon 2013

    1. 1. Android NFC Workshop @JamesElsey1986 @Smart421
    2. 2. Agenda 1. Overview of tags and NDEF a. Types of tags b. Tag Dispatch System c. Different NDEF messages d. Legacy tags 2. Read a plain text tag 3. Write a plain text tag 4. Write a URI tag 5. Android application records (AAR) 6. Beaming data between devices
    3. 3. What is an NFC tag?
    4. 4. NFC Forum
    5. 5. Types of NFC Tag Type 1 Tag Type 2 Tag Type 3 Tag Type 4 Tag Compatible Products Broadcom Topaz NXP Mifare Ultralight, NXP Mifare Ultralight C, NXP NTAG203 Sony FeliCa NXP DESFire / NXP SmartMX-JCOP Memory Size 96 Bytes 48 Bytes / 144 Bytes 1, 4, 9 KB 4 KB /32 KB Unit Price Low Low High Medium I High Data Access Read/Write or Read-Only Read/Write or Read-Only Read/Write or Read-Only Read/Write or Read- Only source:
    6. 6. Variations of Type 2 tags Source : Ultralight Ultralight C NTAG203 Memory Size 64 bytes 192 bytes 168 bytes User Memory 46 bytes 137 bytes 137 bytes URL Length 41 chars 132 chars 132 chars Text Length 39 chars 130 chars 130 chars Best Use Cost effective, short URL, smart poster and general NFC use. For applications required encryption tech only. Latest chip, best performance. Great for everything from marketing to task launcher apps. Cost £0.40 £0.80 £0.40
    7. 7. NDEF
    8. 8. Tag Dispatch System What happens when a tag is detected? 1.Analyse the tag 2.Categorise the data 3.Start an application that is interested in the categorised data Applications declare intent filters to request the ability to handle the data
    9. 9. Tag Dispatch System
    10. 10. Enabling NFC in your app 1. Request permission to the NFC hardware o <uses-permission android:name="android.permission.NFC" /> 1. Set SDK level o <uses-sdk android:minSdkVersion="10"/> 1. (optionally) Set uses feature so app only shows on Google Play if the device has NFC hardware o <uses-feature android:name="android.hardware.nfc" android:required="true" />
    11. 11. Reading a plain text tag 1. Grab the intent 2. Check if action is ACTION_NDEF_DISCOVERED 3. Get EXTRA_NDEF_MESSAGES from the extras bundle 1. Extract the payloads from the NdefRecords
    12. 12. Reading a plain text tag (demo time)
    13. 13. Writing a tag 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); return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data); } private NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
    14. 14. Write a plain text tag (demotime!)
    15. 15. Write a URI to a tag • Same as plain text • Use RTD_URI instead of RTD_TEXT
    16. 16. Write protecting a tag Formatted Tags: ndef.connect(); ndef.writeNdefMessage(message); ndef.makeReadOnly() Make read only during format: format.connect(); format.formatReadOnly(message);
    17. 17. Android Application Records • Introduced in 4.0 • Ensures application is opened if available • Directs to marketplace if not installed NdefRecord.createApplicationRecord( "”)
    18. 18. Android Application Records (demo time)
    19. 19. Google I/O 2011 - How to NFC
    20. 20. Beaming Data between devices
    21. 21. Best Practices • Avoid intent chooser! • Write protect tags where possible • Move the NFC read/writing off the main thread • Use a wrapper such as Ndef tools for android
    22. 22. Resources Android SDK docs for NFC Google I/O NFC video Excellent overview on NDEF standards http:// NDEF Tools for Android
    23. 23. Usages of NFC? • At work • In the car • In your wallet • In the gym & more!
    24. 24. Where to get NFC Tags? •
    25. 25. QA
    26. 26. Thanks for attending! @jameselsey1986