Wireless DevCenter    
 Published on Wireless DevCenter (http://www.oreillynet.com/wireless/)
 http://www.oreillynet.com/pub/a/wireless/2001/06/22/rim.html
 See this if you're having trouble printing code examples


Developing Applications for the RIM BlackBerry

by P.V. Subramanian
06/22/2001

One would have thought that the laptop-toting, VPN-tunneling executives of today had little time left to give. The cell phone occupies them in their cars, and even the lengthiest flights become working sessions, thanks to spare batteries and more DC connections in business class.

If a few moments remain -- say, during dinners, movies or meetings -- wireless pagers can exploit them. The BlackBerry pager from Research in Motion (RIM) is one of the best known; so small you could hide it under your napkin, yet so talented that it can suck your email out of thin air. In short, a hip gadget for two-timing execs, trying to do two things at the same time, like responding to emails in meetings.

Other pagers can do email too; send, receive and compose. So what is the BlackBerry's unique selling proposition? RIM markets it on the basis that you don't need a desktop InBox and a separate RIM InBox. Combine the BlackBerry with some MS Exchange and Lotus Notes-based software-call it the BlackBerry Enterprise Solution--and your corporate InBox rips through firewalls to appear on your handheld. And thanks to the same enterprise software, no one can tell the difference between emails sent from your RIM and those sent from your desktop.

But I think the great thing about it is that the BlackBerry handheld is a fully-programmable handheld computer, built around a 32-bit Intel 386 processor, the same kind that could once run Windows.

In this introductory article, I'll cover basic details on the BlackBerry's hardware, operating system, and software developer kit (SDK). Then I'll cover some of the low-level wireless stuff, to familiarize you with its communication technology. Finally, I'll show you a sample application for RIM, a simple Hangman game.

Figure 1. More than just messaging devices, the RIM 950 and the Palm-sized 957 (shown above) are fully programmable handheld computers. This article shows how to program a simple Hangman game for the devices.

The Hardware, the Operating System, and the SDK

The preferred platform of choice today for developing RIM applications is Visual C++ (version 5.0 or greater). However, ever since RIM announced the "early access" Java development environment last year -- based on Sun's KVM -- there has been eager interest in a version that's fully J2ME compliant. RIM recently announced that it would begin shipping its first J2ME-compliant model later this summer.

While the single InBox story makes for a great sales pitch, I think the common tinkerer got handed something much more exciting: a tiny PC with built-in, always-on wireless connectivity that one can easily write applications for, single InBoxes just being one of them. Think point-of-sale systems, self-monitoring gas meters, remote control for your entire home, and you'll be getting the drift. (Other wireless devices are getting to the corporate InBox as well -- OS CorporateLink from OmniSky is one example -- so the InBox pitch may not work much longer for RIM.)

Blackberries come in two basic flavors, the pager-sized model with up to eight lines of display, and the palm-sized model with 19. In that tiny space lies confined a multitasking, multithreaded operating system, capable of running 31 applications at the same time. Applications are expected to be well-behaved, yielding control every so often, but in this dog-eat-dog world that's not quite enough. So the RIM OS has a couple of watch puppies triggering resets on encountering CPU hogs and deadlocks.

Memory. Writing applications for the BlackBerry requires coming to terms with the very small amount of memory available to your applications; 4 or 5 MB of flash memory and 512 KB of SRAM is all you have. Flash memory is the "disk space" available for your applications, but unlike a regular disk, read, write, and modify operations are dramatically different in terms of access times. Flash memory can be written in small increments, but erasures need to be performed on entire 64-KB sectors. So modifying even a single byte involves erasing an entire sector, and rewriting it with the modification. To counter this problem, the RIM OS simply chooses not to modify existing sectors at all, writing these modifications as sectors of new data instead, with the old data marked as old data. Old sectors are deleted when the file system runs out of space. Applications rarely seem to access the raw file system though. Unlike conventional applications, all file access is through a database API. For RIM applications, files are databases, and file contents are made of variable-sized database records.

Comment on this articleWhat do you want your RIM to do for you? And if you are developing exciting RIM applications, tell us about it.
Post your comments

User interface. One very un-pager-like feature of the pager-sized BlackBerry is its no-compromises user interface. As a developer, it is for you to decide how much to enrich your application's UI with widgets, but you have a surprisingly large menu to choose from: graphic icons, custom fonts, dialog boxes, edit boxes, and lists. User interaction is generally through the use of the clickable thumbwheel, much like the wheels on mice. The keyboard is so small, one would venture to suggest that the best BlackBerry applications use as little of it as possible.

Audio support in the Blackberry is about what you would expect from a PC speaker. You have simple control over frequency, intensity, and duration that lets you create a few tunes. Someone might make an MP3 player of it yet, but there is no really good reason to try it.

RIM's Wireless Protocols

At the core of the BlackBerry is its ability to send messages wirelessly. The Messaging API is what you would use for such high-level use of the communications stack, like sending emails (with MIME attachments and all), fax and phone. (Yes, phone! Skytel has a RIM-based service where you can send a message to a phone and a machine reads it out to the intrigued recipient.) RIM's SDK also includes a Radio API for packet-level access to the radio network, but it's unlikely you'd ever need to get down to the bits for your average power-executive application. But if you are going to be using the radio API, a good understanding of the prevalent protocols is useful.

Wireless handhelds cannot simply throw their data into the ether and hope for it to be picked up by a carrier. Not unless these packets conform to whatever standards the carrier's network is expecting. RIM's handhelds come in the Mobitex and DataTAC flavors. In the USA, Motient operates on DataTAC and BellSouth does Mobitex. (The Palm VII operates on Mobitex as well.)

Both Mobitex and DataTAC are packet-switched protocols. All connections between the wireless unit and the base station are session-less and shared. Data delivery is guaranteed, but since the network uses a store-and-forward mechanism, delivery times can vary significantly.

DataTAC is a narrowband PCS network, available around the world. DataTAC communications are broken up into SDUs, or Service Data Units. SDUs are addressed to other DataTAC equipment in the network by the use of Logical Link Identifiers (LLIs), which uniquely identify fixed or mobile DataTAC terminals (like BlackBerries). A single SDU can have up to 2,048 bytes of routing and payload information. Of course, all of this data is never transmitted in a single huge burst. SDUs are further broken up into smaller packets by the radio (usually 512 bytes). Each SDU is then transmitted at 9,600 bps or 19,200 bps. (You'll see that it is extremely difficult to answer the question "How fast is the data transmission?")

Mobitex communications are centered on the MPAK, or the Mobitex data packet. Packets are addressed through the use of 24-bit Mobile Access Numbers (MAN), which uniquely identify Mobitex-compatible equipment and are assigned by the manufacturer -- if you have a BlackBerry from BellSouth, look inside your battery compartment. After all the address and header information is put in, an MPAK can take 512 bytes of payload data.

Costs of Entry

In beginning to write applications for RIM devices, one of the biggest obstacles is the cost of buying these babies. BlackBerries are definitely expensive. The pager-sized unit typically costs about $400, activation takes another $30, and service can cost anywhere between $10 and $60 a month.

The Palm-sized units cost about $100 more, while activation and service costs are unchanged. In comparison, a Minstrel wireless modem for your Palm costs the same in service charges, and the modem could be free with a year-long contract. But the excellent simulator that comes with the SDK should leave developers with no excuses for not trying. Apart from a look-and-feel that mimics the BlackBerry precisely, the simulator also lets you treat your PC's serial port as a wireless modem. So with two PCs hooked up over a serial link, and running RIM simulators, you should have a very good "wireless" network to test your applications in.

If you are a little more adventurous, RIM also OEMs its equipment as a processor-radio combo. You get an Intel 386, a meg-and-a-quarter of memory, and the same OS as the off-the-shelf handhelds. The OEM units have numerous interfaces and so forth, and a couple of these interfaces are similar to RS-232.

As with the handhelds, there are Mobitex and DataTAC versions of the OEM equipment. And as with the handhelds, I found the OEM kit pricing, at $1,000, a bit steep. But then there are the millions awaiting you once you have wireless Tetris written for the BlackBerry. Or the less-challenging Hangman, which we shall presently set about building.

A Sample App: Hangman for the BlackBerry

RIM applications -- whether in Java or in C++ -- use an event-oriented architecture. The main function sets up high-level application parameters, and then leaves it to the event dispatcher to do the right thing. Writing applications in Java seemed a lot simpler than C++, but that opinion is definitely colored by this writer's preference.

Figure 2. The larger models of the RIM BlackBerry have more screen real estate than the pager-sized models -- better for playing games (and other apps, too).

Obtaining these SDKs involves registering at developers.rim.net. This gets you an email with a login and password. At most developer sites, registering for downloading SDKs is usually a nuisance, resulting in a lot of useless emails, but RIM also gives you email access to a technical contact who you can pound with emails for more information. (I haven't done much pounding so I can't say how well this works.)

Our example application is a simple version of the game of Hangman. The user has to guess all the letters in a six-letter word, and in doing so, can make up to 10 errors. With every error, the gallows and the body are built incrementally in a graphic, adding some excitement to the game.

In building RIM applications, the constraints that jump out at you are the tiny screen and the keyboard (the latter may not be obvious if you use the PC-based simulator a lot, but the less your app uses keyboard input, the more usable it is). There are memory and file-system constraints you need to be aware of, but it's unlikely you'd thinking about these in the first pass of writing your app.

The Hangman example goes all the way in avoiding the keyboard. The entire game is played using only the thumbwheel. Scrolling the wheel chooses letters, and clicking makes a selection.

Since Hangman uses the RIM UI, it needs to extend the UiApplication class. UiApplication keeps track of multiple screens that your app uses. Your app pushes screens to the foreground (or pops screens to the background) and UiApplication repaints the screen as necessary.

Related Links

http://developers.rim.net The "official" site for RIM development

www.rimsource.com Just-started website on RIM development

www.rimroad.com Part of the PDAStreet.com website. Small but growing collection of RIM apps. Empty message boards though.

RIM and BlackBerry Developer Resources. Numerous articles, developer resources, including a RIM SDK for Linux

www.handango.com Among other PDA paraphernalia, the must see RIM applications RIMReader and BerryChess

www.bellsouthwd.com/developers/ For developers who want to build applications that use the Cingular Wireless Network (Mobitex-based).

www.mobitex.org The Mobitex site

www.dopforum The DataTAC site

www.apriva.com RIM-based point-of-sale solutions (with a magnetic card reader attachment) and wireless barcode solutions.

Applications extending UiApplication usually also use one of the many screen classes available in Java. The simplest one to use is the MainScreen. It comes packaged with a title bar on top, a separator element (fancy name for a horizontal line) under the title bar, and a main area that is scrollable. MainScreen descends from a long lineage of classes, and you can choose to use one of the more complex parent classes to get more flexibility.

Most apps would also need to use listeners (as Java interfaces) to handle information from the user, the device, and the network. Hangman uses just one listener for listening to thumbwheel input, but there are other listeners for keypad, radio, system menu and even holster (like a belt clip) events.

As you would have guessed, the ThumbListener is simple, defining only four events (wheel clicked, unclicked, rolled up and rolled down). Its quite amazing how much can be done with such a small selection of events. In fact, Hangman does not even use the wheel unclicked event. And there isn't a double-click event at all.

You would need to do three things with every MainScreen: add graphic elements like labels, edit boxes etc.; add one or more listeners; and finally "push" the screen to the top of the UI stack so that UiApplication can set about painting it.

Here is the basic framework for most RIM applications:

public class SomeApp extends UiApplication implements ThumbListener 
        // and any more listeners you may need
{

	// Class variable definitions etc.

	public static void main(String[] args)
	{
		SomeApp someapp=new SomeApp();
        		someapp.enterEventDispatcher();
	}

public void activate()
   	{
		// activate() is called when the application is brought to the foreground
		// Initialize data, add UI elements etc.

myScreen = new MainScreen();

myScreen.addTitle(new TitleField("Hangman!")); // a TitleField give you the app title
myScreen.add( … ); // Other UI elements
	}

	public boolean thumbClick(int status, int time)
	{
		// Stuff you want happen on a click
	}

public boolean thumbUnclick(int status, int time)
{
	// Stuff you want happen on an un-click
}

public boolean thumbRollUp(int status, int time, int amount)
{
	// Stuff you want happen on an wheel roll-up
}

public boolean thumbRollDown(int status, int time, int amount)
{
	// Stuff you want happen on a wheel roll-down
}
}

The regular programming needed for the Hangman game -- picking a secret word, taking letters as input, keeping track of errors or lives, and so on -- is pretty simple if you know your Java. If you are into this sort of thing, take a look at the source code.

 
Figure 3. Programming the RIM in a Java Integrated Development Environment.  

Adding Graphics

Adding graphics to your application is a little less intuitive (but really easy!), and the SDK documentation is silent on the issue. Thankfully, one of the demo applications included with the SDK jumps right into this subject.

First, all the bitmaps necessary for Hangman were painfully created using Paint. Remember to use monochrome, and keep the size of your pictures small. These bitmaps need to be saved in GIF format. Here are the Hangman bitmaps (the last one is for winners, and whole thing reminiscent of The Dancing Men):

Figure 4. The 10 bitmap graphics that are called to play Hangman.

To add these pictures to the project, right-click on the project name and select "Add file to Hangman" (there is no multi-select!). The RIM Java IDE automatically creates a class containing resources for your application. You can see the name of this resources class by viewing your project properties, but it defaults to <your app name>Resources. The HangmanResources class lets you convert these GIFs to arrays -- with rows and rows of hexadecimal numbers. Such arrays are necessary to create objects of the class Bitmap, which is how pictures are represented within RIM applications. You could create these byte arrays by hand (no mean feat) or simply call the getBitmap("mypic.gif") function of your app's resources class. Just make sure mypic.gif is added to your project. Here is a code fragment from the Hangman app:

Bitmap win={ HangmanResources.getBitmap("win.gif") };

Hangman uses objects of the Dialog class to show these pictures, as well as small text messages, such as:

i=new Dialog("Well done!", s, m, 0, win).doModal();
Source Code

Download the source code for the RIM Hangman game here.

This shows the "win" Bitmap along with a congratulatory message. If you take a look at the code you will find that "s" is an array of strings that represent choices presented to the user as part of the dialog box. In this case the choices are "Play again" and "Bye."

Creating an application icon for Hangman involves no programming at all. Simply add the GIF file as a resource under the project, and set its properties, indicating that it will be used as an application icon. The IDE takes care of creating the appropriate resources, so that the icon appears as part of the ribbon (the series of icons that form the RIM toolbar).

That's all there is to the Hangman: some text processing, pictures and a couple of dialog boxes.

Of course, the magic in the BlackBerry is wireless communications, which we are not making any use of in creating our rather naïve Hangman game. Building wireless into Hangman gives rise to enormous possibilities: a list of news words transmitted over the air refreshing your game's database, two-player duels, and a whole society addicted to wireless Hangman. This isn't all fantasy, simply because its being done even as we speak. Take a look at Four Pegs on RimRoad, PDAStreet.com's site for RIM enthusiasts. Four Pegs lets you play with another gamer over the wireless network, and all you need to know is your opponent's PIN number.

And no one seems to have developed wireless Tetris yet, so hurry.


In our next article, we'll look at Glenayre's AccessLink, a simple two-way pager with an infrared port that can be used for inputting and outputting data.


P.V. Subramanian works as a product manager for a telecom company, but is a secret programmer after hours. His current interests are programming handheld devices, JDMK, and PoV-Ray.

Copyright © 2007 O'Reilly Media, Inc.