BlackBerry Java SDK

Networking and connectivity Version: 7.0 Beta
Development Guide

Published: 2011-05-31 SWD-1683136-0530104202-001

Contents
1 Networking and connectivity overview............................................................................................................ 2 Network connections........................................................................................................................................ Architecture: Network transports..................................................................................................................... Code sample: Determining network transports with sufficient coverage using the Network API............ Code sample: Determining the status of a network transport using the Network API............................. The Network API............................................................................................................................................... Choosing network transports using the Network API............................................................................... Opening a network connection using the Network API............................................................................ Generic Connection Framework....................................................................................................................... Open a network connection using the GCF............................................................................................... Send and receive data using a network connection......................................................................................... Using the BlackBerry Enterprise Server as a network gateway........................................................................ Using a wireless service provider's Internet gateway....................................................................................... Send and receive data using a network connection......................................................................................... Code sample: Retrieving a web page using the Network API........................................................................... Code sample: Retrieving a web page using the GCF......................................................................................... 3 Communication API.......................................................................................................................................... Communicating with HTTP servers................................................................................................................... Request data using a BlockingSenderDestination object.......................................................................... Request data using a NonBlockingSenderDestination object................................................................... Send data using a FireAndForgetDestination object................................................................................. Parsing a common Internet data format.......................................................................................................... Parse a JSON data structure...................................................................................................................... Code sample: Parsing a JSON data structure............................................................................................. Sending login information to an HTTP server................................................................................................... 4 Subscribing to a push initiator.......................................................................................................................... Subscribe to a push initiator............................................................................................................................. 5 Working with radios.......................................................................................................................................... Query a radio's availability and change its status............................................................................................. Code sample: Controlling radios................................................................................................................ 6 Near Field Communication............................................................................................................................... Working with smart tags................................................................................................................................... Create an NDEF tag writer................................................................................................................................ 3 4 5 7 9 11 11 11 13 14 15 18 18 19 22 26 30 31 32 36 41 42 43 46 50 51 52 54 54 55 58 58 58

Code sample: Creating an NDEF tag writer............................................................................................... Create an NDEF tag reader............................................................................................................................... Code sample: Creating an NDEF tag reader............................................................................................... Communicate with an ISO14443 smart tag...................................................................................................... Code sample: Communicating with an ISO 14443 tag............................................................................... 7 Glossary............................................................................................................................................................ 8 Provide feedback.............................................................................................................................................. 9 Document revision history................................................................................................................................ 10 Legal notice.......................................................................................................................................................

62 65 68 70 72 75 78 79 80

the Communication API requires BlackBerry Device Software 6. BlackBerry Device Software version The Network API provides a simple interface to access many 5. Each transport offers different advantages. You would need to write your own code to perform similar tasks on devices that run BlackBerry Device Software 5. including: • Type of user • Importance of security and reliability • Networks that the application must use and support for roaming users • Amount of data that you expect to send and receive • Need to proactively push data for updates and alerts • Location of the destination server (Internet or intranet) The BlackBerry® Java® SDK 7.Beta Customers Only. you should consider whether the API exists in the version of the BlackBerry® Device Software that your target devices are likely to run. You can also use technologies such as Bluetooth® to communicate with accessories. The GCF provides a flexible way to create network 4. GPRS. and NFC to communicate with smart tags. Content and software are subject to change. The Communication API encapsulates all of the operations 6. 3 . you should consider a number of different factors.RIM Confidential and Proprietary Information .0 and earlier. you should choose the transport that is most appropriate for your requirements. API Network API Generic Connection Framework Communication API Description In addition to the functionality that each API provides. When you choose a transport for your application. The BlackBerry solution also enables server-side applications to proactively push data to BlackBerry devices in a highly secure and reliable manner.0 and later connections using the transport of your choice. For example. or Wi-Fi® technology.0. As a developer.0 and later connection-related options and network transports. to communicate over wireless connections.0 includes the following APIs that you can use to open a network connection. Networking and connectivity overview 1 A BlackBerry® device uses radio communication technologies such as CDMA. BlackBerry devices work with different network transports over those radio technologies to connect to the Internet or a private network.0 and later that are required to connect to an HTTP server that is located on the Internet or behind an organization's firewall.

First. However. The following table suggests preference orders for consumer and enterprise applications that target users on CDMA and GPRS wireless networks. For example. and setting a wide variety of parameters for a connection. 4. The Network API provides a simple interface for working with network transports.0 TCP Cellular 4 . You can use the GCF to create network connections on devices that run previous versions of the BlackBerry Device Software.0 BlackBerry® Mobile Data System BlackBerry MDS TCP Wi-Fi TCP Cellular BlackBerry Internet Service WAP 2.RIM Confidential and Proprietary Information . 5. you should be aware that not all transports support all protocols. 3. TCP Wi-Fi® BlackBerry® Internet Service WAP 2. a protocol. you open a network connection. the process of creating a network connection is similar. 2.0 GPRS 1. WAP 1. Content and software are subject to change. TCP Wi-Fi® TCP Cellular BlackBerry® Internet Service WAP 2. The BlackBerry Application Platform supports the following protocols: • • • • • • HTTP HTTPS Socket TLS SSL UDP (Datagram) The protocol and the end point are determined by your application. 3.Beta Customers Only. Applications that target BlackBerry® devices that run BlackBerry® Device Software 5. but the transport is determined by your users' operating environment. 5. 4. 2. However. 2.1 only support HTTP over WAP and HTTPS over WAP or WTLS.0 and later can use the Network API. and finally close the connection. 3. 5. 3. using the GCF requires knowledge of more BlackBerry® APIs to discover what transports are available and how to configure them. CDMA Consumer 1. Enterprise 1. You may need to try more than one transport before you can make a successful connection. you usually specify a transport. then read and write data over that connection. Regardless of which API you choose. and an end point. 4. 2. Before you open a connection.0 BlackBerry® Mobile Data System TCP Cellular BlackBerry MDS TCP Wi-Fi BlackBerry Internet Service WAP 2. 5.0 and 1. 1. You can connect to network resources using a wide range of protocols. Network connections 2 The BlackBerry® Application Platform offers two APIs that you can use to create network connections manually: the Network API and the GCF. 4.

When you are ready to use your connection. For example. you receive a Connection object that represents your connection. POST. After you open a connection. For more information about sending data over the connection. OutputConnection Description This interface provides methods to set the HTTP request method (GET. This interface exposes methods to send data to and receive data from a network host over a socket connection. see the InputStream and OutputStream classes in the API reference for the BlackBerry® Java® SDK.microedition.Beta Customers Only.io package contains several interfaces that you can use to manipulate a Connection object.io package to access the Connection object's send and receive functions. Not all devices have access to all transports. These interfaces provide access to a connection's input and output data streams. Those interfaces expose the Connection object's input and output streams. This interface includes all of the methods in the HttpConnection interface. 5 . Interface HttpConnection HttpsConnection SocketConnection SecureConnection UDPDatagramConnection InputConnection. Content and software are subject to change. This interface provides methods to retrieve information about the connection. This interface provides methods to create TLS and SSL socket connections. You will need the InputConnection and OutputConnection interfaces from the javax. and send and receive data over the connection. This interface includes all of the methods in the SocketConnection interface.RIM Confidential and Proprietary Information . The javax. Architecture: Network transports A BlackBerry® device can connect to a wireless network by using different transports. cast the Connection object according to the protocol that you used to open the connection. and create new datagram objects.microedition. the BlackBerry® Mobile Data System transport is only available to devices registered with a BlackBerry® Enterprise Server. and so on) and headers. and adds getSecurityInfo() that returns the certificate that is supplied by the web server. and adds getSecurityInfo() that returns security information about the connection.

Beta Customers Only. Network transport TCP Wi-Fi® Description The Wi-Fi transport creates a connection to the Internet. When the Wi-Fi radio is turned on. Earlier versions of BlackBerry® Device Software send data through the least expensive transport.RIM Confidential and Proprietary Information . rather than the fastest. 6 . a BlackBerry® device user or an application can configure the device to connect to the Internet using this transport. a device running BlackBerry 6 or later automatically sends data using the fastest data connection. If there are multiple transport services available. Content and software are subject to change. or to private networks such as those in an organization or home.

Beta Customers Only.ui. see "Using a wireless service provider's Internet gateway".2. you should test it for each wireless service provider that your application might use. To support this transport. you must sign up for the Push Service. and 2.component. a user or wireless service provider must configure the WAP connection parameters on the device. WAP 1. import net. see the knowledge base article at http://supportforums. you should test it for each wireless service provider that your application might use. 7 .api. For more information. For more information.api.transport. 1. For more information about retrieving a connection ID. If your application uses this transport.rim. Most wireless service providers configure a user's BlackBerry device to use the provider's Internet gateway.rim.*.*. this transport might not be supported on all wireless networks or with all data plans.blackberry. If your application uses this transport.device. Network transport TCP Cellular Description The TCP Cellular transport creates a connection to the Internet through a wireless service provider's Internet gateway. The WAP transport creates a connection through a wireless service provider's WAP gateway.device. Note: To use the BlackBerry Internet Service transport. when the user roams on a different network.*.RIM Confidential and Proprietary Information . you will need to retrieve the connection ID from the service book.blackberry. However.0 are supported. Data that you send and receive using this transport is compressed and optimized for transmission over wireless connections. import net.0.com/ developers/pushservice The BlackBerry MDS transport enables a BlackBerry device to connect to its associated BlackBerry Enterprise Server through the BlackBerry Infrastructure or using a Wi-Fi connection. the user needs to configure the device manually to use the Internet gateway on the host network.device. Content and software are subject to change. To use WAP 2.com/t5/JavaDevelopment/What-Is-Network-API-alternative-for-legacy-OS/ta-p/ 614822 BlackBerry Internet Service BlackBerry MDS WAP Code sample: Determining network transports with sufficient coverage using the Network API import net.ui. The BlackBerry Internet Service transport creates a connection to the Internet through the BlackBerry® Infrastructure.rim.io. As a result.0. This method creates the most direct type of connection that uses the cellular radio.api. visit www.

container. RichTextField _rtfDisplay. for(int i = _transports. } } class ListTransportsWithCoverageScreen extends MainScreen { private private private private int[] _transportsWithCoverage.add(_rtfDisplay). ButtonField _btnShowTransports. } public NetworkSample() { pushScreen(new ListTransportsWithCoverageScreen()). add(vfm).enterEventDispatcher().api. --i) { switch(_transports[i]. int context) { getTransports().getCoverageStatus(). i >=0. _transportsWithCoverage = TransportInfo.*.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field. vfm.1.add(_btnShowTransports). _transports = TransportInfo.FIELD_HCENTER). Content and software are subject to change. import net. public class NetworkSample extends UiApplication { public static void main(String[] args) { NetworkSample app = new NetworkSample().").getTransportDescriptors (_transportsWithCoverage).RIM Confidential and Proprietary Information .device. setTitle("Network Sample").TRANSPORT_BIS_B: 8 . sb. } public void getTransports() { StringBuffer sb = new StringBuffer().getTransportType()) { case TransportInfo. public ListTransportsWithCoverageScreen() { VerticalFieldManager vfm = new VerticalFieldManager().ui. _btnShowTransports. TransportDescriptor[] _transports. vfm. app. _btnShowTransports = new ButtonField ("Show Transports". } }).append("The transports currently available are: \n").rim. Field.Beta Customers Only. _rtfDisplay = new RichTextField ("Click button below to display available transports.length .

append("BlackBerry Internet Service\n").rim.api. "WAP 1.append("BlackBerry Mobile Data Service\n").0/1. case TransportInfo. } } class ProbeSpecificTransportScreen extends MainScreen implements FieldChangeListener { private TextField _tfTransportStatus.toString()).api. } Code sample: Determining the status of a network transport using the Network API import import import import net.io. public ProbeSpecificTransportScreen() { String[] strTransportNames = {"none". break.*. net. } } } _rtfDisplay.1". public class NetworkSample extends UiApplication { public static void main(String[] args) { NetworkSample app = new NetworkSample(). case TransportInfo. sb.device.append("TCP Cellular\n"). } public NetworkSample() { pushScreen(new ProbeSpecificTransportScreen()).device. case TransportInfo. break. Content and software are subject to change. break.TRANSPORT_TCP_CELLULAR: sb.RIM Confidential and Proprietary Information .TRANSPORT_WAP2: sb. case TransportInfo. break.component.append("TCP WiFi\n").TRANSPORT_WAP: sb. break.ui.enterEventDispatcher(). app.api.container.rim. "TCP Cellular".*.rim.api.append("WAP 2.*. case TransportInfo. private ObjectChoiceField _ocfTransports.append("WAP 1.device.device. net.ui.ui.0\n").setText(sb.rim.transport.Beta Customers Only.1\n").0 or 1. break. 9 .TRANSPORT_MDS: sb. net.TransportInfo.TRANSPORT_TCP_WIFI: sb.

} } 10 .getChoice(intTransportType) + " is available.getSelectedIndex(). " + (String)_ocfTransports.setChangeListener(this). "TCP WiFi" }. then click 'Probe Transport'"). "MDS". "BIS". btnProbe.add(_ocfTransports)."). Content and software are subject to change. _tfTransportStatus = new TextField(Field. _tfTransportStatus.add(btnProbe). add(vfm). } public void fieldChanged(Field field. } } else { _tfTransportStatus.RIM Confidential and Proprietary Information .setText ("Select a transport from the list above.setText("Sorry.FIELD_HCENTER). Field. 0.setText ("Please select a transport first.").getChoice(intTransportType) + " is not available.FIELD_HCENTER).isTransportTypeAvailable(intTransportType)) { if(TransportInfo.setText ((String)_ocfTransports."). ButtonField btnProbe = new ButtonField("Probe Transport". vfm.getChoice(intTransportType) + " is available but has insufficient coverage.Beta Customers Only. _ocfTransports.setText ((String)_ocfTransports. "WAP 2.0". strTransportNames. } } else { _tfTransportStatus.FIELD_HCENTER).setEditable(true). if(intTransportType > 0) { if(TransportInfo.add(_tfTransportStatus). vfm. Field. _ocfTransports = new ObjectChoiceField ("Select Transport to Probe: ". then click 'Probe Transport'").hasSufficientCoverage(intTransportType)) { _tfTransportStatus. int context) { int intTransportType = _ocfTransports. vfm. VerticalFieldManager vfm = new VerticalFieldManager(). } else { _tfTransportStatus.

You can retrieve a list of transports that currently have coverage. If you don't provide an ordered list of preferred transports when you open a connection.io.1 transports require information about an APN. You should also create a CoverageStatusListener object (in the net.rim.device. Content and software are subject to change. you can open a connection and use it to send and receive data. Be sure that you call getConnection() on a thread that is separate from the main event thread. the WAP 1. However.0 and 1.RIM Confidential and Proprietary Information . • Delay between connection attempts. the Network API chooses a transport for you. } The Network API The Network API is implemented in the net.io. For more information. • Maximum time to spend making connection attempts. The API steps through an array of transport types that you set by using ConnectionFactory.Beta Customers Only. and register it using TransportInfo. After you list your preferred transports. For example. you can use the ConnectionFactory to configure connection options such as: • Maximum number of connection attempts.options packages. Most of the functionality is provided by the ConnectionFactory and TransportInfo classes.io. In addition to your preferred transports. you should prioritize the transports that your application uses based on the type of user that your application targets. see the Thread class in the API reference for the BlackBerry® Java® SDK.addListener().getConnection() methods. 11 .api. The device notifies your application about changes in coverage status so that your application can respond appropriately. The ConnectionFactory object is responsible for opening connections. Choosing network transports using the Network API In the Network API. A ConnectionFactory object returns a ConnectionDescriptor object that contains a Connection object and information about the transport over which the connection was opened.device.rim. see "Network transport options".setPreferredTransportTypes().device. Opening a network connection using the Network API After you decide which network transports to use. you should invoke one of the ConnectionFactory. the TransportInfo class provides information about the network transports that are available on a BlackBerry® device.transport package). For more information about creating a thread.api.transport. • Whether or not encryption is required between the connection end points. When you are ready to open a connection. or use the API to determine whether a particular transport is available and has coverage. and the gateway authentication.rim. and so on. you should set options for any transports that require specific options.transport and net.api.

tcpOptions).rim.setTransportTypeOptions(TransportInfo. Thread t = new Thread(new Runnable() { public void run() { ConnectionDescriptor cd = _factory. Open a network connection using the Network API CAUTION: The ConnectionFactory.setAttemptsLimit(5).*.Beta Customers Only.*.io. factory. so set the TCP Cellular transport options.api. When you open a connection successfully. Create an ordered list of preferred transports. tcpOptions.device.api. then ConnectionFactory returns a ConnectionDescriptor object that you can use. Configure the options for the TCP Cellular transport. If the connection was successful. pass the ConnectionDescriptor object to another method (displayContent()) that is responsible for displaying the content. } 4.io.setTunnelAuthPassword("password").api. You should create a separate thread to call getConnection().rim. ConnectionFactory factory = new ConnectionFactory().isDefaultAPNSet()) { tcpOptions.TransportInfo.TRANSPORT_TCP_WIFI. TCP Cellular is one of the preferred transports. tcpOptions.rim. The ConnectionDescriptor contains a Connection object.RIM Confidential and Proprietary Information .rim. see Open a network connection using the Network API and Send and receive data using a network connection.TRANSPORT_TCP_CELLULAR } 3. the ConnectionFactory returns a ConnectionDescriptor object. In this step. TcpCellularOptions tcpOptions = new TcpCellularOptions().io.setApn("My APN"). 6. net. factory. TransportInfo.UiApplication. Import the required classes and interfaces.device.device. int[] intTransports = { TransportInfo.api. Create a thread to retrieve the connection. TransportInfo. Content and software are subject to change. Create a ConnectionFactory object. 5. Set any other ConnectionFactory options that are applicable to your application.transport. For more information.getConnection 12 . 2. if(!TcpCellularOptions. import import import import net.TRANSPORT_WAP2. if applicable.ui. net.setTunnelAuthUsername("user").options.transport. and information about the transport that was used to open the connection. net.TRANSPORT_TCP_CELLULAR.device. In this case. 1.transport.getConnection() method blocks thread execution.

push a screen that uses a Connection parameter to retrieve and display the content. Generic Connection Framework If you develop applications for BlackBerry® device users who are running BlackBerry® Device Software 4. } ("http://www. you need to use the GCF to open a network connection. Implement displayContent(). The connection string that is used by the GCF comprises three parts: <scheme> : <hierarchical location information> . The <hierarchical location information> describes the end point for the connection. For example. You can call Connector. in the following code sample. The open() method accepts a connection string that specifies the type of connection to make. if(cd != null) { Connection c = cd.invokeLater(new Runnable() { public void run() { UiApplication. the connection string specifies the HTTP protocol and uses a host name to indicate the connection end point. In this case. after the connection retrieval thread completes. and optional configuration details for the connection. For a complete code sample. 7. see "Code sample: Retrieving a web page using the Network API".getUiApplication().com"). For more information about transport options. However. and provides authentication details for a proxy server if they are required. see "Network transport options". The interface=wifi parameter is included to specify that the Wi-Fi® radio should be used to establish the connection. see "Send and receive data using a network connection". } }). the end point. <additional information> The <scheme> indicates the protocol to use to establish the connection. any code that you write that uses the GCF also runs on later versions of BlackBerry® Device Software. t. the <additional information> controls the transport that is used. displayContent(c).Connector class. 13 .pushScreen(new HTTPOutputScreen(conn)). } After you finish: For more information about using a connection and implementing the HTTPOutputScreen class.start().Beta Customers Only.getConnection().open() to create any type of supported connection. } }). private void displayContent(final Connection conn) { UiApplication.blackberry.7 or earlier.RIM Confidential and Proprietary Information .getUiApplication().microedition. The GCF is implemented in the javax. Finally.io. Content and software are subject to change.

1.com. 7. import net. open() returns a Connection object that you can use. Start your thread. Import the required classes and interfaces. If the connection attempt was successful. CAUTION: The Connector.Beta Customers Only.io. HTTPConnection c = (HTTPConnection)Connector. t. Thread t = new Thread(new Runnable() { public void run() { 3. Specify the connection string.blackberry.rim.open() method is not thread-safe.interface=wifi").open("http://www. Connection conn = null. Implement displayContent().start().deviceside=false").IOException. } 6. Before you begin: Make sure that the transport that you want to use is available and has coverage. push a screen that uses a Connection parameter to retrieve and display the content. You can use a similar process to open a connection using other protocols and transports.open("http:// example. import javax. } catch (IOException e) { // Process your error condition } 5.microedition.RIM Confidential and Proprietary Information . after the connection retrieval thread completes.*.ui. try { conn = Connector. Invoke open(). Create a local variable for your Connection object. Pass the connection object to another method (displayContent()) that is responsible for displaying the content.UiApplication. Open a network connection using the GCF The following task shows you how to open an HTTP connection using the BlackBerry® Mobile Data System transport.api. 4.io. 14 . Ensure that you invoke open() on a thread that is separate from the main event thread. import java. In this case.device. Content and software are subject to change. } }).com. Create a new thread to open the connection. if (conn != null) { displayContent(conn). 2.

ui. Import the required classes and interfaces. } }).component. You can use a similar process to send and receive data using other network protocols. java. CAUTION: Network input and output operations are not thread-safe.pushScreen(new HTTPOutputScreen(conn)). import import import import import import import net.device.MainScreen.device.ui.rim.getUiApplication().device. and implementing the HTTPOutputScreen class.UiApplication.api.Beta Customers Only.io. public class HTTPOutputScreen extends MainScreen { 3. } After you finish: For more information about using a connection.invokeLater(new Runnable() { public void run() { UiApplication.container. RichTextField _rtfOutput = new RichTextField(). Content and software are subject to change. Send and receive data using a network connection The following task shows you how to send and receive data using an HTTP connection to a web site. net.RichTextField. 4.api.io.microedition. Normally.rim.*. 2. net. the following code sends an HTTP GET command manually to a server. see "Send and receive data using a network connection". 1. Create a class that extends the MainScreen class.rim. javax. public HTTPOutputScreen(Connection conn) { 15 . To make this task as general as possible.getUiApplication().IOException. Create a constructor that accepts a Connection object as an argument. private void displayContent(final Connection conn) { UiApplication.api. java. you would use an HttpConnection interface.OutputStream.InputStream. The data that is returned from the web site is displayed on the screen.io. Make sure that you create a separate thread when you use a Connection object.ui. which constructs the HTTP command string according to the options that you configure. see "Code sample: Retrieving a web page using the GCF". see Open a network connection using the Network API or Open a network connection using the GCF. For more information about opening network connections.io.RIM Confidential and Proprietary Information . Create an instance variable for a RichTextField object to display the results. java. For a complete code sample. Before you begin: Open a network connection and pass a Connection object to the constructor of the class that is developed in this task.

"). ContentReaderThread(Connection conn) { _connection = conn. Add the RichTextField to your screen. 5. Create an OutputConnection object to send data over your connection. Create a method to populate your RichTextField with the data that is returned from the web site. Content and software are subject to change. t. create a thread to communicate with the web server. public void showContents(final String result) { UiApplication. add(_rtfOutput). 16 . 10. OutputStream os = null. _rtfOutput. private final class ContentReaderThread extends Thread { private Connection _connection. Retrieve an OutputStream from your OutputConnection. ContentReaderThread t = new ContentReaderThread(conn).. 6. os.openOutputStream(). Initialize a String object to store the response from the web site. try { OutputConnection outputConn = (OutputConnection) connection. } } }).RIM Confidential and Proprietary Information . and start a thread to access the network connection. 11. Accept a ConnectionDescriptor object as an argument.0\r\n\r\n".start(). String getCommand = "GET " + "/" + " HTTP/1.setText(result). InputStream is = null. You invoke this method in step 20.. Initialize an OutputStream object and an InputStream object to exchange data with the web site.getBytes()). after ContentReaderThread completes. 7.setText("Retrieving data. String result = "". os. os = outputConn.write(getCommand.Beta Customers Only.getUiApplication(). } public void run() { 8. In an inner class. 9.flush(). Please wait.invokeLater(new Runnable() { public void run() { _rtfOutput.

RIM Confidential and Proprietary Information . } catch(IOException e) { } } 19. Send an HTTP GET command to the web server over your OutputStream. Content and software are subject to change. result = new String(data). if(os != null) { try { os.Beta Customers Only.close().flush().close().IOUtilities. 12. String getCommand = "GET " + "/" + " HTTP/1. InputConnection inputConn = (InputConnection) connection. } catch(IOException e) { // process the error condition } } 18. Retrieve an InputStream from your InputConnection. Convert the GET command into a byte array.write(getCommand. 15. } 17. Close your InputStream.device.toString().io. Close your Connection.streamToBytes(is). Retrieve the stream data and store it in a byte array. catch(Exception e) { result = "ERROR fetching content: " + e.getBytes()). os. os.rim. Create an InputConnection object to receive data from your connection. 14. 16. Close your OutputStream.api.openInputStream(). is = inputConn. byte[] data = net.0\r\n\r\n". if(is != null) { try { is. 13. Catch any errors that might be generated by your procedure. 17 .

you can also use either the BlackBerry® Internet Service or the Internet gateway of the wireless service provider to manage connections. When you use the BlackBerry® Enterprise Server as a network gateway. which provides an HTTP and TCP/IP proxy service to allow the BlackBerry WebWorks application to use it as a secure gateway for managing HTTP and TCP/IP connections to the intranet. applications can communicate with application servers and web servers that are located on the organization's intranet. which makes the network request to the Internet through the corporate firewall. testing 18 . including traffic destined for the Internet. If your application is for BlackBerry device users who are on a specific wireless network.close(). } } showContents(result). you might be able to use the BlackBerry® Enterprise Server as a gateway. Because the BlackBerry Enterprise Server is located behind the organization's firewall and provides inherent data encryption. If your application connects to the Internet. The BlackBerry® Mobile Data System component of the BlackBerry Enterprise Server includes the BlackBerry MDS Services. and reliable connections. Call showContents() that you created in step 6. If your application connects to the Internet. } catch(IOException ioe) { } 20. The BlackBerry® Mobile Data System component of the BlackBerry Enterprise Server includes the BlackBerry MDS Services. If your application is for users on a variety of wireless networks.RIM Confidential and Proprietary Information . all traffic between your BlackBerry® WebWorks™ application and the BlackBerry Enterprise Server is encrypted using AES or triple DES encryption. all traffic between your application and the BlackBerry Enterprise Server is encrypted using AES or triple DES encryption. Some wireless service providers also provide a WAP gateway that allows HTTP connections to use the WAP protocol.Beta Customers Only. A BlackBerry® WebWorks™ application can use either of these gateways to connect to the Internet. A BlackBerry® Java® Application can use either of these gateways to connect to the Internet. Content and software are subject to change. using the wireless service provider's Internet gateway can often yield fast. Using a wireless service provider's Internet gateway Most wireless service providers provide an Internet gateway that offers direct TCP/IP connectivity to the Internet. Network requests travel behind the organization's firewall to the BlackBerry Enterprise Server. which provides an HTTP and TCP/IP proxy service to allow the BlackBerry® Java® Application to use it as a secure gateway for managing HTTP and TCP/IP connections to the intranet. { } connection. Using the BlackBerry Enterprise Server as a network gateway When you use the BlackBerry® Enterprise Server as a network gateway. Administrators can set an IT policy to make sure that the BlackBerry Enterprise Server is the gateway for all wireless network traffic.

Add the RichTextField to your screen. you should use the BlackBerry® Internet Service transport. You can use a similar process to send and receive data using other network protocols. Before you begin: Open a network connection and pass a Connection object to the constructor of the class that is developed in this task. and start a thread to access the network connection.MainScreen.. The data that is returned from the web site is displayed on the screen.io. Create an instance variable for a RichTextField object to display the results. For more information about opening network connections. t.RIM Confidential and Proprietary Information . your application against the different Internet gateways can be challenging. Create a constructor that accepts a Connection object as an argument.OutputStream.InputStream. Create a method to populate your RichTextField with the data that is returned from the web site.IOException.UiApplication. CAUTION: Network input and output operations are not thread-safe.RichTextField. In this case. Make sure that you create a separate thread when you use a Connection object.api. java. see Open a network connection using the Network API or Open a network connection using the GCF.ui.io. public class HTTPOutputScreen extends MainScreen { 3. javax.ui. Please wait. _rtfOutput. To make this task as general as possible. Content and software are subject to change. 4. net.Beta Customers Only. Import the required classes and interfaces.*. you would use an HttpConnection interface. the following code sends an HTTP GET command manually to a server. import import import import import import import net. after ContentReaderThread completes.setText("Retrieving data.device. 2. RichTextField _rtfOutput = new RichTextField(). ContentReaderThread t = new ContentReaderThread(conn).io.. public HTTPOutputScreen(Connection conn) { 5.component. You invoke this method in step 20.start().microedition. 19 .api.device.io. Normally.device.api. Send and receive data using a network connection The following task shows you how to send and receive data using an HTTP connection to a web site. and use the wireless service provider’s Internet gateway as a backup connection type if the BlackBerry Internet Service transport is not available. 6. which constructs the HTTP command string according to the options that you configure. java. java.rim.rim.container.ui.").rim. Create a class that extends the MainScreen class. net. 1. add(_rtfOutput).

String result = "". ContentReaderThread(Connection conn) { _connection = conn. Initialize an OutputStream object and an InputStream object to exchange data with the web site. Create an InputConnection object to receive data from your connection. Initialize a String object to store the response from the web site. Accept a ConnectionDescriptor object as an argument.write(getCommand.Beta Customers Only.0\r\n\r\n".setText(result). Retrieve an OutputStream from your OutputConnection.0\r\n\r\n". try { OutputConnection outputConn = (OutputConnection) connection. Convert the GET command into a byte array. os = outputConn. 9. 10. public void showContents(final String result) { UiApplication. In an inner class. OutputStream os = null. private final class ContentReaderThread extends Thread { private Connection _connection. os.invokeLater(new Runnable() { public void run() { _rtfOutput. } } }). Create an OutputConnection object to send data over your connection. 13. os.flush().flush().write(getCommand. 12. Content and software are subject to change.openOutputStream().getUiApplication(). create a thread to communicate with the web server. Send an HTTP GET command to the web server over your OutputStream. 20 .RIM Confidential and Proprietary Information . } public void run() { 8. os. InputConnection inputConn = (InputConnection) connection. String getCommand = "GET " + "/" + " HTTP/1. InputStream is = null. os.getBytes()). 7.getBytes()). String getCommand = "GET " + "/" + " HTTP/1. 11.

Content and software are subject to change.io. 16. } 17.toString(). Close your OutputStream. { connection.close().close().streamToBytes(is).device. 14. is = inputConn.openInputStream().close().rim. Call showContents() that you created in step 6. Close your Connection. if(os != null) { try { os. } catch(IOException e) { } } 19. Close your InputStream. if(is != null) { try { is. catch(Exception e) { result = "ERROR fetching content: " + e.api. Retrieve the stream data and store it in a byte array. } catch(IOException e) { // process the error condition } } 18.IOUtilities. Catch any errors that might be generated by your procedure. byte[] data = net. 15.RIM Confidential and Proprietary Information . } catch(IOException ioe) { } } 20. result = new String(data). 21 .Beta Customers Only. Retrieve an InputStream from your InputConnection.

rim.api. Content and software are subject to change.RichTextField. TransportInfo.rim.microedition.rim. } public NetworkSample() { new HTTPConnectionSetup(). the InputConnection and OutputConnection interfaces are used in place of the HttpConnection interface.length .UiApplication.*.ui.*.io. // Remove any transports that are not (currently) available for(int i = 0.io.*. i < _intTransports. net. public HTTPConnectionSetup() { // Create preference ordered list of transports int[] _intTransports = { TransportInfo.MainScreen.enterEventDispatcher(). TransportInfo.api. import import import import import import import import net. public class NetworkSample extends UiApplication { public static void main(String[] args) { NetworkSample app = new NetworkSample().rim.rim.io.api. } } showContents(result).Beta Customers Only.options.*. java. Code sample: Retrieving a web page using the Network API To make this code sample as generic as possible.device.util. } } class HTTPConnectionSetup { ConnectionFactory _factory = new ConnectionFactory().component.api.ui.RIM Confidential and Proprietary Information . net.device.ui. javax. i++) { int transport = _intTransports[i].io.device.isTransportTypeAvailable(transport) || !TransportInfo.transport.device.hasSufficientCoverage(transport)) { 22 .rim.TRANSPORT_TCP_WIFI.transport.device. net.api.TRANSPORT_TCP_CELLULAR }. net.Arrays.TRANSPORT_WAP2. app.device. if(!TransportInfo.container. net.api.

if(!TcpCellularOptions.getConnection(). // Set options for TCP Cellular transport TcpCellularOptions tcpOptions = new TcpCellularOptions().setTunnelAuthUsername("user"). } } Arrays. tcpOptions. tcpOptions.length > 0) { _factory.pushScreen(new HTTPOutputScreen(conn)).getUiApplication(). t.RIM Confidential and Proprietary Information .start(). tcpOptions). } private void displayContent(final Connection conn) { // When the connection thread completes.TRANSPORT_TCP_CELLULAR.setTunnelAuthPassword("password").setAttemptsLimit(5).Beta Customers Only. fetch and show the content from // the web server if(cd != null) { Connection c = cd.setApn("My APN").setPreferredTransportTypes(_intTransports). } } }).blackberry. // If connection was successful. Content and software are subject to change. i). } _factory. } 23 .setTransportTypeOptions(TransportInfo.isDefaultAPNSet()) { tcpOptions. } }).getConnection ("http://www. show the data from the web server UiApplication. displayContent(c).getUiApplication(). } // Set ConnectionFactory options if(_intTransports.removeAt(_intTransports. // Open a connection on a new thread Thread t = new Thread(new Runnable() { public void run() { ConnectionDescriptor cd = _factory. _factory.invokeLater(new Runnable() { public void run() { UiApplication.com").

t. } class HTTPOutputScreen extends MainScreen { RichTextField _rtfOutput = new RichTextField().getUiApplication(). OutputStream os = null. os. } // After the data has been retrieved."). on a // separate thread ContentReaderThread t = new ContentReaderThread(conn). add(_rtfOutput). // Retrieve the data from the web server.. ContentReaderThread(Connection conn) { _connection = conn.setText("Retrieving data. 24 .write(getCommand. Content and software are subject to change. private final class ContentReaderThread extends Thread { private Connection _connection. String getCommand = "GET " + "/" + " HTTP/1. try { // Send HTTP GET to the server OutputConnection outputConn = (OutputConnection) _connection.. display it public void showContents(final String result) { UiApplication.openOutputStream(). and put it on the screen _rtfOutput.RIM Confidential and Proprietary Information . InputStream is = null.setText(result).getBytes()). os = outputConn. public HTTPOutputScreen(Connection conn) { // Create a container for the data. os. Please wait.invokeLater(new Runnable() { public void run() { _rtfOutput. } public void run() { String result = "".start().flush(). using the connection.Beta Customers Only.0\r\n\r\n". } } }).

Beta Customers Only. 25 .device.streamToBytes(is). } catch(IOException ioe) { } } } } } // Show the response received from the web server. result = new String(data). is = inputConn. byte[] data = net.close().rim. Content and software are subject to change.api.io. // Get InputConnection and read the server's response InputConnection inputConn = (InputConnection) _connection. } catch(IOException e) { } } // Close InputStream if(is != null) { try { is.IOUtilities. } catch(IOException e) { } } // Close Connection try { _connection.openInputStream(). } catch(Exception e) { result = "ERROR fetching content: " + e.toString().close().close().close(). } finally { // Close OutputStream if(os != null) { try { os.RIM Confidential and Proprietary Information . or an error message showContents(result). // is.

Beta Customers Only.api.blackberry.ui. import import import import import net. Content and software are subject to change. java. public class NetworkSample extends UiApplication { public static void main(String[] args) { NetworkSample app = new NetworkSample(). net. To make this code sample as generic as possible. javax.ui.device.start().rim.getUiApplication().ui.RIM Confidential and Proprietary Information .rim.device.enterEventDispatcher().RichTextField.component.*. net.rim.*. try { c = Connector. } public NetworkSample() { new HTTPConnectionSetup().invokeLater(new Runnable() 26 .UiApplication.open("http://www.MainScreen.container. } private void displayContent(final Connection c) { // When the connection thread completes. app. show the data from the web server UiApplication. } catch (IOException e) { e.io.io.com.deviceside=false").api. } if(c != null) { displayContent(c).printStackTrace(). t.microedition.device.api. the InputConnection and OutputConnection interfaces are used in place of the HttpConnection interface. Code sample: Retrieving a web page using the GCF This code sample uses the BlackBerry® Mobile Data System transport. } } }). } } class HTTPConnectionSetup { public HTTPConnectionSetup() { Thread t = new Thread(new Runnable() { public void run() { Connection c = null.

RIM Confidential and Proprietary Information . display it public void showContents(final String result) { UiApplication. public HTTPOutputScreen(Connection conn) { // Create a container for the data..setText("Retrieving data. ContentReaderThread(Connection conn) { _connection = conn. } } }).getUiApplication().pushScreen(new HTTPOutputScreen(c)).start(). } // After the data has been retrieved. public void run() { UiApplication.Beta Customers Only.setText(result).invokeLater(new Runnable() { public void run() { _rtfOutput. private final class ContentReaderThread extends Thread { private Connection _connection. } public void run() { String result = "". // Retrieve the data from the web server.getUiApplication(). Please wait. add(_rtfOutput). and put it on the screen _rtfOutput. { } } }). try { // Send HTTP GET to the server 27 . t. Content and software are subject to change. using the connection."). } class HTTPOutputScreen extends MainScreen { RichTextField _rtfOutput = new RichTextField().. on a // separate thread ContentReaderThread t = new ContentReaderThread(conn). InputStream is = null. OutputStream os = null.

} catch(IOException ioe) { } } // Show the response received from the web server. // is. os. is = inputConn. result = new String(data). os.rim.close().api.device.toString(). } finally { // Close OutputStream if(os != null) { try { os.openInputStream(). String getCommand = "GET " + "/" + " HTTP/1.openOutputStream().close().streamToBytes(is). } catch(Exception e) { result = "ERROR fetching content: " + e. byte[] data = net.0\r\n\r\n". or an error message showContents(result).flush(). } catch(IOException e) { } } // Close InputStream if(is != null) { try { is.write(getCommand.close(). Content and software are subject to change.IOUtilities.close(). // Get InputConnection and read the server's response InputConnection inputConn = (InputConnection) _connection.RIM Confidential and Proprietary Information .getBytes()). OutputConnection outputConn = (OutputConnection) _connection. os = outputConn.io.Beta Customers Only. 28 . } catch(IOException e) { } } // Close Connection try { _connection.

Beta Customers Only. Content and software are subject to change.RIM Confidential and Proprietary Information . } } } 29 .

Alternatively. Alternatively. creating a thread-safe connection. BlockingSenderDestination can return a MessageFuture object. You can use this interface to send data to a web service when you don't expect a response. NonBlockingSenderDestination BlockingReceiverDestination NonBlockingReceiverDestination FireAndForgetDestination Data that you send to and receive from a web service is wrapped in a Message object. you can allow the Communication API to choose reasonable default values for your request. pass your implementation of MessageListener to receive push messages.send() without specifying an HTTP GET command. In the parameter list. The API is implemented in the net.rim.io. pass your implementation of the MessageListener interface to receive the response from the web service. You can use this interface to send a message to a web service. Content and software are subject to change. You can set the headers and content of the data that is sent to a web service in the Message object.api.Beta Customers Only. This allows thread execution to continue until you invoke one of the get() methods from the MessageFuture.messaging package. 30 . URI and URL end points are called destinations. You can use this interface to subscribe to a push service and block thread execution until you receive confirmation of your subscription request. You must use the DestinationFactory class to create an object that implements one of the Destination subinterfaces that suits your requirements. you should not invoke it from the main event thread. In the parameter list. but this object blocks thread execution while it waits for a response from the web service. You can use objects that implement the SenderDestination interface to send data to a web service and access the response.RIM Confidential and Proprietary Information . For example. you can use objects that implement the ReceiverDestination interface to subscribe to a push service and provide access to new messages from that service. and negotiating an exchange of data with the URI or URL end point that you specify. When you invoke sendReceive() in BlockingSenderDestination to send a message and wait for a response. You can use this interface to subscribe to a push service. you can request a web page by invoking SenderDestination. Similarly.device. The objects that you create using this API automate the process of finding an available network transport. Within the Communication API. Interface BlockingSenderDestination Description You can use this interface to send a message to a web service. Communication API 3 The Communication API simplifies the process of interacting with web services and other applications.

Before you create a SenderDestination. any messages in the queue will be deleted. the body of the Message contains the raw response data. The SenderDestination object is responsible for queuing messages for delivery. You can choose to specify a message processor from the net. including the HTTP request method and any additional data that you require.release() or DestinationFactory.api.RIM Confidential and Proprietary Information .io. After you send your message. MessageProcessor interface with your parser class.device. you should invoke DestinationFactory. The release() method removes the association between a Destination and the inbound and outbound message queues. default values are provided by the Communication API.rim. When you finish exchanging data with an end point. you need to create a Thread object when you invoke one of the sendReceive() methods.create. You can access an existing destination by providing the name of the Context object that you supplied when you invoked any of the DestinationFactory. For NonBlockingSenderDestination objects. This approach enables you to make better use of both network bandwidth and memory.rim.api. If you implement the The net. The DestinationFactory class creates and maintains a list of Destination objects that you can use to communicate with an end point. you should check whether one exists by invoking getSenderDestination(). destroy() also destroys the message queue. Content and software are subject to change.parser packages contain message processors for a variety of standard data formats that are used on the Internet. you must create a MessageListener object to receive the response. For BlockingSenderDestination objects.parser package. A message contains the details of your command. You can then retrieve the parsed response using Message.io. Atom) • SOAP • XML To improve efficiency. In addition to removing the association between a Destination and the a message queue. An application can request additional data as required rather than downloading a large amount of data at once and storing it in memory on the device..Beta Customers Only. and retrieving incoming messages for delivery.destory(). In either case.() methods. If you do not specify all parameters for your message. You can also instruct the API to automatically parse the response data from a web service. 31 . By default. the API continues to attempt the delivery of messages in the queue.. you may need to listen for a response. The packages include parsers for: • JSON • RSS (RDF. After you invoke destory(). or create your own using the MessageProcessor interface.device. you need a SenderDestination object to communicate with an end point. you need to process a Message object that contains the response. After you invoke release(). you can supply your parser object to the method in DestinationFactory that creates your Destination object.getObjectPayload(). Communicating with HTTP servers To send a command to an HTTP server. You can use release() when your application is not in a state to send and receive messages. the Communication API provides large responses from web services in an InputStream object.

Create a URI object to pass to the DestinationFactory class.URI. 5.device.sendReceive(). 7.rim. Import the required classes and interfaces. URI uri = new URI("http://www. uri).RIM Confidential and Proprietary Information .io. } 8. The MessageProcessorChain class shares memory between the MessageProcessor objects to improve efficiency. 4.rim.io. Thread t = new Thread( new Runnable() { public void run() { 3. For example.getSenderDestination ("MyContext". uri). BlockingSenderDestination bsd = null. create one. Message response = null. you can separate the decoding and decompression logic into separate message processors. Request data using a BlockingSenderDestination object 1. try { bsd = (BlockingSenderDestination) DestinationFactory. if(bsd == null) { bsd = DestinationFactory.messaging. Create a thread from which to call BlockingSenderDestination.blackberry. import net. and then use MessageProcessorChain to group them together.api.api. if one exists.*.sendReceive().com"). process the response. 6. Send a message and wait for the response. 2.device. you can connect multiple message processors together. if you receive video data that uses custom encoding and compression. If necessary. 32 . If no BlockingSenderDestination exists. Retrieve the BlockingSenderDestination object for your context.Beta Customers Only.createBlockingSenderDestination (new Context("MyContext"). If the web service sent a response. import net. response = bsd. Create a Message object to hold the response from the URL. Content and software are subject to change. Create a BlockingSenderDestination object. 9.

*. Release the BlockingSenderDestination.*.*.api. For a complete code sample. net.api.messaging.device.com/t5/Java-Development/Manage-UI-interactions/ta-p/502378. } } } }). java.device. see "Code sample: Requesting data using a BlockingSenderDestination object".device.io. 12. app. read the knowledge base article at http:// supportforums.enterEventDispatcher(). public class NetworkSample extends UiApplication { public static void main(String[] args) { NetworkSample app = new NetworkSample().api.ui. Code sample: Requesting data using a BlockingSenderDestination object import import import import import import net.*.ui. net.io.device. } public NetworkSample() { pushScreen(new BlockingSenderSample()). not on the thread that you created in this task.release(). After you finish: If your processResponse() updates the UI.device. you must do so on the main event thread. net. finally { if(bsd != null) { bsd. } if(response != null) { processResponse(response). net.api. Content and software are subject to change.RIM Confidential and Proprietary Information .ui. 33 . Start the thread. catch (Exception e) { // Process the error } 11. Catch any errors that occur if the message could not be sent for some reason.*. t. For more information.component.rim.io.container.URI.rim.rim. } 10.start().api.rim.blackberry.Beta Customers Only.rim.

} // Send message and wait for response response = bsd. public void fieldChanged(Field button. if(response != null) { BSDResponse(response). int unused) { if(button == _btnBlock) { Thread t = new Thread(new Runnable() { public void run() { Message response = null.sendReceive(). if(bsd == null) { bsd = DestinationFactory. private static UiApplication _app = UiApplication. private String _result.FIELD_HCENTER). } } class BlockingSenderSample extends MainScreen implements FieldChangeListener { ButtonField _btnBlock = new ButtonField(Field. _btnBlock.getUiApplication().Beta Customers Only. try { bsd = (BlockingSenderDestination) DestinationFactory.setLabel("Fetch page").RIM Confidential and Proprietary Information . String uriStr = "http://www. } add(_btnBlock). } } catch(Exception e) 34 .getSenderDestination ("CommAPISample". URI. public BlockingSenderSample() { _btnBlock. URI. BlockingSenderDestination bsd = null.create(uriStr)).createBlockingSenderDestination (new Context("CommAPISample").setChangeListener(this).com".blackberry. Content and software are subject to change.create(uriStr) ).

} } private void BSDResponse(Message msg) { if (msg instanceof ByteMessage) { ByteMessage reply = (ByteMessage) msg. } catch (IOException e) { // process the error } if(data != null) { _result = new String(data).streamToBytes(is).api.IOUtilities.RIM Confidential and Proprietary Information .invokeLater(new Runnable() { public void run() { _app. _result = (String) reply.getStreamPayload(). t. } } }). { } // process the error } finally { if(bsd != null) { bsd.device.io. byte[] data = null. InputStream is = reply.start().pushScreen(new HTTPOutputScreen(_result)).release(). Content and software are subject to change.getStringPayload(). } }). } else if(msg instanceof StreamMessage) { StreamMessage reply = (StreamMessage) msg. } } _app. } } class HTTPOutputScreen extends MainScreen { 35 .rim.Beta Customers Only. try { data = net.

getUiApplication().rim. MyMessageListener msgListener = new MyMessageListener(). Create a Message object to hold the response from the URL. Request data using a NonBlockingSenderDestination object Before you begin: To request data using the NonBlockingSenderDestination class.invokeLater(new Runnable() { public void run() { _rtfOutput. Import the required classes and interfaces. Retrieve the NonBlockingSenderDestination object for your context. For more information.messaging. 2. 36 . 4. } } } }). RichTextField _rtfOutput = new RichTextField().io. Create a NonBlockingSenderDestination object.com").device. see "Implement the MessageListener interface". Create a reference to your MessageListener.api.api. display it public void showContents(final String result) { UiApplication."). import net. showContents(message).RIM Confidential and Proprietary Information .. 3. Please wait. if one exists. URI uri = new URI("http://www. create an object that implements the MessageListener interface.Beta Customers Only. Content and software are subject to change. 5. import net.blackberry.setText("Retrieving data. add(_rtfOutput). 1.rim.device.URI.*.io. public HTTPOutputScreen(String message) { _rtfOutput.. } // After the data has been retrieved. 6. Message response = null.setText(result). NonBlockingSenderDestination nbsd = null. Create a URI object to pass to the DestinationFactory class.

see "Code sample: Request data using a NonBlockingSenderDestination object" Implement the MessageListener interface You can use the MessageListener interface to receive messages that are sent by a NonBlockingSenderDestination object. 2.io. Initialize a String variable to hold the response data.rim. Catch any errors that occur if the message could not be sent for some reason.api.*.device. msgListener). Send a message to the web service. Import the required classes and interfaces. 37 . retrieve the response as a String and assign it to payload.send().io. uri). 5. If the response is a ByteMessage object.InputStream. 1.io. import net. try { nbsd = (BlockingSenderDestination) DestinationFactory. import java.messaging. 9. create one. nbsd. String payload = null.Beta Customers Only. uri.IOException. public void onMessage(Destination dest. 7. For a complete code sample. if(nbsd == null) { nbsd = DestinationFactory.RIM Confidential and Proprietary Information . import java. 3. Define a class that implements the MessageListener interface. } 8. public class MyMessageListener implements MessageListener { Implement onMessage(). or push messages that are sent from a push initiator. If no NonBlockingSenderDestination exists.createNonBlockingSenderDestination (new Context("MyContext"). catch (Exception e) { // Process the error } After you finish: Release the NonBlockingSenderDestination when you are done processing the response. Content and software are subject to change.getSenderDestination ("MyContext". Message incomingMessage) { 4.

} } 7.container. payload = (String) reply. if (incomingMessage instanceof ByteMessage) { ByteMessage reply = (ByteMessage) incomingMessage.device.* net. display it.io.ButtonField. byte[] data = null.ui. net.api.io. else if(incomingMessage instanceof StreamMessage) { StreamMessage reply = (StreamMessage) incomingMessage.device.rim.getUiApplication().ui.messaging. If the response is a StreamMessage. For a complete code sample.getStreamPayload().api.api.*. } } After you finish: Implement onMessageCancelled() and onMessageFailed() to process other notifications. a. convert the byte array to a String and assign it to payload.rim. if(data != null) { payload = new String(data).api.RIM Confidential and Proprietary Information .pushScreen (new HTTPOutputScreen(payload)). . If the response is small.rim. If the conversion was successful.device. convert the contents of the stream into a byte array.device.getEventLock()) { UiApplication. see "Code sample: Request data using a NonBlockingSenderDestination object" Code sample: Requesting data using a NonBlockingSenderDestination object import import import import import 38 net. try { data = net.rim.getStringPayload(). } 6. net.device.MainScreen.ui.URI.rim. InputStream is = reply.IOUtilities.component.Beta Customers Only.streamToBytes(is).rim.api. retrieve the response as an InputStream object. Content and software are subject to change. } catch (IOException e) { // process the error } b.io.device.api. net. If payload contains data. if(payload!=null) { synchronized(Application.

try { URI uri = URI.*. destination = (NonBlockingSenderDestination) DestinationFactory. } // Send message to retrieve the response destination. if (destination == null) { destination = DestinationFactory. int unused) { if(button == _btnNonBlock) { NonBlockingSenderDestination destination = null.setChangeListener(this). public class NetworkSample extends UiApplication { public static void main(String[] args) { NetworkSample app = new NetworkSample().FIELD_HCENTER). public NonBlockingSenderSample() { _btnNonBlock.RIM Confidential and Proprietary Information . } add(_btnNonBlock). public void fieldChanged(Field button.blackberry.Beta Customers Only. uri. app. } } class NonBlockingSenderSample extends MainScreen { implements FieldChangeListener ButtonField _btnNonBlock = new ButtonField(Field. import net. } public NetworkSample() { pushScreen(new NonBlockingSenderSample()).system. uri). private static UiApplication _app = UiApplication.createNonBlockingSenderDestination (new Context("CommAPISample").com").create("http://www. _btnNonBlock.io.getUiApplication(). 39 .rim.getSenderDestination ("CommAPISample".api.Application. NBSDMsgListener responseListener = new NBSDMsgListener().device.send(). Content and software are subject to change. responseListener). import java.setLabel("Fetch page").enterEventDispatcher().

if (msg instanceof ByteMessage) { ByteMessage reply = (ByteMessage) msg.streamToBytes(is). } catch(Exception e) { // process the error } } } class NBSDMsgListener implements MessageListener { public void onMessage(Destination dest. Message msg) { String payload = null.rim. } catch (IOException e) { } if(data != null) { payload = new String(data).api.Beta Customers Only.IOUtilities.getEventLock()) { UiApplication. payload = (String) reply.pushScreen (new HTTPOutputScreen(payload)). } } if(payload!=null) { synchronized(Application. int arg1) { // process message cancelled notification } 40 .device.getUiApplication(). byte[] data = null. Content and software are subject to change. } } } } public void onMessageCancelled(Destination arg0.getStreamPayload(). try { data = net.getStringPayload(). } else if(msg instanceof StreamMessage) { StreamMessage reply = (StreamMessage) msg.io. InputStream is = reply.RIM Confidential and Proprietary Information .

getUiApplication().*. URI uri = new URI("http://www.api.setText(result). public void onMessageFailed(Destination arg0. 5. import net.getSenderDestination ("MyContext". public HTTPOutputScreen(String message) { _rtfOutput. Send data using a FireAndForgetDestination object 1.com"). uri). Please wait. FireAndForgetDestination ffd = null. 3. } } } }).. 41 . Create a FireAndForgetDestination object. showContents(message).example. 4.io.api. Import the required classes and interfaces.messaging.URI. add(_rtfOutput).rim.invokeLater(new Runnable() { public void run() { _rtfOutput. Retrieve the FireAndForgetDestination object for your context. import net."). } // After the data has been retrieved.setText("Retrieving data. Create a URI object to pass to the DestinationFactory class. display it public void showContents(final String result) { UiApplication.RIM Confidential and Proprietary Information .io. create one. Content and software are subject to change.device.rim.Beta Customers Only. If no FireAndForgetDestination exists. 2. if one exists. try { ffd = (FireAndForgetDestination) DestinationFactory. MessageFailureException arg1) { // process message failed notification } } class HTTPOutputScreen extends MainScreen { RichTextField _rtfOutput = new RichTextField()..device.

sendNoResponse(myMsg).createFireAndForgetDestination (new Context("MyContext").* import net.parser. ByteMessage myMsg = ffd. 42 . ffd. // Retrieve the response Message response = bsd.Beta Customers Only. } 6.io.api..createByteMessage(). new JSONMessageProcessor()). 9.setMethod(HttpMessage. you should: 1.device. To retrieve the data structure in a Java object.messaging.rim. Code sample The following code sample demonstrates the three actions that are required to retrieve a Java object that contains a JSON data structure.create. myURI.. Extract the data from the Message object that is returned in the response.rim. ((HttpMessage) myMsg). if(ffd == null) { ffd = DestinationFactory.getObjectPayload().sendReceive().setStringPayload("I love my BlackBerry device!"). uri). catch (Exception e) { // Process the error } Parsing a common Internet data format You can configure a Destination object to return a Java® object that contains data parsed from a standard format.POST).device. // Extract the Java object that contains the JSON data structure Object payload = response. 8.RIM Confidential and Proprietary Information . Content and software are subject to change.io. import net. Retrieve the response from your Destination. Specify a MessageProcessor object when you invoke DestinationFactory.api. Cast your message as an HTTPMessage to set the HTTP method that you want to use. Send the message to the web service. such as JSON. Create a ByteMessage object and populate it with information to send to a web service. Catch any errors that occur if the message could not be sent for some reason. 2.().json. 3. 7.* // Specify a MessageProcessor when you create your Destination BlockingSenderDestination bsd = DestinationFactory(myContext. myMsg.

rim. Import the required classes and interfaces.device.container. Create an initializeTree() method to clear any existing data from the TreeField.ui. import net.api. Pass that object to the constructor of the class developed in this task. public JSONOutputScreen(Object JSONData) { _treeField = new TreeField(this. } else if(obj instanceof JSONObject) { parentNode = populateTreeObject (_treeField.*. 2. void initializeTree(Object obj) { int parentNode = 0. 43 . Content and software are subject to change. (JSONObject) obj.device. import net. 3. public class JSONOutputScreen extends MainScreen implements TreeFieldCallback { private TreeField _treeField.ui. import net. parentNode). initializeTree(JSONData).FOCUSABLE). _treeField.Beta Customers Only. 1. and initiates the parsing code. Determine whether the current node in the JSON object is a JSONArray or a JSONObject.component. Field. add(_treeField).device.api.rim.rim. 5. } 4.*.MainScreen. (JSONArray) obj. Before you begin: Retrieve a Java® object that contains a JSON data structure.RIM Confidential and Proprietary Information . Create a constuctor that accepts an Object as a parameter. Parse a JSON data structure This task uses a TreeField to display the contents of a JSON data structure.deleteAll(). Invoke the appropriate populateTreeArray() method. Define a MainScreen class that implements TreeFieldCallback interface.ui.api. creates the UI. try { if(obj instanceof JSONArray) { parentNode = populateTreeArray (_treeField.

toString(). if(temp instanceof JSONArray) { populateTreeArray(tree. 6.get(i). go to the next node. } 12.length(). else { newParent = tree. Implement populateTreeArray(TreeField. 8. i < o. JSONArray o.addSiblingNode(newParent. Retrieve the current JSONArray. newParent). catch(JSONException e) { // Process error } } _treeField. ++i) { 10.equalsIgnoreCase("null")) { continue. for(int i = 0. This node must contain data.addChildNode(p. int p) throws JSONException { Object temp. 9.toString()). If this node contains a nested JSON structure. } 13. newParent). temp = o. If the node is empty. parse the object recursively. Add a node to the TreeField. } else if(temp instanceof JSONObject) { populateTreeObject(tree. Again. } } parentNode). int newParent = tree. if(temp == null || temp. } 44 .Beta Customers Only. and specify where the TreeField should add new data. int). (JSONArray) temp. 7.RIM Confidential and Proprietary Information . (JSONObject) temp.setCurrentNode(parentNode). Content and software are subject to change. 11. Catch any errors. int populateTreeArray(TreeField tree. choose the most appropriate version of populateTreeArray(). JSONArray. temp. Add the data to the tree. Iterate through the elements in this node of the JSONArray. "Array " + p).

RIM Confidential and Proprietary Information - Beta Customers Only. Content and software are subject to change.

} } return newParent;

14. Implement populateTreeArray(TreeField, JSONObject, int). The code is similar to steps 7 through 13, with the following alterations: a. Change the method signature from step 7.
int populateTreeArray(TreeField tree, JSONObject o, int p) throws JSONException {

b. c.

Create a JSONArray containing the names of the elements.
JSONArray jsonArray = o.names();

Iterate over the newly created JSONArray instead of the JSONObject passed as a parameter. For more information, see step 9.
for(int i = 0; i < jsonArray.length(); ++i) {

d.

From the JSONObject, retrieve the value for each name in jsonArray. For more information, see step 10.
temp = o.get(jsonArray.getString(i));

e.

Ensure that you add both the name and value to the tree. For more information, see step 13.
tree.addSiblingNode(newParent, a.getString(i) + ": " + temp.toString());

15. Implement DrawTreeItem().
public void drawTreeItem(TreeField treeField, Graphics graphics, int node, int y, int width, int indent) { if(treeField == _treeField) { Object cookie = _treeField.getCookie(node); if(cookie instanceof String) { String text = (String) cookie; graphics.drawText(text, indent, y, Graphics.ELLIPSIS, width); } } } }

45

RIM Confidential and Proprietary Information - Beta Customers Only. Content and software are subject to change.

Code sample: Parsing a JSON data structure
The following code sample demonstrates one way to parse a JSON data structure. You can use a similar process to parse JSON or other data formats that are provided by the Message Processing API.
import import import import import import import net.rim.device.api.io.URI; net.rim.device.api.io.messaging.*; net.rim.device.api.ui.* net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; java.io.*; org.json.me.*;

public class NetworkSample extends UiApplication { public static void main(String[] args) { NetworkSample app = new NetworkSample(); app.enterEventDispatcher(); } public NetworkSample() { pushScreen(new ParseJSONSample()); } } class ParseJSONSample extends MainScreen implements FieldChangeListener { ButtonField _btnJSON = new ButtonField(Field.FIELD_HCENTER); private static UiApplication _app = UiApplication.getUiApplication(); public ParseJSONSample() { _btnJSON.setChangeListener(this); _btnJSON.setLabel("Fetch page"); } add(_btnJSON);

public void fieldChanged(Field button, int unused) { if(button == _btnJSON) { Thread t = new Thread(new Runnable() { public void run() { Message response = null; String uriStr = "http://docs.blackberry.com/sampledata.json"; BlockingSenderDestination bsd = null; try 46

RIM Confidential and Proprietary Information - Beta Customers Only. Content and software are subject to change.

{

bsd = (BlockingSenderDestination) DestinationFactory.getSenderDestination ("CommAPISample", URI.create(uriStr)); if(bsd == null) { bsd = DestinationFactory.createBlockingSenderDestination (new Context("CommAPISample"), URI.create(uriStr), new JSONMessageProcessor() ); } // Send message and wait for response response = bsd.sendReceive(); _json = response.getObjectPayload(); if(_json != null) { _app.invokeLater(new Runnable() { public void run() { _app.pushScreen(new JSONOutputScreen(_json)); } } });

}

} catch(Exception e) { System.out.println(e.toString()); } finally { if(bsd != null) { bsd.release(); } }

}); t.start(); } } class JSONOutputScreen extends MainScreen implements TreeFieldCallback { private TreeField _treeField;

47

RIM Confidential and Proprietary Information - Beta Customers Only. Content and software are subject to change.

public JSONOutputScreen(Object JSONData) { _treeField = new TreeField(this, Field.FOCUSABLE); add(_treeField); setTree(JSONData); } void setTree(Object obj) { int parentNode = 0; _treeField.deleteAll(); try {

} catch(JSONException e) { System.out.println(e.toString()); } }

if(obj instanceof JSONArray) { parentNode = populateTreeArray (_treeField, (JSONArray) obj, parentNode); } else if(obj instanceof JSONObject) { parentNode = populateTreeObject (_treeField, (JSONObject) obj, parentNode); }

_treeField.setCurrentNode(parentNode);

// Populate the trees with JSON arrays int populateTreeArray(TreeField tree, JSONArray o, int p) throws JSONException { Object temp; int newParent; newParent = tree.addChildNode(p, "Array " + p); for(int i = 0; i < o.length(); ++i) { temp = o.get(i); if(temp == null || temp.toString().equalsIgnoreCase("null")) { continue; } if(temp instanceof JSONArray) { // Array of arrays populateTreeArray(tree, (JSONArray) temp, newParent);

48

newParent). } else { tree. } else if(temp instanceof JSONObject) { populateTreeObject(tree. } else { // other values newParent = tree.addSiblingNode(newParent.get(a.addChildNode(p. } } } else if(temp instanceof JSONObject) { // Array of objects populateTreeObject(tree.length(). // Populate the tree with JSON objects int populateTreeObject(TreeField tree. (JSONArray) temp.toString(). int y. for(int i = 0. public void drawTreeItem(TreeField treeField. } } } return newParent. JSONObject o. int newParent = tree. if(temp == null || temp.Beta Customers Only. int node. newParent).names(). int indent) { if(treeField == _treeField) 49 . int width. } if(temp instanceof JSONArray) { populateTreeArray(tree. temp.addSiblingNode (newParent. Content and software are subject to change. int p) throws JSONException { Object temp.toString()). i < a.toString()). (JSONObject) temp. } return newParent.getString(i)). ++i) { temp = o. Graphics graphics.getString(i) + ": " + temp.equalsIgnoreCase("null")) { continue. (JSONObject) temp. JSONArray a = o. "Object" + p). a. newParent).RIM Confidential and Proprietary Information .

when a web server requests it. return new UsernamePasswordCredentials("username". } }). indent.ELLIPSIS. new CredentialsCollector() { public UsernamePasswordCredentials getBasicAuthenticationCredentials (String aeID.Beta Customers Only. "password"). then return them from // this method. Hashtable properties) { // Provide or retrieve authentication credentials here. } public boolean onSavePrompt() { // Suppress the save dialog return true. 50 . } } Sending login information to an HTTP server A Destination object can supply login information. such as a user name and password. Graphics.drawText(text. you could display a dialog box to ask your user // to enter a username and password. Login information is stored in the Context object that you supply when you create a Destination using the DestinationFactory class. Content and software are subject to change. width). if(cookie instanceof String) { String text = (String) cookie. y. // For example.RIM Confidential and Proprietary Information . { } } Object cookie = _treeField. Code sample context = new Context("DemoContext". graphics.getCookie(node).

and an InboundDestinationConfiguration object. Subscribing to a push initiator 4 You can use the Communication API to send a subscription request to a content provider's URI. You can create an InboundDestinationConfiguration using the InboundDestinationConfigurationFactor y class. The Communication API can create a properly formed subscription message for you.RIM Confidential and Proprietary Information . You can send a subscription message using any type of network connection. MessageListener This component processes incoming push messages.createB yteSubscriptionMessage() to retrieve a ByteMessage object that is configured for your SenderDestination. NonBlockingReceiverDestination. This component is optional. such as an indicator that specifies whether your application should be started when a new push message arrives. In addtition to the SenderDestination object that sends the subscription request. This component specifies a variety of push service parameters.Beta Customers Only. This component associates a particular URI with a MessageListener where you want to receive incoming push messages. you need to create a ReceiverDestination object that defines the MessageListener object to which the BlackBerry® device should deliver incoming push messages from a given URI. you can use the Network API to create an HTTPConnection and send the subscription parameters manually. Component SenderDestination Subscription message Description This component sends the subscription message to the content provider. Content and software are subject to change. You can invoke BpsSubscriptionMessageBuilder. and the MessageListener where you want to receive NonBlockingReceiverDestination InboundDestinationConfiguration incoming push messages. 51 . The following table describes the components that are involved in a subscription request. For example.

9.create("http://:101"). // application ID. pushListener).createByteSubscriptionMessage (bpsDestination. Subscribe to a push initiator This task focuses on creating a subscription message and the NonBlockingReceiverDestination object for a Push Service subscription. InboundDestinationConfiguration config = InboundDestinationConfigurationFactory.createBPSConfiguration (true.RIM Confidential and Proprietary Information .Beta Customers Only. // allow other applications to receive these push messages false. nbrd. pushURI. 5. // do not store these messages (persistence not supported) "12-Ab234cD5eF67h890". Create an InboundDestinationConfiguration object to set parameters for the push subscription. Before you begin: Obtain an application ID and the local port number that your application should use to listen for incoming messages. Create a NonBlockingReceiverDestination. 4. ByteMessage subMsg = BpsSubscriptionMessageBuilder. 52 .api. import net. NonBlockingSenderDestination bpsDestination = DestinationFactory. "user". uri. These details are provided to the content provider that creates a server-side push application. "pwd").device. BPSuri). 2. responseListener).*.createNonBlockingReceiverDestination (config. // BlackBerry Push Service URI 6. Content and software are subject to change. NonBlockingReceiverDestination nbrd = null. Create a SenderDestination to send a subscription message.rim. Configure a subscription message. Initialize a NonBlockingReceiverDestination variable to manage the subscription. 3. or by creating a network connection manually.io.createNonBlockingSenderDestination (myContext. Create a URI object with the port information that the content provider assigns to you. Import the required classes and interfaces. nbrd = DestinationFactory. 1. 8. URI pushURI = URI. Create a MessageListener object to process incoming push messages. try { MyMessageListener pushListener = new MyMessageListener().messaging. Send the subscription message. 7. // start this application when a push message arrives false. You must send your subscription message using a SenderDestination object.

bpsDestination. 53 .send(subMsg).RIM Confidential and Proprietary Information .Beta Customers Only. Content and software are subject to change.

For more information. import net.api. Check if the radio that you want to use is turned off. Query a radio's availability and change its status You can use the RadioInfo and Radio classes to determine whether a particular radio technology is supported on a BlackBerry® device. 2. 5.device.RIM Confidential and Proprietary Information .system.api.11a. You can use the net. Import the required classes and interfaces.Radio class.api. 802. Wireless access family 3GPP® CDMA WLAN Description This family includes GPRS.Beta Customers Only. you can manage the radios on the device. Using the rim. a bitwise AND operation applied to 54 . EDGE. import net.11b. 3. Working with radios 5 There may be cases where you need to turn on a radio on a BlackBerry® device to use a particular network transport. 802. int intSupportedWAFs = RadioInfo. int intSupportedWAFs = RadioInfo.getActiveWAFs(). see the API reference for the BlackBerry® Java® SDK.getSupportedWAFs(). intActiveWAFs and the constant for the radio returns 0. This family includes IEEE® 802.rim. Content and software are subject to change. This family includes CDMA2000® and EVDO.device. For example.system. 1.rim. Or. Perform a bitwise AND operation that combines the intSupportedWAFs bit field and the constant for the wireless access family that you want to use. and GAN.device.device. int intActiveWAFs = RadioInfo. if ((intSupportedWAFs & RadioInfo. you may want to compare your application's performance when you use different wireless technologies.Radio. 802. If it is turned off.device. The wireless technologies that are available on BlackBerry devices are grouped into three wireless access families.rim.system.system.api. UMTS® GERAN. You should also implement the net.11g.WAF_WLAN) !=0 ) { 4. If the family is available.RadioInfo. Retrieve a bit field of supported wireless access families.rim. Retrieve a bit field of available radios. Check if the wireless access family that you want to use is available on the device. the result will be nonzero. you may want your BlackBerry device application to connect over Wi-Fi® to make efficient use of bandwidth. UTRAN.RadioStatusListener interface to receive notifications about changes in radio status. and to turn on or turn off the radio.system.RadioInfo class to gather information about the wireless technologies that are available on a device.11™.api.getSupportedWAFs().

setChangeListener(this).RIM Confidential and Proprietary Information .add(_btnCDMA).container. if ((wafs & RadioInfo.device.getSupportedWAFs(). int wafs = RadioInfo. public RadioControlScreen() { VerticalFieldManager vfm = new VerticalFieldManager(Field.ui. If the radio is turned off.api. _btnWiFi.device.component.device.ui.WAF_CDMA) != 0 ) { _btnCDMA = new ButtonField("CDMA Radio").*. } } class RadioControlScreen extends MainScreen implements FieldChangeListener { boolean[] _intRadioOn = new boolean[3].api.activateWAFs(RadioInfo.rim.api. net. } if ((wafs & RadioInfo. _btnCDMA.FIELD_HCENTER).Beta Customers Only. ButtonField _btn3G. _btnCDMA.enterEventDispatcher(). _btniDEN. public class NetworkSample extends UiApplication { public static void main(String[] args) { NetworkSample app = new NetworkSample(). _btn3G. } public NetworkSample() { pushScreen(new RadioControlScreen()).rim. net.*.setChangeListener(this).system.rim. app. then turn it on. net.WAF_WLAN). } if ((wafs & RadioInfo.add(_btn3G).WAF_WLAN) = 0) { 6. vfm.device.api.rim. vfm. if ((intActiveWAFs & RadioInfo.WAF_3GPP) != 0 ) { _btn3G = new ButtonField("3G Radio"). } Radio.*. Content and software are subject to change.ui. } Code sample: Controlling radios import import import import net.*.WAF_WLAN) != 0 ) 55 .

activateWAFs(RadioInfo. { } _btnWiFi = new ButtonField("WiFi Radio").deactivateWAFs(RadioInfo. _btnCDMA. 56 .setLabel("CDMA Radio is off").WAF_3GPP) != 0 ) { _intRadioOn[0] = true. wafs = RadioInfo. int context) { if (field instanceof ButtonField) { if(field == _btn3G) { if (_intRadioOn[0]) { Radio.deactivateWAFs(RadioInfo. setTitleBar(tb). _intRadioOn[0] = false.WAF_CDMA). Content and software are subject to change.addTitle("Radio Control Demo").RIM Confidential and Proprietary Information .setLabel("3G Radio is on"). _intRadioOn[1] = false. } if ((wafs & RadioInfo. tb. } } else if(field == _btnCDMA) { if (_intRadioOn[1]) { Radio. _btn3G.setLabel("3G Radio is off").setChangeListener(this). _btnWiFi.WAF_3GPP). _intRadioOn[0] = true. _btn3G. vfm. } if ((wafs & RadioInfo.WAF_3GPP). } public void fieldChanged(Field field.setLabel("WiFi Radio is on").WAF_WLAN) != 0 ) { _intRadioOn[2] = true. } add(vfm).addSignalIndicator(). if ((wafs & RadioInfo. _btnWiFi.WAF_CDMA) != 0 ) { _intRadioOn[1] = true. _btnCDMA. } else { Radio.setLabel("3G Radio is on").add(_btnWiFi). _btn3G. StandardTitleBar tb = new StandardTitleBar().setLabel("CDMA Radio is on").Beta Customers Only. tb.getActiveWAFs().

setLabel("CDMA Radio is on"). _intRadioOn[1] = true. _btnCDMA. _intRadioOn[2] = true. _btnWiFi.setLabel("WiFi Radio is on").WAF_CDMA). } } 57 .WAF_WLAN). _btnWiFi. Content and software are subject to change. } } } } else { Radio.Beta Customers Only.deactivateWAFs(RadioInfo.RIM Confidential and Proprietary Information .activateWAFs(RadioInfo. } else { Radio. } } else if(field == _btnWiFi) { if (_intRadioOn[2]) { Radio. _intRadioOn[2] = false.WAF_WLAN).setLabel("WiFi Radio is off").activateWAFs(RadioInfo.

api.io.nfc.io.device. When a device detects a smart tag. and so on.readerwriter and the net. Only one DetectionListener object can access a smart tag at a time while the smart tag is within the range of the NFC radio. a DetectionListener receives a Target object that contains the URI that is required to open a connection to the tag.nfc. the data on a smart tag refers to another information source or a data channel. such as a movie or a coupon • provide pairing information for a Bluetooth® accessory • provide identification information for a smart dock net. 58 .api. Import the required classes and interfaces.nfc.nfc. Near Field Communication 6 BlackBerry® devices that are equipped with a Near Field Communication (NFC) radio enable an application to interact with smart tags.device.rim. When one DetectionListener finishes with the smart tag. The net.NDEFMessageListener interface to receive messages from a smart tag that is configured according to the NDEF Technical Specification.rim.api.readerwriter. and other NFC-enabled devices. NFC technology is designed to transfer small amounts of data over a short distance. smart docks. You can implement the net. smart accessories.rim.ndef packages The NFC API enables you to read and write smart tags formatted according to the NDEF Technical Specification. The BlackBerry device provides an NDEFMessage object that contains the data from the smart tag to an NDEFMessageListener. the device can notifiy your application that a tag is available. Content and software are subject to change.rim.api. Working with smart tags The NFC feature on a BlackBerry® device is typically activated by a user when the user taps a smart tag. If you registered a listener that matches the configuration of the smart tag that a user taps.RIM Confidential and Proprietary Information . In many cases.io.io.nfc. another DetectionListener can open a connection to the smart tag if it is still in range. Applications that register an NDEFMessageListener object can restrict the Record Type Definition and record type that trigger the application.readerwriter package also includes programming elements that enable you to communicate with ISO14443 smart tags.rim.DetectionListener interface to enable your application to receive notification of a connection to any smart tag that conforms to the ISO14443 standard. When invoked.device.device. You can use smart tags to: • provide a URL where a user can retrieve more information about an advertisement on a smart poster. You can implement the net.device.Beta Customers Only. Some examples of smart accessories and NFCenabled devices include bluetooth speakers.io. The include classes and interfaces that enable you to read and write NDEF-formatted smart tags. Create an NDEF tag writer 1.api.ndef. the device notifies applications that registered relevant listener objects.

ndef. ReaderWriterManager nfc.device.*.nfc.component. Add your screen object to the display stack. create a status screen and instantiate your implementation of the DetectionListener interface. 5.*. public void registerListener(NDEFWriterListener listener) { 7. 8. You implement a DetectionListener in step 10. You create a status screen in step 25.device. registerListener(listener).io. Indicate that you want to listen for the NDEF tag target type. import java. net.Beta Customers Only.rim. Declare your application class and start your application.api. import import import import import import net. import javax. net.enterEventDispatcher().getInstance(). Invoke a method to register your implementation of DetectionListener. 2.NFCException.rim.ui.io.io.ui. You delcare a registerListener method in step 6. } 3.IOException.Connector.device. In your application's constructor. NDEFWriterListener listener = new NDEFWriterListener(screen). public class NDEFWriterDemo extends UiApplication { public static void main(String[] args) { new NDEFWriterDemo().rim.nfc. net.ByteArrayOutputStream.lang.api.ui. 59 .api. net. Retrieve the system instance of ReaderWriterManager.io. net. public NDEFWriterDemo() { NDEFWriterScreen screen = new NDEFWriterScreen().*. 6. try { nfc = ReaderWriterManager.api. import java. Register your implementation of DetectionListener.device.*. } pushScreen(screen).device.device.rim.io.container.rim.LabelField.io.rim.api.microedition. Content and software are subject to change. 4.readerwriter.nfc. import java.RIM Confidential and Proprietary Information .String. Create a registerListener() method.api.

getBytes()).TNF_WELL_KNOWN.getBytes()).setType(NDEFRecord. Create an instance variable to hold a reference to the status screen and assign a value to the status screen variable in your constructor. // encoding payload1.write("My Title". titleRec. private NDEFWriterScreen display.write((byte) 0x05). private NDEFMessage createSmartTag() throws IOException { 13. catch (NFCException e) { // add your error handling code here } } 10.Beta Customers Only. uriRec. "U"). NDEFRecord uriRec = new NDEFRecord(). // status byte .write("en-US". titleRec. titleRec.getBytes()). Process any errors that occur. 9. ByteArrayOutputStream payload2 = new ByteArrayOutputStream(). private class NDEFWriterListener implements DetectionListener { 11. // uri 60 . // abbreviation: http://www. public NDEFWriterListener(NDEFWriterScreen screen) { super().toByteArray()). 14. Declare your implementation of DetectionListener. // title payload1.com".setId("1"). Create a createSmartTag method to define the content to write to a smart tag. NDEFRecord titleRec = new NDEFRecord(). } 12. Create an NDEF record to write to the smart tag.setType(NDEFRecord.flush().write("blackberry. payload2.NDEF_TAG}). payload1. Content and software are subject to change.RIM Confidential and Proprietary Information . payload2.write((byte) 0x01). Create a second NDEF record to write to the smart tag.setId("2"). display = screen.setPayload(payload1. "T"). } nfc. uriRec.addDetectionListener(listener.TNF_WELL_KNOWN. new int[]{Target. ByteArrayOutputStream payload1 = new ByteArrayOutputStream().length of encoding payload1.

Content and software are subject to change. 22."). NDEFTagConnection c = null.write(smartTag)."). NDEFMessage rootMessage = new NDEFMessage().setPayload(payload2.open( target. "Sp").message("Tag detected. rootRec.flush(). Update the message on the status screen. display. NDEFMessage ndefMessage = new NDEFMessage(). 17. } display. 16. 15. payload2. 20. catch (NFCException e) { display."). 18.message("Could not write to tag. Set your NDEFMessage to be the first message on the smart tag. c = (NDEFTagConnection)Connector. uriRec.getBytes().message() method to update the message on the status screen. Create an NDEFMessage to write to the smart tag. Declare the onTargetDetected method. try { NDEFMessage smartTag = createSmartTag(). byte[] rootPayload = ndefMessage.setRecords(new NDEFRecord[] {rootRec}). Attempting to write data. Create an NDEF message and populate it with your NDEF records. rootRec. Open a connection to the smart tag.setRecords(new NDEFRecord[] {titleRec. uriRec}). Retrieve the URI for the connection using the Target. Cast the connection using the NDEFTagConnection interface. rootMessage.Beta Customers Only. } return rootMessage. 21.TNF_WELL_KNOWN.NDEF_TAG)). Create a variable for the connection to the smart tag. 24.setType(NDEFRecord. 61 . Attempting to write data. Return the NDEFMessage to the invoking method.toByteArray()). Invoke the display. 23. public void onTargetDetected(Target target) { 19. ndefMessage.getUri(Target.setPayload(rootPayload).RIM Confidential and Proprietary Information . c.message("Tag detected.getUri() method. Process any errors that occur. NDEFRecord rootRec = new NDEFRecord().

ui.api. Create a message() function to update the text in the label when tag related events occur.nfc. net.ByteArrayOutputStream.lang. } } } // add your error handling code here 25.nfc.io. } 62 . Content and software are subject to change. import java.api.api.api.ui.device.nfc. net.device. add(lbl).ndef.enterEventDispatcher().RIM Confidential and Proprietary Information .Beta Customers Only. public NDEFWriterScreen() { lbl = new LabelField("Tap a smart tag to write data.FIELD_VCENTER). Declare a constructor for your status screen.device.io.api.rim. net.nfc.NDEFTagConnection. net. net.LabelField.ndef.io.io. import javax. import import import import import import import import import net. Field. } 27.container. private class NDEFWriterScreen extends MainScreen { private LabelField lbl.nfc.rim. public class NDEFWriterDemo extends UiApplication { public static void main(String[] args) { new NDEFWriterDemo().rim.api.api.IOException.device.rim. 26. public void message(String msg) { lbl.rim. net.device.api.microedition.device.Connector.ui. net.rim.".device. Declare a status screen class and create an instance variable to hold a reference to a LabelField control.setText(msg).Field.device. Initialize your label and add it to the screen.ndef.rim. } } } Code sample: Creating an NDEF tag writer import java.io.NDEFMessage. net.component.*.ui.String.readerwriter.rim.io. import java.api.UiApplication.device.NFCException.NDEFRecord.io.FIELD_HCENTER| Field.rim.MainScreen.io.

} private class NDEFWriterListener implements DetectionListener { private NDEFWriterScreen display. // save your registration state in persistent storage } catch (NFCException e) { // error handling code } } private class NDEFWriterListener implements DetectionListener { private NDEFWriterScreen display.NDEF_TAG}).TNF_WELL_KNOWN.setId("1"). ByteArrayOutputStream payload1 = new ByteArrayOutputStream(). payload1. public NDEFWriterDemo() { // detect whether or not you // registered a listener already // if not. display = screen. new int[]{Target.getInstance(). display = screen. try { nfc = ReaderWriterManager.length of encoding payload1. titleRec.setType(NDEFRecord.Beta Customers Only. } private NDEFMessage createSmartTag() throws IOException { NDEFRecord titleRec = new NDEFRecord().write((byte) 0x05). // encoding 63 .write("en-US". then register a listener NDEFWriterScreen screen = new NDEFWriterScreen(). nfc. titleRec. "T"). // status byte .getBytes()). NDEFWriterListener listener = new NDEFWriterListener(screen).RIM Confidential and Proprietary Information . public NDEFWriterListener(NDEFWriterScreen screen) { super().addDetectionListener(listener. pushScreen(screen). } public void registerListener(NDEFWriterListener listener) { ReaderWriterManager nfc. public NDEFWriterListener(NDEFWriterScreen screen) { super(). Content and software are subject to change. registerListener(listener).

uriRec. Attempting to write data. NDEFRecord uriRec = new NDEFRecord(). // add your error handling code here } private class NDEFWriterScreen extends MainScreen { private LabelField lbl. ByteArrayOutputStream payload2 = new ByteArrayOutputStream().message("Tag detected. } } c = (NDEFTagConnection)Connector. } catch (NFCException e) { display.getBytes()).").message("Could not write to tag.flush().setRecords(new NDEFRecord[] {rootRec}).open( target. Attempting to write data.setPayload(rootPayload). display.setId("2").NDEF_TAG)).setRecords(new NDEFRecord[] {titleRec. try { NDEFMessage smartTag = createSmartTag().Beta Customers Only.toByteArray()).flush(). rootRec. payload1. NDEFMessage rootMessage = new NDEFMessage(). public NDEFWriterScreen() { 64 .write((byte) 0x01). NDEFMessage ndefMessage = new NDEFMessage(). payload2. "U"). titleRec.message("Tag detected. rootMessage.getBytes(). byte[] rootPayload = ndefMessage. rootRec.").com". public void onTargetDetected(Target target) { NDEFTagConnection c = null. uriRec. // abbreviation: http://www.").setType(NDEFRecord.RIM Confidential and Proprietary Information .setType(NDEFRecord.setPayload(payload1. display. NDEFRecord rootRec = new NDEFRecord().getBytes()).TNF_WELL_KNOWN.getUri(Target.write("blackberry.toByteArray()). // uri payload2. "Sp").TNF_WELL_KNOWN. uriRec. payload2. ndefMessage. c. // title payload1.write("My Title". Content and software are subject to change.setPayload(payload2. uriRec}). } return rootMessage.write(smartTag).

} Create an NDEF tag reader 1.io. Field.*. } lbl = new LabelField("Tap a smart tag to write data.rim. Declare your application class and start your application.device.rim. add(lbl).device.api. net.lang.*.NFCException. You create this screen in step 11.".RIM Confidential and Proprietary Information .rim.component.nfc.device.api.nfc.*.api.ndef.ui.ui. Content and software are subject to change. Import the required classes and interfaces.rim.rim.String. } 4.io. Attempt to retrieve the system instance of ReaderWriterManager.nfc. try 65 .*.api.FIELD_VCENTER).enterEventDispatcher(). net. 2. import import import import import import net. import java. net. } 3.api. net.io.device.Beta Customers Only.rim.readerwriter. ReaderWriterManager nfc. add a screen to the display stack to allow a user to interact with your application.FIELD_HCENTER|Field. public NDEFReaderDemo() { pushScreen(NDEFReaderScreen()).device.api.device. public class NDEFReaderDemo extends UiApplication { public static void main(String[] args) { new NDEFReaderDemo(). public void registerListener(NDEFReaderListener listener) { 5.ui. } } public void message(String msg) { lbl.container. net.*. Create a registerListener() function. In your application's constructor.setText(msg).

TNF_WELL_KNOWN. Create a similar method to deregister the listener if required.alert(e. } 10. Process any errors that occur. Register your implementation of NDEFMessageListener.alert(e. public void onNDEFMessageDetected(NDEFMessage msg) { NDEFReaderDemo.this. Implement the onNDEFMessageDetected() method. Declare your implementation of NDEFMessageListener.Pass the NDEF records as a parameter to the screen's constructor. NDEFRecord.addNDEFMessageListener(listener. private NDEFReaderListener(NDEFReaderScreen screen) { super(). { nfc = ReaderWriterManager. } 7. and assign a value to it in the constructor.TNF_WELL_KNOWN. } 66 . nfc. Add an instance variable to keep a reference to the UI. "Sp").getInstance().getInstance(). } } 9.toString()).removeNDEFMessageListener(NDEFRecord.getRecords()).RIM Confidential and Proprietary Information . } } 8.displayRecs(msg. "Sp". nfc. } catch(NFCException e) { Dialog. 6. catch (NFCException e) { Dialog. true).Beta Customers Only. display = screen. Indicate that you want to listen for a smart poster. Content and software are subject to change. public void deregisterListener() { try { ReaderWriterManager nfc = ReaderWriterManager.toString()). private class NDEFReaderListener implements NDEFMessageListener { private NDEFReaderScreen display.invokeLater(new Runnable() { public void run() { display.

create an array of LabelField objects and add them to a vertical field manager.getTypeNameFormat() + ".Field. LabelField lbl[] = new LabelField[numRecords]. btn2.Beta Customers Only. then add a label to the screen to inform the user. Determine whether any records were passed to this method. } 15. btn2. If no NDEF records were read from the tag.FIELD_HCENTER| Field. String record = "ID: " + records[j]. Content and software are subject to change. for (int j = numRecords . btn2 = new ButtonField("Deregister Persistent Listener". if (numRecords > 0) { 14. public void displayRecs(NDEFRecord[] records) { int numRecords = records. } } 11. add(btn2). }). Create instance variables to keep references to the buttons on the screen. 67 . In the constructor.FIELD_HCENTER| Field. create your buttons and add them to the screen. add(btn1).getId() + ". Add the vertical field manager to the screen to contain the labels. private class NDEFReaderScreen extends MainScreen implements FieldChangeListener { ButtonField btn1. Type: " + records[j].setChangeListener(this).setText(record).1. lbl[j]. btn1.RIM Confidential and Proprietary Information .getType() + ". } add(vfm). Create a displayRecs method to display any records you receive from the smart tag. private NDEFReaderScreen() { btn1 = new ButtonField("Register Persistent Listener". TNF: " + records[j].FIELD_VCENTER). Payload: " + records[j]. j >= 0.getPayload().Field. VerticalFieldManager vfm = new VerticalFieldManager().length. vfm. If NDEF records exist. 12. Declare a screen class to display the NDEF records from the smart poster.FIELD_VCENTER).setChangeListener(this). j--) { lbl[j] = new LabelField().add(lbl[j]). } 13.

device.api.device.nfc.NFCException. } public void registerListener(NDEFReaderListener listener) { try { ReaderWriterManager nfc = ReaderWriterManager.*.api.*.rim.device.rim.getInstance(). Implement the fieldChanged method to respond when the user presses the button.rim.readerwriter.container.nfc. net.*.*. NDEFRecord.FIELD_VCENTER). import import import import import import net.String.io.addNDEFMessageListener(new NDEFReaderListener().device.api.ui. public void fieldChanged(Field field.api.Beta Customers Only. net.api. true).rim.nfc. } } } Code sample: Creating an NDEF tag reader import java.io. public class NDEFReaderDemo extends UiApplication { public NDEFReaderDemo() { pushScreen(NDEFReaderScreen()). add(lbl). Content and software are subject to change. } public NDEFReaderDemo() { pushScreen(NDEFReaderScreen()). net. else { } } } LabelField lbl = new LabelField("This tag contains no records".component.api.*.FIELD_HCENTER|Field. nfc.TNF_WELL_KNOWN.rim. } else if (field == btn2) { deregisterListener(). "Sp". 16.ui.ui. net.io.rim. Field. net.device. int context) { if (field == btn1) { registerListener(new NDEFReaderListener(this)).RIM Confidential and Proprietary Information .lang.device.ndef. // save your registration state in persistent storage 68 .

RIM Confidential and Proprietary Information . nfc. btn2 = new ButtonField("Deregister Persistent Listener".FIELD_HCENTER| Field. } } private class NDEFReaderScreen extends MainScreen implements FieldChangeListener { ButtonField btn1.setChangeListener(this). btn1.FIELD_VCENTER).alert(e.getRecords()). } }). private NDEFReaderScreen() { btn1 = new ButtonField("Register Persistent Listener".Field.alert(e.this. add(btn2).Field. } catch(NFCException e) { Dialog. } } private class NDEFReaderListener implements NDEFMessageListener { private NDEFReaderScreen display.toString()). btn2. } public void onNDEFMessageDetected(NDEFMessage msg) { NDEFReaderDemo. } } public void deregisterListener() { try { ReaderWriterManager nfc = ReaderWriterManager.removeNDEFMessageListener(NDEFRecord. display = screen.toString()).FIELD_VCENTER). } public void displayRecs(NDEFRecord[] records) 69 .displayRecs(msg. } catch(NFCException e) { Dialog. private NDEFReaderListener(NDEFReaderScreen screen) { super(). add(btn1).setChangeListener(this). Content and software are subject to change.FIELD_HCENTER| Field. "Sp").getInstance().TNF_WELL_KNOWN.Beta Customers Only. btn2.invokeLater(new Runnable() { public void run() { display.

lang. import javax.ui.FIELD_HCENTER|Field. VerticalFieldManager vfm = new VerticalFieldManager().getTypeNameFormat() + ".device.readerwriter. net.io.MainScreen. Import the required classes and interfaces. int context) { if (field == btn1) { registerListener(new NDEFReaderListener(this)). vfm.1. net. Type: " + records[j].*.RIM Confidential and Proprietary Information .api. } } } public void fieldChanged(Field field. import import import import import import net.nfc.Field. add(lbl).FIELD_VCENTER).device.ui. net. import java. String record = "ID: " + records[j]. } add(vfm). } else { LabelField lbl = new LabelField("This tag contains no records".NFCException.device.rim.component.setText(record).ui.rim. Field.length.IOException.device.ui.rim. TNF: " + records[j]. import java.LabelField.container.microedition.io. j >= 0.getId() + ".rim. } else if (field == btn2) { deregisterListener().UiApplication. j--) { lbl[j] = new LabelField().api.api. for (int j = numRecords .rim.getPayload(). net.api. Payload: " + records[j].io.Connector. Content and software are subject to change. 70 .api.device.Beta Customers Only.device.getType() + ". if (numRecords > 0) { LabelField lbl[] = new LabelField[numRecords]. } } } Communicate with an ISO14443 smart tag 1.io.add(lbl[j]). net. { int numRecords = records. lbl[j].nfc.api.String.rim.

Beta Customers Only. Create a registerListener() function. ReaderWriterManager nfc.enterEventDispatcher(). Attempt to retrieve the system instance of ReaderWriterManager. public class ISO14443Demo extends UiApplication { public static void main(String[] args) { new ISO14443Demo(). Register your implementation of DetectionListener. 7.getInstance(). 2. Declare your application class and start your application. catch (NFCException e) { // add your error handling code here } } 8. 6. Declare your implementation of DetectionListener. public void registerListener() { 5. Create local variables to hold references to the following resources: • the connection to the smart tag • the command to send to the smart tag • the response from the smart tag public void onTargetDetected(Target target) { ISO14443Part3Connection c = null. Process any errors that occur. Content and software are subject to change. } nfc. } 4. invoke a function to register your implementation of DetectionListener. public ISO14443Demo() { registerListener().RIM Confidential and Proprietary Information . Implement the onTargetDetected() method. } 3. try { nfc = ReaderWriterManager. private class ISO14443Listener implements DetectionListener { 9. 71 . In your application's constructor.addDetectionListener(new ISO14443Listener()).

11. In the constructor. Retrieve the URI for the connection using the Target. byte[] response = null. Field. Send your command to the smart tag and retrieve the response.microedition.ISO_14443_3)). } response = c. and add the label to the screen to display the data. 12. Pass the response variable as a parameter to the screen's constructor. Declare a screen class to display the response data from the smart tag. import net. Process any errors that occur.api. 10.IOException. Use Connector. import java. Content and software are subject to change.FIELD_VCENTER). } } } Code sample: Communicating with an ISO 14443 tag import java. try { c = (ISO14443Part3Connection)Connector. initialize a LabelField object. Cast the connection using the ISO14443Part3 interface. add(lbl).lang.device. // make sure to follow the specification for the // manufacturer and model of your tag // the command below is provided as a sample only byte[] iso14443Command = {(byte) 0x30. Add a screen to the display stack to show the response from the smart tag. 72 . } 14.io.open( target. Populate the label with the smart tag response data.getUri() method.rim. import javax.Beta Customers Only. (byte) 0x03}.transceive(iso14443Command).getUri(Target. catch (NFCException e) { // add your error handling code here // make sure to set a non-null value for response } 13.Field.open() to open a connection to the smart tag.FIELD_HCENTER| Field. private class ISO14443DemoStatusScreen extends MainScreen { public ISO14443DemoStatusScreen(byte[] response) { LabelField lbl = new LabelField(response.String.Connector.RIM Confidential and Proprietary Information .io. } pushScreen(new ISO14443DemoStatusScreen(response)).ui.

ui. import import import import import net.UiApplication.RIM Confidential and Proprietary Information .nfc.addDetectionListener(new ISO14443Listener()).device. response = c.component.api.NFCException.rim. Content and software are subject to change.*.device.open( target.ui. (byte) 0x03}.enterEventDispatcher().api.getUri(Target. } public void registerListener() { ReaderWriterManager nfc. net. try { nfc = ReaderWriterManager.device.readerwriter.getInstance(). then register a listener registerListener(). } catch (IOException e) { byte[] response 73 .ISO_14443_3)).device.ui.io. nfc.rim.LabelField. = null.Beta Customers Only.api. net.container.nfc. // make sure to follow the specification for the // manufacturer and model of your tag // the command below is provided as a sample only byte[] iso14443Command = {(byte) 0x30.MainScreen.device.api. } public ISO14443Demo() { // detect whether or not you // registered a listener already // if not.rim.io.rim. net. // save your registration state in persistent storage } catch (NFCException e) { // error handling code } } private class ISO14443Listener implements DetectionListener { public void onTargetDetected(Target target) { ISO14443Part3Connection c = null. try { c = (ISO14443Part3Connection)Connector.rim. public class ISO14443Demo extends UiApplication { public static void main(String[] args) { new ISO14443Demo().transceive(ISO14443Command). net.api.

Content and software are subject to change. Field.FIELD_VCENTER). } } // error handling code // make sure to set a non-null value for response pushScreen(new ISO14443DemoStatusScreen(response)). } } } 74 . } private class ISO14443DemoStatusScreen extends MainScreen { public ISO14443DemoStatusScreen(byte[] response) { LabelField lbl = new LabelField(response.FIELD_HCENTER| Field. add(lbl).Beta Customers Only.RIM Confidential and Proprietary Information .

RIM Confidential and Proprietary Information .Beta Customers Only. Content and software are subject to change. Glossary 3GPP Third Generation Partnership Project AES Advanced Encryption Standard API application programming interface APN access point name BlackBerry MDS BlackBerry® Mobile Data System CDMA Code Division Multiple Access EDGE Enhanced Data Rates for Global Evolution EVDO Evolution Data Optimized GAN generic access network GERAN GSM-EDGE Radio Access Network GCF Generic Connection Framework GPRS General Packet Radio Service GSM Global System for Mobile Communications® HTTP Hypertext Transfer Protocol 7 75 .

Beta Customers Only. Content and software are subject to change. HTTPS Hypertext Transfer Protocol over Secure Sockets Layer IP Internet Protocol JSON JavaScript Object Notation RDF Resource Description Framework RSS Really Simply Syndication SOAP Simple Object Access Protocol SSL Secure Sockets Layer TCP Transmission Control Protocol TLS Transport Layer Security Triple DES Triple Data Encryption Standard UDP User Datagram Protocol URI Uniform Resource Identifier URL Uniform Resource Locator UMTS Universal Mobile Telecommunications System UTRAN UMTS Terrestrial Radio Access Network 76 .RIM Confidential and Proprietary Information .

Beta Customers Only. Content and software are subject to change.RIM Confidential and Proprietary Information . VPN Virtual Private Network WAP Wireless Application Protocol WLAN wireless local area network WTLS Wireless Layer Transport Security XML Extensible Markup Language 77 .

Provide feedback To provide feedback on this deliverable.com/docsfeedback.blackberry. 8 78 . visit www.Beta Customers Only.RIM Confidential and Proprietary Information . Content and software are subject to change.

Document revision history Date 31 May 2011 Description Changed the following topics: • Networking and connectivity overview Network connections Added the following topics: • Code sample: Creating an NDEF tag reader • Code sample: Creating an NDEF tag writer • Code sample: Communicating with an ISO14444 tag • Communicate with an ISO14444 smart tag • Create an NDEF tag reader • Create an NDEF tag writer • Near Field Communication • Working with smart tags Changed the following topics: • Architecture: Network Transports • Communicating with HTTP servers • Network tranport options First draft released.RIM Confidential and Proprietary Information .Beta Customers Only. 9 8 November 2010 27 September 2010 79 . Content and software are subject to change.

RIM®.com/go/docs is provided or made accessible "AS IS" and "AS AVAILABLE" and without condition. representation. ALL CONDITIONS. CDMA2000 is a trademark of the Telecommunications Industry Association. SERVICE. This documentation including all documentation incorporated by reference herein such as documentation provided or made available at www. Legal notice 10 ©2011 Research In Motion Limited. copyright compliance. SOME JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES AND CONDITIONS. OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN. and logos are the property of Research In Motion Limited and are registered and/or used in the U. OR ARISING FROM A STATUTE OR CUSTOM OR A COURSE OF DEALING OR USAGE OF TRADE. HARDWARE. IN NO EVENT SHALL RIM BE LIABLE FOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE. REPRESENTATIONS. legality.RIM Confidential and Proprietary Information . this documentation may describe some aspects of RIM technology in generalized terms. OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN INCLUDING WITHOUT LIMITATION ANY OF THE FOLLOWING DAMAGES: DIRECT. MERCHANTABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION. links. GUARANTEES. REPRESENTATIONS OR WARRANTIES OF DURABILITY. trustworthiness. OR TITLE. or any other aspect of Third Party Products and Services. or other inaccuracies. errors. however. RIM does not control. or warranty of any kind by Research In Motion Limited and its affiliated companies ("RIM") and RIM assumes no responsibility for any typographical. WiFi is a trademark of the Wi-Fi Alliance. TO THE EXTENT PERMITTED BY LAW.S. any Third Party Products and Services including. ARE HEREBY EXCLUDED. OR WARRANTIES OF ANY KIND. INCLUDING WITHOUT LIMITATION. or omissions in this documentation. guarantee. OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE.Beta Customers Only. 3GPP. ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENT THEY CANNOT BE EXCLUDED AS SET OUT ABOVE. 80 . enhancements. RIM reserves the right to periodically change information that is contained in this documentation. hardware or software. BlackBerry®. UMTS are trademarks of the European Telecommunications Standards Institute. FITNESS FOR A PARTICULAR PURPOSE OR USE. JavaScript are trademarks of Oracle America. decency. EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION. MERCHANTABLE QUALITY. ANY CONDITIONS. ENDORSEMENTS. compatibility. SERVICE. This documentation might contain references to third-party sources of information. and countries around the world.blackberry. accuracy. Content and software are subject to change. updates. The inclusion of a reference to Third Party Products and Services in this documentation does not imply endorsement by RIM of the Third Party Products and Services or the third party in any way. Java. SATISFACTORY QUALITY. Inc. without limitation the content. GUARANTEES. NON-INFRINGEMENT. OR RELATED TO THE DOCUMENTATION OR ITS USE. ENDORSEMENTS. and related trademarks. BUT CAN BE LIMITED. names. endorsement. technical. ARE HEREBY LIMITED TO NINETY (90) DAYS FROM THE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEM THAT IS THE SUBJECT OF THE CLAIM. EXPRESS OR IMPLIED. or other additions to this documentation to you in a timely manner or at all. and is not responsible for. OR PERFORMANCE OR NONPERFORMANCE OF ANY SOFTWARE. RIM makes no commitment to provide any such changes. performance. In order to protect RIM proprietary and confidential information and/or trade secrets. Research In Motion®. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE OR PROVINCE. products or services including components and content such as content protected by copyright and/or third-party web sites (collectively the "Third Party Products and Services"). All other trademarks are the property of their respective owners. HARDWARE. All rights reserved.

Certain features outlined in this documentation require a minimum version of BlackBerry® Enterprise Server. AUTHORIZED RIM DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE PROVIDERS) AND THEIR RESPECTIVE DIRECTORS. AND (B) TO RIM AND ITS AFFILIATED COMPANIES. You should not install or use Third Party Products and Services until all necessary licenses have been acquired. OR ACTION BY YOU INCLUDING BUT NOT LIMITED TO BREACH OF CONTRACT. Check with your service provider for availability. Any Third Party Products and Services that are provided with RIM's products and services are provided as a convenience to you and are provided "AS IS" with no express or implied conditions. COST OF SUBSTITUTE GOODS. DUTY. EXEMPLARY. INDIRECT. or using any Third Party Products and Services. Content and software are subject to change. COST OF CAPITAL. service plans and features. BlackBerry® Desktop Software. BUSINESS INTERRUPTION. EXCLUSIONS. SUPPLIERS (INCLUDING AIRTIME SERVICE PROVIDERS). TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION. You are solely responsible for determining whether to use Third Party Products and Services and if any third party licenses are required to do so. If required you are responsible for acquiring them. THEIR SUCCESSORS. COSTS OF COVER. LOSS OF THE USE OF RIM PRODUCTS OR SERVICES OR ANY PORTION THEREOF OR OF ANY AIRTIME SERVICES. OR CORRUPTION OR LOSS OF DATA. endorsements. NEGLIGENCE. it is your responsibility to ensure that your airtime service provider has agreed to support all of their features. AGENT.Beta Customers Only.RIM Confidential and Proprietary Information . SUPPLIER. FAILURES TO TRANSMIT OR RECEIVE ANY DATA. Your use of Third Party Products and Services shall be governed by and subject to you agreeing to the terms of separate licenses and other agreements applicable thereto with third parties. Some airtime service providers might not offer Internet browsing functionality with a subscription to the BlackBerry® Internet Service. guarantees. AGENTS. copyright. DAMAGES FOR LOSS OF PROFITS OR REVENUES. INCIDENTAL. WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN. IN NO EVENT SHALL ANY DIRECTOR. or other licenses in order to avoid infringement or violation of third party rights. installing. SPECIAL. EMPLOYEES. OR OTHERWISE TO YOU INCLUDING ANY LIABILITY FOR NEGLIGENCE OR STRICT LIABILITY. CONSEQUENTIAL. OR LIABILITY WHATSOEVER IN CONTRACT. roaming arrangements. AND EVEN IF RIM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. PROBLEMS ASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITH RIM PRODUCTS OR SERVICES. AND INDEPENDENT CONTRACTORS. AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THE CAUSE OF ACTION. DEMAND. except to the extent expressly covered by a license or other agreement with RIM. STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND SHALL SURVIVE A FUNDAMENTAL BREACH OR BREACHES OR THE FAILURE OF THE ESSENTIAL PURPOSE OF THIS AGREEMENT OR OF ANY REMEDY CONTAINED HEREIN. PUNITIVE. LOSS OF BUSINESS OPPORTUNITY. and/or BlackBerry® Device Software. THE LIMITATIONS. FACILITIES OR SERVICES. DOWNTIME COSTS. Prior to subscribing for. TORT. IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE. trademark. FAILURE TO REALIZE ANY EXPECTED SAVINGS. EMPLOYEE. OR OTHER SIMILAR PECUNIARY LOSSES. TORT. DISTRIBUTOR. 81 . in relation thereto. or warranties of any kind by RIM and RIM assumes no liability whatsoever. LOSS OF BUSINESS INFORMATION. representations. RIM SHALL HAVE NO OTHER OBLIGATION. OR AGGRAVATED DAMAGES. Installation or use of Third Party Products and Services with RIM's products and services may require one or more patent. INDEPENDENT CONTRACTOR OF RIM OR ANY AFFILIATES OF RIM HAVE ANY LIABILITY ARISING FROM OR RELATED TO THE DOCUMENTATION. ASSIGNS.

Beta Customers Only. ON N2L 3W8 Canada Research In Motion UK Limited Centrum House 36 Station Road Egham.RIM Confidential and Proprietary Information . Surrey TW20 9LF United Kingdom Published in Canada 82 . The terms of use of any RIM product or service are set out in a separate license or other agreement with RIM applicable thereto. Research In Motion Limited 295 Phillip Street Waterloo. NOTHING IN THIS DOCUMENTATION IS INTENDED TO SUPERSEDE ANY EXPRESS WRITTEN AGREEMENTS OR WARRANTIES PROVIDED BY RIM FOR PORTIONS OF ANY RIM PRODUCT OR SERVICE OTHER THAN THIS DOCUMENTATION. Content and software are subject to change.

Sign up to vote on this title
UsefulNot useful