20.08.2016 Views

Professional Android 4 Application Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Near Field Communication x 697<br />

Introducing <strong>Android</strong> Beam<br />

<strong>Android</strong> Beam, introduced in <strong>Android</strong> 4.0 (API level 14), provides a simple API for an application to<br />

transmit data between two devices using NFC, simply by placing them back-to-back. For example,<br />

the native contacts, browser, and YouTube applications use <strong>Android</strong> Beam to share the currently<br />

viewed contact, web page, and video, respectively, with other devices.<br />

To beam messages, your application must be in the foreground and the device<br />

receiving the data must not be locked.<br />

<strong>Android</strong> Beam is initiated by tapping two NFC-enabled <strong>Android</strong> devices<br />

together. Users are presented with a “touch to beam” UI, at which point they<br />

can choose to “beam” the foreground application to the other device.<br />

<strong>Android</strong> Beam uses NFC to push NDEF messages between devices when they are physically placed<br />

together.<br />

By enabling <strong>Android</strong> Beam within your application, you can define the payload of the beamed<br />

message. If you don’t customize the message, the default action for your application will be to<br />

launch it on the target device. If your application isn’t installed on the target device, the Google Play<br />

Store will launch and display your application’s details page.<br />

To define the message your application beams, you need to request the NFC permission in the<br />

manifest:<br />

<br />

The process to define your own custom payload is described as follows:<br />

1. Create an NdefMessage object that contains an NdefRecord that contains your message<br />

payload.<br />

2. Assign your Ndef Message to the NFC Adapter as your <strong>Android</strong> Beam payload.<br />

3. Configure your application to listen for incoming <strong>Android</strong> Beam messages.<br />

Creating <strong>Android</strong> Beam Messages<br />

To create a new Ndef Message, create a new NdefMessage object that contains at least one<br />

NdefRecord containing the payload you want to beam to your application on the target device.<br />

When creating a new Ndef Record, you must specify the type of record it represents, a MIME<br />

type, an ID, and a payload. There are several common types of Ndef Record that can be used to<br />

transmit data using <strong>Android</strong> Beam; note that they should always be the first record added to each<br />

beamed message.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!