Programming the BlackBerry With J2ME

   
By Qusay H. Mahmoud, April 2005  

Developed by Research In Motion (RIM), the BlackBerry is a handheld wireless device whose major selling feature to date has been instant, secure, mobile access to email. New BlackBerry devices support voice communications as well. While some BlackBerry devices are based on C++, many new ones support the Java 2 Platform, Micro Edition (J2ME), primarily because Java technology makes developing applications so much easier. Its platform-independence eliminates many porting woes and its automatic garbage collection lets developers concentrate on application logic rather than memory management.

RIM's support for J2ME includes development of its own Java virtual machine (JVM) 1, which supports the Connected Limited Device Configuration (CLDC) and the Mobile Information Device Profile (MIDP). BlackBerry devices also come with additional BlackBerry-specific APIs, however, that enable developers to create applications that have the BlackBerry-native look and feel, and are more sophisticated than standard MIDlets developed using MIDP.

This article describes the BlackBerry architecture and two application models, and gets you started developing applications and deploying them on the BlackBerry.

Contents
 
The BlackBerry Architecture
BlackBerry Application Models
BlackBerry Extensions to J2ME
RIM's Java Development Environment
Running Existing MIDlets on the BlackBerry
Developing Applications Using the JDE
Deploying Applications Using the BlackBerry Desktop Manager
RIM's Extensions to JAD Files
Deploying BlackBerry Applications Over the Air
Conclusion
For more information
Acknowledgments
About the author
 
The BlackBerry Architecture

BlackBerry devices are offered by Nextel, Telus, T-Mobile, and many other wireless carriers. Once a device is on a carrier's network, it's linked to RIM's Network Operating Center (NOC), which has direct connections to all RIM's carrier partners and to BlackBerry Enterprise Servers (BES) deployed all over the world. The BlackBerry Enterprise Server (BES) software is middleware that links handheld devices to corporate email services such as Microsoft Exchange and Lotus Notes, as depicted in Figure 1:

Figure 1: BlackBerry Architecture With Wireless Gateways

Installed behind the corporate firewall, a BES can be configured with additional services. The Mobile Data Service (MDS), for instance, gives devices access to servers in the corporate intranet that wouldn't be accessible from public networks otherwise. For your BlackBerry to take advantage of such features you must configure it to use a BES when you install the Desktop Software Manager. This manager comes with the BlackBerry, but you install it on a computer connected to the corporate intranet, then connect the BlackBerry to that computer. Encryption keys are generated for secure communication between the device and the BES. On devices that aren't linked to a BES, email integration is achieved through a web-based client. You select the appropriate option when installing the Desktop Software Manager, as in Figure 2.

Figure 2: Desktop Software Manager Integration Options
BlackBerry Application Models

To give developers flexibility in designing sophisticated wireless applications for the enterprise, BlackBerry supports two application models:

  • The browser-based model allows developers to focus on developing back-end content in a standard markup language, such as the Wireless Markup Language (WML) or the compact Hypertext Markup Language (cHTML). Using existing browsers' client capabilities frees the developer from worrying about the client interface – but it does limit client functionality to what the browser provides, and there's no support for offline processing.
  • Custom Java applications enable developers to develop customized user interfaces and navigation, and support content beyond text and images. Developers can also build applications that users can download and install on wireless devices, so they can continue to use offline capabilities while out of wireless coverage. Several BlackBerry devices come with a complete set of APIs and tools that enable you to build custom Java-based applications.
BlackBerry Extensions to J2ME

In addition to full support of standard CLDC and MIDP APIs, RIM provides BlackBerry-specific extensions that enable you to develop applications with the look and feel of native applications. The BlackBerry APIs provide tighter integration for BlackBerry devices, and access to BlackBerry features for user interface, networking, and other capabilities.

Generally, you can use CLDC, MIDP, and BlackBerry APIs together in the same application – with the notable exception of user-interface APIs. A single application should not use both the javax.microedition.lcdui and net.rim.device.api.ui packages. RIM's UI APIs provide greater functionality and more control over the layout of your screens and fields, but at a cost: Resulting MIDlets will be non-standard, so porting to other platforms will require more effort.

Unlike MIDP's UI classes, RIM's are similar to Swing in the sense that UI operations occur on the event thread, which is not thread-safe as in MIDP. To run code on the event thread, an application must obtain a lock on the event object, or use invokeLater() or invokeAndWait() – extra work for the developer, but sophistication comes with a price tag.

Your choices come down to these: You can develop your application as a standard MIDlet that will run on any MIDP-enabled device, or as a RIMlet, a CLDC-based application that uses BlackBerry-specific APIs and therefore will run only on BlackBerry devices. If you're developing solely for the BlackBerry you should use the CLDC model because the RIM APIs will give you the BlackBerry-native look and feel &ndash without denying you the option to use J2ME-standard APIs in areas other than UI. For persistence, you can use BlackBerry's APIs or the MIDP RMS APIs; if you're already familiar with RMS, use it. For networking, use the Generic Connection Framework.

The main class of a RIMlet extends either net.rim.system.Application, if it's a background application with no user interaction, or net.rim.system.UiApplication if the RIMlet needs a user interface. Unlike a MIDlet's starting point, the entry point into a RIMlet is the main() method. As in the MIDP UI, a RIMlet screen is not a movable window. To display it you simply push it on the display stack using pushScreen(). I'll show you an example later.

RIM's Java Development Environment

The BlackBerry Java Development Environment (JDE) is an integrated development environment (IDE) that provides a complete set of tools and APIs for you to develop Java applications that run on BlackBerry devices. JDE requires the Java 2 SDK to run. It comes with a BlackBerry simulator for testing, but I recommend you obtain an actual BlackBerry device. I personally like the 7510 model, a data and voice handheld device for networks that adhere to the Integrated Digital Enhanced Network (iDEN) standard, such as Nextel in the US and Telus in Canada. Other devices run on GPRS or CDMA2000/1x networks. To test your applications you must also sign up with a wireless carrier for a plan that includes data services. You can get voice service as well, of course, but beware: Having both phone and email services in a single appealing mobile device is addictive!

Through the JDE you can compile your Java source code, package it in a .cod file, which is in a proprietary format, and load your application into the BlackBerry, whose JVM will then run it. Note that, as in other environments, a preverification process occurs before classes are loaded into the device. The JDE preverifies code automatically before packaging it in .cod files.

The current version of the JDE is 4.1. I've used JDE 3.6 for this article only because the BlackBerry I'm using came with version 3.6 of BlackBerry and I haven't upgraded the OS yet. For a list of the JDE versions available that indicates what OS versions they support, please see the JDE download page. Links to that page and to other resources for developers appear at Java SDKs and Tools.

Running Existing MIDlets on the BlackBerry

To run a standard MIDlet on a Java-enabled BlackBerry device, you first need to convert the .jad and .jar files to the .cod format, using the rapc command-line tool that comes with RIM's JDE. You'll find rapc in the bin directory of your JDE installation. This command converts a MIDlet named LoginMIDlet:

rapc import="c:\BlackBerryJDE3.6\lib\net_rim_api.jar" codename=LoginMIDlet -midlet jad=LoginMIDlet.jad LoginMIDlet.jar
 

You can load the resulting LoginMIDlet.cod file into your BlackBerry device from your desktop computer over a USB cable. Use the javaloader command, which can also be found in the bin directory of your JDE installation. I used this command to load LoginMIDlet.cod into my BlackBerry 7510:

javaloader -usb load LoginMIDlet.cod
 

Once the application is loaded into the BlackBerry, you can run it just as if it were a native application.

You can use javaloader to delete applications from the BlackBerry as well as to load them. This command will remove LoginMIDlet.cod from the BlackBerry:

javaloader -usb erase -f LoginMIDlet.cod
 
Developing Applications Using the JDE

Recall that BlackBerry applications that support user interaction extend net.rim.device.api.ui.UiApplication. This class provides methods for applications to register event listeners, manage threads, and manage UI components. When an application starts, the JVM invokes main(), which in turn calls enterEventDispatcher() to start handling events.

To get started developing BlackBerry applications with the JDE, you create a workspace, and subdirectories for each project. Then you create source files, build the application, and test it, much as in any IDE. Let's walk through development of a simple example.

Create a Workspace
  1. In the IDE, from the File menu, choose New workspace.
  2. Enter a name for the workspace and a pathname for the directory where it should be saved, and press OK.

    Figure 3: Create a Workspace
Create a Project
  1. From the Project menu, choose Create new project.
  2. Enter a name for the project and a directory where it should be saved, and press OK.
Figure 4: Create a Project
Create the Source Files
  1. From the File menu, choose New.
  2. Give a name to the file; include the .java extension.
  3. Enter the pathname of the project directory where you want the file saved, and press OK.

    Figure 5: Create a Java Source File
  4. In the editor pane, right-click the file, and choose Insert into project.

    Figure 6: Insert a File Into a Project
  5. Select the project and press OK.
  6. In the editor pane, enter the code for this sample Blackberry application:

    Code Sample 1: HelloApp.java
    import net.rim.device.api.ui.*;
    import net.rim.device.api.ui.component.*;
    import net.rim.device.api.ui.container.*;
    import net.rim.device.api.system.*;
    
    public class HelloApp extends UiApplication {
        public static void main(String argv[]) {
            HelloApp app = new HelloApp();
            app.enterEventDispatcher();
        }
    
        public HelloApp() {
            pushScreen(new HelloScreen());
        }
    }
    
    class HelloScreen extends MainScreen {
        public HelloScreen() {
            super();
            LabelField title = new LabelField
                ("BlackBerry App", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
            setTitle(title);
            add(new RichTextField("Welcome to Developing BlackBerry Apps Tutorial"));
        }
    
        public boolean onClose() {
           Dialog.alert("Visit Again!");
           System.exit(0);
           return true;
        }
    }
    

Once you've entered this code, you can build the project. To compile the source file, perform preverification, and package the application into a .cod file, from the Build menu choose Build all.

Figure 7: Code the Source File (click image for full size)

The JDE will generate FirstApp.jad, FirstApp.jar, and FirstApp.cod, among other files, in the project directory you created earlier.

Now you can run the application in the simulator. In the JDE's Build menu choose Build all and run. The application will appear in the simulator. Just select it, and it will display a welcome message. When you exit, you'll see the message "Visit Again!" as in Figure 8.

Figure 8: Sample run of HelloApp in BlackBerry simulator

To load the application into a real device, use the javaloader command-line tool as I described earlier:

javaloader -usb load FirstApp.cod
 
Deploying Applications Using the BlackBerry Desktop Manager

To deploy the application using the BlackBerry Desktop Manager, you need to generate an .alx file, which is an XML-based BlackBerry application descriptor. Select the project FirstApp, then from the Project menu choose Generate ALX file. The resulting file, FirstApp.alx, looks like this:

<loader version="1.0">

    <application id="FirstApp">

        <name >
        </name>
        <description >

        </description>
        <version >
        </version>

        <vendor >
            MyCompany
        </vendor>

        <copyright >
            Copyright (c) 2005 MyCompany
        </copyright>

        <fileset Java="1.5">
            <directory >
                MyCompany
            </directory>

            <files >
                FirstApp.cod
            </files>
        </fileset>

    </application>

</loader>

 

Now you can use the BlackBerry Desktop Manager and a USB cable to load the .alx file, which contains a reference to the .cod file, into a BlackBerry device. Figure 9 shows the BlackBerry Desktop Manager, and Figure 10 shows the application to be installed:

Figure 9: BlackBerry Desktop Manager

Figure 10: Application to Be Installed

RIM's Extensions to JAD Files

The JDE generated the following JAD file for the FirstApp project:

Manifest-Version: 1.0
MIDlet-Version: 0.0
MIDlet-Jar-Size: 1692
RIM-COD-Module-Dependencies: net_rim_os,net_rim_cldc
MicroEdition-Configuration: CLDC-1.0
MIDlet-Jar-URL: FirstApp.jar
RIM-MIDlet-Flags-1: 0
RIM-COD-Module-Name: FirstApp
MIDlet-Name: FirstApp
RIM-COD-Size: 1496
RIM-COD-Creation-Time: 1107707260
RIM-MIDlet-Position-1: 0
RIM-COD-URL: FirstApp.cod
RIM-MIDlet-NameResourceId-1: 0
MicroEdition-Profile: MIDP-1.0
 

As you can see, this .jad file includes both standard JAD properties and RIM-specific properties. It's a dual-purpose JAD, that supports downloading of MIDlets to BlackBerry devices, and to other devices as well. The properties RIM-COD-URL and MIDlet-Jar-URL ensure that BlackBerry users can download the .cod file, while users of other devices download the .jar.

Some of RIM's JAD properties are required, others are optional. Here are the required properties:

  • RIM-COD-Creation-Time: the time the .cod file was created
  • RIM-COD-Module-Dependencies: a list of modules the .cod file requires
  • RIM-COD-Module-Name: the name of the module contained in the .cod file
  • RIM-COD-SHA1: the SHA1 hash of the .cod file
  • RIM-COD-SIZE: the size of the .cod file, in bytes
  • RIM-COD-URL: the URL from which the .cod file can be downloaded

The optional properties are:

 

  • RIM-Library-Flags: reserved for use by RIM
  • RIM-MIDlet-Flags: reserved for use by RIM
  • RIM-MIDlet-NameResourceBundle: the name of the resource bundle the application depends on
  • RIM-MIDlet-Position: the suggested position of the application icon on the home screen
Deploying BlackBerry Applications Over the Air

You can download both standard MIDlets and BlackBerry-specific applications applications over the air, wirelessly. The provider puts up on a server both a .jad file to describe the application, and either a .cod or a .jar file holding the application itself. To download, you select the .jad file from a browser.

To enable you to download standard MIDlets to a BlackBerry, the Mobile Data Service feature of the BES provides a built-in transcoder that converts .jar files into .cod files. Note that the web server must identify the MIME types for .jad and .cod files, text/vnd.sun.j2me.app-descriptor and application/vnd.rim.cod respectively.

Be aware that you can download a .jar file to a BlackBerry only if the MDS feature is enabled, so it can convert the file to .cod format. If your access to the network is through a WAP gateway, you can download only .cod files.

Conclusion

RIM's BlackBerry handheld devices are becoming quite popular for both data and voice, and wireless carriers all over the world are distributing them. Several BlackBerry devices are Java-enabled, supporting CLDC and MIDP, while also providing API extensions for BlackBerry-specific features. The BlackBerry Java Development Environment enables developers to create CLDC-based, BlackBerry-specific applications that will run only on a BlackBerry, as well as standard MIDlets that will run on any MIDP-enabled device, including those bearing the BlackBerry brand.

This article provided an overview of the BlackBerry architecture, and a tutorial on developing J2ME applications for the BlackBerry. The sample code gave a flavor of the CLDC-based BlackBerry programming style. The article described how to load existing standard MIDlets into a BlackBerry, as well as how to download applications over the air.

For more information
Acknowledgments

Thanks to RIM and Telus Mobility for lending me the devices I used to deploy, run, and test Java applications for this article. Also, special thanks to Roger Riggs of Sun Microsystems, whose feedback helped me improve this article.

About the author

Qusay H. Mahmoud provides Java technology consulting and training services. He has published dozens of Java articles, and is the author of Distributed Programming with Java (Manning Publications, 1999) and Learning Wireless Java (O'Reilly, 2002).



1As used in this document, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
Your email address (no reply is possible without an address):
Sun Privacy Policy

Note: We are not able to respond to all submitted comments.