BUY THIS BOOK
Add to Cart

Print Book $34.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £24.95

What is this?

Looking to Reprint this content?


Wireless Java
Wireless Java Help for New J2ME Developers

By Qusay Mahmoud
Price: $34.95 USD
£24.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Overview of J2ME
This book is about wireless Java programming with the Java 2 Platform, Micro Edition (J2ME). Sun Microsystems, Inc. introduced J2ME at the JavaOne conference in June 1999 as the younger sibling of both the Java 2 Standard Edition (J2SE) and the Java 2 Enterprise Edition (J2EE). At the time, distributed programming was taking the Java developer community by storm, so most of the participants at the show were more interested in what J2EE had to offer. However, over the next two years, developers also realized that there was tremendous value in having small components running Java. Two years later, at the 2001 JavaOne conference, Sun devoted an entire track for individuals seeking to master the once arcane J2ME. Luckily, you don't need to attend JavaOne to learn about J2ME. Instead, this book will help you through the myriad details of understanding J2ME architecture and programming J2ME applications.
In this chapter, we will present an overview of J2ME's primary components, including virtual machines, configurations, and profiles. We'll then present a few short examples of J2ME-enabled applications to whet your appetite and to show you how easy it is to get started with J2ME.
J2ME is a version of Sun Microsystems' Java that is aimed at the consumer and embedded devices market, which includes electronic commodities such as cellular telephones, pagers, Personal Digital Assistants (PDAs), set-top boxes, and other small devices. Since its release, over 600 companies have joined the development effort, including large corporations such as Palm, Nokia, Motorola, and RIM. However, the direction that J2ME travels is not shrouded in secrecy behind closed corporate doors. Instead, development of J2ME is handled through the Java Community Process (JCP), which allows anyone with an Internet connection to get involved.
J2ME provides a complete set of solutions for creating state-of-the-art networked applications for small devices. It also promises to enable device manufacturers, service providers, and application developers to deploy new applications and services to their customers. However, in doing so, it does not sacrifice some of the founding guidelines of Java, which have become increasingly important these days, namely cross-platform compatibility and security.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is J2ME?
J2ME is a version of Sun Microsystems' Java that is aimed at the consumer and embedded devices market, which includes electronic commodities such as cellular telephones, pagers, Personal Digital Assistants (PDAs), set-top boxes, and other small devices. Since its release, over 600 companies have joined the development effort, including large corporations such as Palm, Nokia, Motorola, and RIM. However, the direction that J2ME travels is not shrouded in secrecy behind closed corporate doors. Instead, development of J2ME is handled through the Java Community Process (JCP), which allows anyone with an Internet connection to get involved.
J2ME provides a complete set of solutions for creating state-of-the-art networked applications for small devices. It also promises to enable device manufacturers, service providers, and application developers to deploy new applications and services to their customers. However, in doing so, it does not sacrifice some of the founding guidelines of Java, which have become increasingly important these days, namely cross-platform compatibility and security.
From a high-level view, J2ME defines the following components:
  • A series of Java virtual machines, each for use on different types of small devices, each with different requirements
  • A group of libraries and APIs that can be run under each of the virtual machines; these are known as configurations and profiles
  • Various tools for deployment and device configuration
The first two components make up the J2ME runtime environment . Figure 1-1 provides a relational view of the runtime environment. At its heart is a Java virtual machine, which runs on top of a device's host operating system. Above that is a specific J2ME configuration, which consists of programming libraries that provide basic functionality based on the resource requirements of the device. On top of the configuration are one or more J2ME profiles, which are additional programming libraries that take advantage of kindred functionalities on similar devices.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Downloading the J2ME Wireless Toolkit
Now that you know your way around the J2ME landscape, let's get started with J2ME. However, before we can compile and run any J2ME programs, we need to download and install the J2ME Wireless Toolkit. You can obtain the J2ME Wireless Toolkit at the following URL: http://java.sun.com/products/j2mewtoolkit.
The version that we use in this book is 1.0.3 beta. It is available for the Microsoft Windows 98/ME and 2000 platforms, as well as Linux and Sun Solaris operating systems. The toolkit requires the presence of at least Version 1.3 of the Java Development Kit (JDK) for the host operating environment.
Once you've downloaded the Wireless Toolkit, double-click on it or execute the resulting binary (depending on your platform) to activate the extraction. This will uncompress the files needed to install the Wireless Toolkit. Note that you may be directed to specify an existing JDK installation on your system. If so, choose the latest stable release of the JDK that you currently have on your system. In addition, the distribution may also ask you if you would like to install a version of the toolkit that interfaces with Forte™ for Java. If you would like to develop your J2ME applications in the Forte for Java Integrated Development Environment, choose the corresponding option. Be sure that Forte is already installed on your system before doing so.
In this case, we're going to install the Java Wireless Toolkit on a Windows platform into the directory C:\j2mewtk. After the installation is completed, this directory will contain all the required classes and tools to run the MIDP applications. (If the installation program asks you to run the ktoolbar program, just ignore it for the moment.) However, we need to do a few more things before we can get started with our examples.
First, we need to add the wireless toolkit binaries to your system path. You can do that on Windows with the following command (again, we've assumed that the Java Wireless Toolkit is installed at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Simple Example
The examples that we're going to demonstrate here, and throughout the rest of the book, are called MIDlets. If you've programmed with Java applets or servlets before, then you'll likely recognize the similarities in the "fill-in-the-method" program structure. This first example, HelloMidlet.java, shown in Example 1-1, creates a text box and then prints the archetypal "Hello World" in a text box.
Example 1-1. "Hello World"
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class HelloMidlet extends MIDlet {

    // The display for this MIDlet
    private Display display;
    // TextBox to display text
    TextBox box = null;

    public HelloMidlet(  ) {
    }

    public void startApp(  ) {
        display = Display.getDisplay(this);
        box = new TextBox("Simple Example", "Hello World", 20, 0);
        display.setCurrent(box);
    }

    /**
     * Pause is a no-op since there are no background activities or
     * record stores that need to be closed.
     */
    public void pauseApp(  ) {
    }

    /**
     * Destroy must cleanup everything not handled by the garbage 
     * collector. In this case there is nothing to cleanup.
     */
    public void destroyApp(boolean unconditional) {
    }
}
This MIDlet consists of a public class definition that extends the MIDlet class found in javax.microedition.midlet . This superclass forms the base of all MIDlets in J2ME. Our HelloMidlet class contains a constructor, as well as the startApp() , pauseApp( ) , and destroyApp( ) methods that have been inherited from the MIDlet class. Note that there is no main() method in this program. Instead, the startApp(), pauseApp( ), and destroyApp( ) methods are called by the underlying framework to start up the MIDlet, to pause it, or to destroy it.
Let's start off by compiling our program on the command line. Using the command line is a bit more complex than the KToolbar application that comes with the Wireless Toolkit, so in order to simplify it, be sure that you have entered the additional environment variables shown above. However, there are several steps that we need to perform when compiling J2ME applications, and it's important to see each of the steps as they occur.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: The Connected Limited Device Configuration (CLDC)
The Connected Limited Device Configuration (CLDC) defines a standard, minimum-footprint Java platform for small, resource-constrained devices. As we mentioned in Chapter 1, the CLDC was designed as a lowest common denominator of Java that can be applicable to a wide variety of devices. However, features specific to a certain vertical market, such as cell phones or pagers, are not found in the CLDC but are instead defined in profiles that sit above it. Configurations primarily target devices with similar amounts of memory and processing power.
This leads to a very important point about the CLDC: there are no optional features. Everything that the CLDC provides is usable on the devices that support it. After all, the primary goal of the CLDC is to ensure portability and interoperability between applications running on various kinds of resource-constrained devices, which is the main objective of programming in Java. In this chapter, we discuss the CLDC and its virtual machine, the KVM, in detail.
Let's start off with some specifics. According to the specification, the devices targeted by the CLDC have the following characteristics:
160 KB to 512 KB of total memory
At a minimum, a CLDC device should have 128 KB of non-volatile memory for the Java VM and the CLDC libraries, and at least 32 KB of volatile memory for the VM to use at runtime, independent of any applications.
16-bit or 32-bit processor with at least 25 Mhz speed
These types of processors are pretty typical in today's handheld devices.
Connectivity to some kind of networking
With CLDC, this is often a two-way wireless connection with limited bandwidth.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Examining the CLDC in Detail
Let's start off with some specifics. According to the specification, the devices targeted by the CLDC have the following characteristics:
160 KB to 512 KB of total memory
At a minimum, a CLDC device should have 128 KB of non-volatile memory for the Java VM and the CLDC libraries, and at least 32 KB of volatile memory for the VM to use at runtime, independent of any applications.
16-bit or 32-bit processor with at least 25 Mhz speed
These types of processors are pretty typical in today's handheld devices.
Connectivity to some kind of networking
With CLDC, this is often a two-way wireless connection with limited bandwidth.
Low power consumption
CLDC devices often operate under battery power. Hence, they have very low power consumption.
Devices that fit these characteristics come in all shapes and sizes. Cell phones and pagers immediately come to mind, but one could also install Java on bar code scanners, video and audio equipment, navigation systems, and other wireless devices yet to come. In fact, as the nature of these devices changes, you can expect that the base specifications for the CLDC will change as well.
Given the constraints listed above, the CLDC currently provides the following functionality to its devices:
  • A subset of Java language and virtual machine features
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using the Standalone CLDC and KVM
If you want to experiment with the raw KVM and CLDC classes, you can download the standalone CLDC and KVM. As of this writing, the latest edition of the CLDC itself is version 1.0.2. The CLDC 1.0.2 contains an updated version of the KVM. The KVM code has been rewritten to improve performance and includes a faster bytecode interpreter, better garbage collection, Java-level debugging APIs, preverifier improvements, and several bug fixes. If you wish to download the standalone CLDC and KVM, you can find it at the following address: http://java.sun.com/products/kvm.
Note that this is different than the J2ME Wireless Toolkit that we used in Chapter 1. This distribution does not contain any MIDP classes, nor does it contain a MIDP emulator. Hence, it will only execute programs that adhere to the base CLDC specification and not any MIDP functionality. If you are solely interested in writing applications for the MIDP, you can just read through this section without taking any action.
This distribution contains KVM implementations for Windows, Solaris, and Linux operating systems, as well as the CLDC classes that can be used to compile and run applications. After downloading and uncompressing the distribution, you should have a series of directories, as shown in Table 2-4.
Table 2-4: CLDC/KVM directories
Directory
Description
api
The Java classes and source code for the CLDC
bin
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
CLDC Next Generation
Finally, let's briefly mention the CLDC Next Generation (NG). The CLDC NG is a specification that is currently in development and that aims to define a revised version of the CLDC. The goal of the CLDC NG is to make the CLDC more compliant with the Java language and virtual machine specifications by reintroducing features such as floating-point support and improved error-handling capabilities.
Some other goals of the CLDC NG will be to:
  • Maintain backward compatibility with CLDC 1.0.
  • Maintain small footprint (limit API growth).
  • Continue focus on small, resource-constrained, connected devices.
  • Investigate the possibility of adding a minimal security manager.
Note, however, that not many new APIs will be reintroduced to the CLDC with this revision. Devices that require significantly more complete Java libraries should use the Connected Device Configuration (CDC) instead. You can follow the progress of the CLDC NG at the Java Community Process web site at: http://www.jcp.org/.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: The Mobile InformationDevice Profile (MIDP)
The Mobile Information Device Profile (MIDP) is built on top of the CLDC, and defines an open application development environment for what Sun calls Mobile Information Devices (MIDs). In simpler terms, MIDP is the J2ME profile that is used for wireless devices, such as mobile phones and pagers. This chapter expands on the previous chapter by introducing some of the fundamental concepts of MIDP and offering programming guidelines that are used throughout the remainder of this book.
As we mentioned in Chapter 1, the MIDP is governed by the Java Community Process. The MIDP is JSR 37, which is part of the Java Community Process. Like the CLDC, the MIDP is an ever-changing standard that actively solicits input from corporations and the general programming community. You can find more information on the MIDP at the following URL: http://java.sun.com/products/midp.
Again, let's start off with some specifics. The MIDP standard defines a MID as a device with the following minimum characteristics:
Display
A screen size of at least 96 x 54 pixels with at least a 1-bit display depth
Input
A one-handed keyboard, two-handed keyboard, or touch screen
Memory
32 KB of volatile memory for the Java runtime (heap); 128 KB of non-volatile memory for the MIDP components; and 8 KB of non-volatile memory for application-created persistent data
Networking
A two-way intermittent connection, usually wireless, with limited bandwidth
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Mobile Information Devices
Again, let's start off with some specifics. The MIDP standard defines a MID as a device with the following minimum characteristics:
Display
A screen size of at least 96 x 54 pixels with at least a 1-bit display depth
Input
A one-handed keyboard, two-handed keyboard, or touch screen
Memory
32 KB of volatile memory for the Java runtime (heap); 128 KB of non-volatile memory for the MIDP components; and 8 KB of non-volatile memory for application-created persistent data
Networking
A two-way intermittent connection, usually wireless, with limited bandwidth
Because the MIDP is built on top of the CLDC, it addresses the following areas that are omitted by the CLDC:
Application Life Cycle Management
The MIDP includes the javax.microedition.midlet package, which contains classes and methods for starting, pausing, and destroying applications in the host environment.
User Interface and Events
The MIDP also provides the javax.microedition.lcdui packages, which include classes and interfaces for creating GUI components for applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
More About MIDlets
In Chapter 1, we introduced you to MIDlets, applications that run on MIDP devices. MIDlets are written as one or more Java classes whose objects are compressed into a JAR file. Like Java applets, MIDP applications have an application life cycle while running on a mobile device. Specifically, a MIDlet can be in one of three states:
  • Paused
  • Active
  • Destroyed
Figure 3-1 shows the rules for transitioning between states.
Figure 3-1: MIDlet transition states
Here is a quick rundown of how MIDP applications change state: when a MIDlet is first started, it is placed in the paused state. After it's ready, the controlling software will then place the MIDlet in the active state. At this point, the MIDlet is running and the user can interact with it. The application can be placed back in the paused state by either the MIDP system or the program itself. In addition, the MIDP can be moved to the destroyed state from either the paused or the active state, again by either the MIDP system or the programmer. In the destroyed state, the MIDlet should release all of the resources it currently has back to the MIDP system.
We'll cover this in more detail in the following chapter, where we create and execute a MIDlet with multiple states. In the meantime, this quick introduction brings us to the point where we must first introduce some important concepts.
A MIDlet suite is simply two or more MIDlets that are packaged in a JAR file. MIDlets within the same suite can use the classes and resources contained in the JAR file, much like any standard Java application, the classes of which are loaded by the same class loader.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Working with MIDlets
MIDlets are very simple to implement. All MIDlets must extend the javax.microedition.midlet.MIDlet abstract class and implement certain methods in that class. The MIDlet abstract class provides the basic functionality required in all MIDlets. A MIDlet runs in a controlled environment and therefore must implement certain methods that allow the application manager (which installs and runs the MIDlet) to control the behavior of the MIDlet. These methods are known as life cycle methods, since they reflect various states in which a MIDlet can be.
You'll recall from the previous chapter that a MIDlet can be in one of three states: paused, active, or destroyed. The state chart in Figure 4-1 shows the possible state transitions of a MIDlet, this time with the addition of the methods that the Java Manager will call inside the MIDlet code during those transitions.
Figure 4-1: MIDlet state transitions
Here, the javax.microedition.midlet.MIDlet abstract class defines three life cycle methods that are called during the state transitions: pauseApp(), startApp(), and destroyApp(). These three methods were present in the example we developed in Chapter 1. The responsibilities for these three life cycle methods are as follows.
public void startApp( )
This method indicates that the MIDlet is moving from a paused state to an active state. Here, the MIDlet will typically initialize any objects that are required while the MIDlet is active, and set the current display.
public void pauseApp( )
This method is called when the MIDlet is moving from an active state to a paused state. This means that it will pause any threads that are currently active, as well as optionally setting the next display to be shown when the MIDlet is re-activated. Data can be persisted, if necessary, and retrieved later when the MIDlet is activated again.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Application Manager
The application manager, sometimes called the Application Management System (AMS) or MIDlet management software, is software that is preinstalled on a MIDP device and that functions as an operating environment. For example, on a Motorola i85s, the Java Apps menu item will start the application manager, which immediately shows the Java logo and the words "Mobile Information Device Profile Compatible" and then displays a menu of the MIDlet suites that have been installed on the phone.
However, the application manager must do more than simply show a menu of the MIDlet suites that are installed. According to the MIDP specification, the application manager must be able to:
  • Retrieve a MIDlet suite from somewhere, possibly through a serial connection, infrared connection, or across a wireless connection to the Internet
  • Install a MIDlet suite on the MIDP device
  • Perform version management on MIDlet suites that are installed
  • Launch a MIDlet from a MIDlet suite and provide an operating environment for the KVM, as well as any system, MIDP, and CLDC classes
  • Delete a previously installed MIDlet suite
As a MIDlet programmer, you typically won't need to be concerned with the internals of the application manager running on the device—it's unique to each device. However, some insight into its responsibilities is important when designing MIDP applications. In this case, the MIDlet life cycle methods can be called by the application manager to control the MIDlet state:
  • When the user launches a MIDlet, the application manager creates a new instance of the MIDlet class by calling its zero-argument constructor. This typically performs the one-time initialization. Once this is done, the MIDlet will be placed in a paused state. However, if any exception occurs during the instantiation of the MIDlet class, the application manager will move the class to the destroyed state.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating MIDlets
Now that you're familiar with MIDlet states and the application manager, let's create another MIDlet. As you've probably guessed by now, this involves the following five steps:
  1. Write the MIDlet.
  2. Compile the MIDlet's source code.
  3. Preverify the MIDlet's class file.
  4. Package the application in a JAR file.
  5. Create a JAD file.
Let's review each of these steps. First, we'll look at the command-line technique that was shown in Chapter 1. Then, we'll introduce the KToolbar application, which comes with the J2ME Wireless Toolkit and which can make our lives much easier.
The first step in the development life cycle is to write the MIDlet. Example 4-2 shows a simple MIDlet, PaymentMIDlet. This MIDlet creates a List object of type EXCLUSIVE (that is, only one option can be selected at a time), and adds three methods of payments to it. It displays a list of options for the user to select a method of payment.
Example 4-2. Sample MIDlet
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class PaymentMIDlet extends MIDlet {

    // The display for this MIDlet
    private Display display;

    // List to display payment methods
    List method = null;

    public PaymentMIDlet(  ) {
       method = new List("Method of Payment", 
           Choice.EXCLUSIVE); 
    }

    public void startApp(  ) {
        display = Display.getDisplay(this);
        method.append("Visa", null);
        method.append("MasterCard", null);
        method.append("Amex", null);
        display.setCurrent(method);
    }

    /**
     * Pause is a no-op since there are no background
     * activities or record stores that need to be closed.
     */

    public void pauseApp(  ) {
    }

    /**
     * Destroy must cleanup everything not handled by the 
     * garbage collector. In this case there is nothing to
     * cleanup.
     */

    public void destroyApp(boolean unconditional) {
    }
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: MIDP GUI Programming
User interface requirements for handheld devices are different from those for desktop computers. For example, the display size of handheld devices is smaller, and input devices do not always include pointing tools such as a mouse or pen input. For these reasons, you cannot follow the same user-interface programming guidelines for applications running on handheld devices that you can on desktop computers.
The CLDC itself does not define any GUI functionality. Instead, the official GUI classes for the J2ME are included in profiles such as the MIDP and are defined by the Java Community Process (JCP). You'll note that the GUI classes included in the MIDP are not based on the Abstract Window Toolkit (AWT). That seems like a major issue, which brings us to the following question.
After a great deal of consideration, the MIDP Expert Group decided not to subset the existing AWT and Project Swing classes for the following reasons:
  • AWT is designed for desktop computers and optimized for these machines.
  • AWT assumes certain user interaction models. The component set of the AWT is designed to work with a pointing device such as a mouse; however, many handheld devices, such as cell phones, have only a keypad for user input.
  • AWT has a rich feature set, and includes support for functionality that is not found or is impractical to implement on handheld devices. For example, the AWT has extensive support for window management, such as resizing overlapping windows. However, the limited display size of handheld devices makes resizing a window impractical. Therefore, the window and layout managers within the AWT are not required for handheld devices.
  • When a user interacts with an AWT-based application, event objects are created dynamically. These objects exist only until each associated event is processed by the application or system, at which time the object becomes eligible for garbage collection. The limited CPU and memory of handheld devices, however, cannot handle the burden.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Not Reuse the AWT?
After a great deal of consideration, the MIDP Expert Group decided not to subset the existing AWT and Project Swing classes for the following reasons:
  • AWT is designed for desktop computers and optimized for these machines.
  • AWT assumes certain user interaction models. The component set of the AWT is designed to work with a pointing device such as a mouse; however, many handheld devices, such as cell phones, have only a keypad for user input.
  • AWT has a rich feature set, and includes support for functionality that is not found or is impractical to implement on handheld devices. For example, the AWT has extensive support for window management, such as resizing overlapping windows. However, the limited display size of handheld devices makes resizing a window impractical. Therefore, the window and layout managers within the AWT are not required for handheld devices.
  • When a user interacts with an AWT-based application, event objects are created dynamically. These objects exist only until each associated event is processed by the application or system, at which time the object becomes eligible for garbage collection. The limited CPU and memory of handheld devices, however, cannot handle the burden.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The MIDP GUI APIs
Because of the issues outlined earlier, the MIDP contains its own abbreviated GUI, which is much different from AWT. The MIDP GUI consists of both high-level and low-level APIs, each with their own set of events. This chapter discusses and shows examples of using objects from both the high-level and low-level APIs. Handling events from APIs, however, is deferred to the next chapter.
The high-level API is designed for applications where portability between mobile information devices is important. To achieve portability, the API employs a high-level abstraction and gives you little control over its look and feel. For example, you cannot define the visual appearance (shape, color, or font) of the high-level components. Most interactions with the components are encapsulated by the implementation; the application will not be aware of them. Consequently, the underlying implementation does the necessary adaptation to the device's hardware and native user interface style. Classes that implement the high-level API all inherit the javax.microedition.lcdui.Screen class.
The low-level API provides little abstraction. It is designed for applications that need precise placement and control of graphic elements, as well as access to low-level input events. This API gives the application full control over what is being drawn on the display. The javax.microedition.lcdui.Canvas and javax.microedition.lcdui.Graphics classes implement the low-level API. However, we should point out that MIDlets that access the low-level API are not guaranteed to be portable, because this API provides mechanisms to access details that are specific to a particular device.
Here's how the MIDP GUI model works, in a nutshell. In order to show something on a MIDP device, you'll need to obtain the device's display, which is represented by the javax.microedition.lcdui.Display class. The Display class is the one and only display manager that is instantiated for each active MIDlet and provides methods to retrieve information about the device's display capabilities.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The High-Level MIDP APIs
Now, let's see how the various classes in the high-level API can be used to create GUI components. We will cover two parts of this process: working with screens and the components that subclass them, and working with forms and the components that can be arranged in them.
Having seen an example of a screen, a few questions immediately come to mind: how do you manage screens, how do you navigate through them, and how do you manage the display and the input devices? The answer is that all this functionality is implemented by the Display class, which includes methods for requesting that objects be displayed on the device, and for retrieving properties of the device.

Section 5.3.1.1: Display

A reference to the device's display can be obtained by providing a MIDlet reference to the static getDisplay( ) method.
public static Display getDisplay(MIDlet c);
This is typically done in the startApp( ) method of a MIDlet, as follows:
public class MyMIDlet extends MIDlet {

   Display display = null;

   public MyMIDlet(  ) { // constructor
   }

   public void startApp(  ) {
      display = Display.getDisplay(this);
   }

   // other methods
}
The getDisplay( ) method should be called after the beginning of the MIDlet's startApp( ) method, as shown earlier. It should never be called from the MIDlet's constructor, as per the MIDP specification, as it may not be properly initialized by the application manager at that time.
After you obtain a reference to the device's display, you simply need to create a GUI component to show. Note that all of the GUI components in Figure 5-2 implement the Displayable abstract class. You can pass the GUI component you create to one of Display's two setCurrent( ) methods:
public void setCurrent(Displayable d);
public void setCurrent(Alert alert, Displayable d);
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Low-Level GUI Components
In the high-level API, you have no control of what is displayed on the screen and very little freedom to "play" with the components programmatically. The implementation is responsible for selecting the best approach for the device. Some applications, however, such as games, may need more control over what is drawn on the screen. The MIDP javax.microedition.lcdui package also provides a low-level API for handling such cases.
In order to directly draw lines, text, and shapes on the screen, you must use the Canvas class. The Canvas class provides a blank screen on which a MIDlet can draw. For example, let's draw the string "HelloWorld" on the screen. There's a simple way to do this: subclass the Canvas class, which is an abstract class that extends Displayable, and override the paint( ) method. The resulting class, MyCanvas, is shown in Example 5-1.
The implementation of the paint( ) method uses the drawing capabilities of the javax.microedition.lcdui.Graphics class. In the paint( ) method, the drawing color is set to red, then a rectangle is drawn in the current color. The methods getWidth( ) and getHeight( ) return the width and height of the Canvas, respectively. The next call to setColor( ) sets the drawing color to white; then the string "Hello World!" is drawn in the top left corner of the screen.
Example 5-1. Subclassing Canvas
import javax.microedition.lcdui.*;

public class MyCanvas extends Canvas {
   public void paint(Graphics g) {
      g.setColor(255, 0, 0);
      g.fillRect(0, 0, getWidth(), getHeight(  ));
      g.setColor(255, 255, 255);
      g.drawString("Hello World!", 0, 0, g.TOP | g.LEFT);
   }
}
Now, in order to view the MyCanvas, it must be instantiated and displayed. Since Canvas is a subclass of Displayable, it can be displayed the same way any other screen using the setCurrent( ) method. Example 5-2 shows the resulting MIDlet.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: MIDP Events
In AWT and Swing, events are generated when a user interacts with an application. For example, if the user selects Save from the File menu, the application is notified of this action and responds to the generated event. The same model holds true for the MIDP. However, as mentioned in the previous chapter, there are two MIDP user interface APIs: high-level and low-level. Therefore, there are two kinds of events: high-level (such as selecting an item from a list) and low-level (such as pressing a key on the device).
This chapter discusses event handling in the MIDP and shows, through examples, how to handle high-level and low-level MIDP events generated by the components of the previous chapter. We start with an explanation of a simple application of events: navigating between screens.
A MIDlet developer needs to provide ways for the user to navigate through the different screens that make up the MIDlet. Because we can only show one screen at a time, however, we need to tie a mechanism to each screen that indicates to the MIDlet that the user has completed working with the current Displayable screen. We can do this by using the Command class, which is part of the javax.microedition.lcdui package. Let's take a closer look at the Command class now.
Just like a design pattern with the same name, the Command class encapsulates the semantic information of an action. Note that it only contains information about a command, not the actual functionality that is executed when a command is activated. Here is the constructor of the Command class:
public Command(String label, int commandType, int priority);
This is the only constructor for the Command class. Hence, creating a Command object is extremely simple:
Command infoCommand = new Command("Info", Command.SCREEN, 2);
The Command class constructor takes three parameters, and therefore contains the following three lightweight pieces of information:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Screen Navigation
A MIDlet developer needs to provide ways for the user to navigate through the different screens that make up the MIDlet. Because we can only show one screen at a time, however, we need to tie a mechanism to each screen that indicates to the MIDlet that the user has completed working with the current Displayable screen. We can do this by using the Command class, which is part of the javax.microedition.lcdui package. Let's take a closer look at the Command class now.
Just like a design pattern with the same name, the Command class encapsulates the semantic information of an action. Note that it only contains information about a command, not the actual functionality that is executed when a command is activated. Here is the constructor of the Command class:
public Command(String label, int commandType, int priority);
This is the only constructor for the Command class. Hence, creating a Command object is extremely simple:
Command infoCommand = new Command("Info", Command.SCREEN, 2);
The Command class constructor takes three parameters, and therefore contains the following three lightweight pieces of information: label, command type, and priority.
  • The label is a string used for the visual representation of the command. For example, the label may appear next to a soft button on the device or as an element in a menu.
  • The command type element specifies the command's intent. The predefined types are actually static integers in the Command class: BACK , CANCEL , EXIT , HELP , ITEM , OK , SCREEN , and STOP .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Handling Low-Level Events
If you use the Canvas class to write applications to access low-level input events or to issue graphics calls for drawing to the display, you must handle low-level events. Game applications are likely to use the Canvas class because it provides methods to handle game actions and key events. The key events are reported with respect to keycodes that are directly bound to concrete keys on the device.
The Canvas class, which is a subclass of Displayable, allows the application to register a listener for commands, but it requires applications to subclass the listener first. Also, while screens allow the application to define a listener and register it with an instance of the Screen class, the Canvas class does not allow this, because several listener interfaces need to be created, one for each kind of event.
Every key for which events are reported is assigned a keycode. The MIDP defines the following keycodes in the Canvas class:
KEY_NUM0
The keycode for key 0
KEY_NUM1
The keycode for key 1
KEY_NUM2
The keycode for key 2
KEY_NUM3
The keycode for key 3
KEY_NUM4
The keycode for key 4
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 7: Networking
Way back in Chapter 1, we briefly introduced the CLDC Generic Connection Framework. Let's quickly review why it was necessary to create an entirely new networking library for the CLDC.
The java.io and java.net packages of the J2SE are not suitable for handheld devices with a small memory footprint, for the following reasons:
  • Device manufacturers who work with circuit-switched networks require stream-based connections such as the Transport Control Protocol (TCP), which is a connection-oriented protocol.
  • Device manufacturers working with packet-switched networks require datagram-based connections such as the User Datagram Protocol (UDP), which is a connectionless protocol.
  • Other handheld devices have specific mechanisms for communications.
All this variation makes designing networking facilities for the CLDC quite a challenge. This challenge has led to the design of a set of related abstractions that can be used at the programming level instead of using different abstractions for different forms of communications. For example, the J2SE java.net package provides a set of related abstractions in the form of over 20 networking classes, including Socket, ServerSocket, and DatagramSocket. With the CLDC, however, we need to go a step further to save space.
In the Generic Connection Framework, all connections are created using the static open( ) methods from a single class: javax.microedition.io.Connector . If successful, these methods return an object that implements one of the generic connection interfaces. Figure 7-1 shows how these interfaces form an inheritance hierarchy. The Connection interface (don't confuse Connection with Connector) is the base interface.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generic Connections
In the Generic Connection Framework, all connections are created using the static open( ) methods from a single class: javax.microedition.io.Connector . If successful, these methods return an object that implements one of the generic connection interfaces. Figure 7-1 shows how these interfaces form an inheritance hierarchy. The Connection interface (don't confuse Connection with Connector) is the base interface.
Figure 7-1: Connection interface hierarchy
  • The Connection interface represents the most basic connection type. It can only be opened and closed.
  • The InputConnection interface represents a device from which data can be read. Its openInputStream( ) method returns an input stream for the connection.
  • The OutputConnection interface represents a device to which data can be written. Likewise, its openOutputStream( ) method returns an output stream for the connection.
  • The StreamConnection interface combines the input and output connections.
  • The ContentConnection interface extends the StreamConnection interface. It provides access to some of the basic metadata information provided by HTTP connections.
  • The StreamConnectionNotifier interface waits for a connection to be established. It returns an object that implements the StreamConnection interface, on which a communication link has been established.
  • The DatagramConnection interface is used to represent a datagram endpoint.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
MIDP Connectivity