The Communication and Parsing API introduced in the BlackBerry® 6 OS probably doesn’t get as much attention as it really deserves. It has one of those names that could mean just about anything, but when I created a sample with it, I found it made many tasks simple – and I barely scratched the surface of what was possible.
You’ll find the API specification in the net.rim.device.api.io.messaging package, where you will see the significant set of interfaces and classes that provide all this functionality. The API breaks up communication into a few parts: The Destination is the target for a connection, usually a URL, and you can send and receive Message objects through it. Destinations can block the execution thread, or not, and you can send messages without handling the response with a FireAndForgetDestination. A Destination can also be connected with a MessageProcessor, which will parse the messages for you. Several processors are included in the API for common message formats like XML, JSON, RSS, and so on. Processors can be chained to support even more functionality. Finally, Messages can be retrieved as MessageFutures, and Destinations can be used to receive pushes and other incoming connections.
Behind the scenes is even more great stuff, like message queuing, prioritization, and even support for inter-process communication. Before we get too buried in the details, I should point out that the BlackBerry 6 SDK includes a full sample application that shows how to do all of this. The sample I want to share with you today is an example using this new API to streamline development of a YouTube® client. With the proliferation of APIs like YouTube’s Data API, which offer ATOM and JSON-C (for more bandwidth saving) interfaces, many opportunities become quite accessible.
Full sample code is included so you can check it out, but let’s look at some of the Communication API in action. The destination is the YouTube Data server with several basic query parameters:
The query I’ve used restricts the response somewhat to a mobile-friendly version, including filtering out any videos that don’t have a mobile video link – a useful feature for mobile clients that could be expanded on in this sample. I’ve also included a MessageProcessor to handle the output; in this case, it’s an XMLHashtableMessageProcessor, which nicely converts the ATOM response into a simple Hashtable, so I can do things like pulling all the titles out into a String array:
Once I’ve grabbed all the details I care about, I can send the results back to the screen for displaying. However, the feed response contains a URL for the thumbnails, so I need to download that as well. This is a neat opportunity to use non-blocking destinations and update the display when the thumbnails arrive: