Device programming with MIDP, Part 1

The concepts behind MIDP APIs and J2ME to build cross-wireless-platform apps

If you've been following the wireless industry, you've noticed the speed at which a technology runs through its life cycle. A brand new product can become obsolete within months due to an improved technology or platform. The result of that rapid change has been the lack of standardization between the deployment platforms in the wireless world. A development team currently needs its staff to understand numerous markup languages and processes in order to deploy a product onto multiple devices. A marketing department continually needs to modify product direction based on the changing marketplace.

Devices that are compliant with Mobile Information Device Profile (MIDP) will enable vendors to develop applications that can run on multiple wireless platforms without spending intensive amounts of energy customizing or reworking each platform. That would, in turn, let developers focus their energies on the system's functionality.

This article is the first in a three-part series designed to introduce you to the concept of MIDP APIs and the Java 2 Micro Edition (J2ME) platform. I will expose you to the APIs used to generate graphical, form-based, storage-driven code that can connect with external resources.

Introduction to J2ME

The J2ME is Sun Microsystems's attempt to port the Java programming language to devices with resource limitations. A mobile phone, which lacks the computational power, memory, and workstation power, cannot perform the same functionality as high-end servers or client workstations.

The J2ME platform is built upon the Java programming language to provide the maximum functionality available on the resource-limited device. A subset of the base functionality is provided along with some specialized classes.

In this article, I will focus on the CLDC (Connected Limited Device Configuration) and MIDP classes. Those sets of classes make up a profile in the J2ME terminology. That profile is based on the extremely limited device memory, processor speed, battery, and network connectivity bandwidth.

Introduction to CLDC APIs

The CLDC is the base platform on which the MIDP APIs are stacked. The CLDC classes consist of a standardized set of functionality that all vendors who offer J2ME-certified phones will support. Generally, you won't have to interact directly with those classes, but certain devices require that you access those lower-level classes to perform certain functionality. Those low-level accesses will likely be deprecated as the devices and platform develop.

Introduction to the MIDP profile

The MIDP profile has been developed to support the vertical niche of cell phones or similar devices constrained by screen and keypad limitations, in addition to the obvious battery, processor, and bandwidth constraints.

That profile contains a series of APIs that let you create anything from video games using customized graphics to full-scale business applications using external and internal data sources.

Several device manufacturers have already announced that they will support the MIDP platform on their devices. At the time of this writing, Nextel has announced that its phones will support MIDP in the first quarter of 2001.

Quick example

Below is a simple HelloWorld type example that offers a quick overview of a midlet's life cycle. A midlet is the name given for the code that executes on your mobile device. It is similar to an applet in that it contains user interface, data, and control capabilities.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloMidlet extends MIDlet implements CommandListener
{
    // Initialize the Midlet Display variable
    private Display midletDisplay;
    // Initialize a variable for the doneCommand
    private Command doneCommand;
    public HelloMidlet()
    {
      // Retrieve the display from the static display object
      midletDisplay = Display.getDisplay(this);
        // Initialize the doneCommand
      doneCommand = new Command("DONE", Command.SCREEN, 1);
    }
    /**
     * Create the Hello Midlet World TextBox and associate
     * the exit command and listener.
     */
    public void startApp()
    {
        // Create the TextBox containing the "Hello Midlet World!!" message
        TextBox textBox = new TextBox("Hello Midlet", "Hello Midlet World!!", 256, 0);
        // Add the done Command to the TextBox
        textBox.addCommand(doneCommand);
        // Set the command listener for the textbox to the current midlet
        textBox.setCommandListener( (CommandListener) this);
        // Set the current display of the midlet to the textBox screen
        midletDisplay.setCurrent(textBox);
    }
    /**
     * PauseApp is used to suspend background activities and release
     * resources on the device when the midlet is not active.
     */
    public void pauseApp()
    {
    }
    /**
     * DestroyApp is used to stop background activities and release
     * resources on the device when the midlet is at the end of its
     * life cycle.
     */
    public void destroyApp(boolean unconditional)
    {
    }
    /*
     * The commandAction method is implemented by this midlet to
     * satisfy the CommandListener interface and handle the done action.
     */
    public void commandAction(Command command, Displayable screen)
    {
      // If the command is the doneCommand
      if (command == doneCommand)
      {
            // Call the destroyApp method
            destroyApp(false);
            // Notify the midlet platform that the midlet has completed
            notifyDestroyed();
      }
    }
}

This midlet's output is shown in Figure 1, which is a screen capture of the J2ME Windows Toolkit DefaultGrayPhone emulator.

Figure 1. HelloMidlet output

The first two lines import midlet-specific classes to support the MIDlet class, the CommandAction interface, and the user interface (UI) classes. Those classes are present in the MIDP APIs along with a modified subset of the Java programming language. The classes included in the MIDP API will be discussed in more detail later in this article.

public class HelloMidlet extends MIDlet implements CommandListener

This line declares the HelloMidlet class to extend the MIDlet class and implement the CommandListener interface. Each midlet must extend the abstract MIDlet class, which contains three methods, described below, that each midlet must override to complete its life cycle.

Method NameMethod Purpose
startAppTo allocate desired system resources and initialize the application.
pauseAppTo temporarily suspend resource-intensive processes.
destroyAppTo release resources used by the midlet and dispose of the midlet.

In the previous example, the startApp contains the bulk of the functionality because the HelloMidlet does not use other system resources such as network connections or datastores. When the HelloMidlet is executed, the startApp will be called.

As you would expect, the constructor is executed prior to the startApp method. In this example, the constructor retrieves the display from the global Display object. In addition, the constructor initializes the doneCommand.

The startApp method above is used to create the screen to be displayed on the midlet. The following line shows the initialization of the TextBox screen.

TextBox textBox = new TextBox("Hello Midlet", "Hello Midlet World!!", 256, 0);

A midlet Screen may also contain Commands. A command is the mechanism the midlet uses to create menus as shown in the picture above with the "Done" button. Here's the code used to add the "Done" button to the TextBox screen:

      // Add the done Command to the TextBox
      textBox.addCommand(doneCommand);

The Command source will generate CommandActions when it is clicked. In this simple example, the HelloMidlet will implement the CommandListener interface and thereby handle all events itself. As the developed system becomes more complex, handling events in a more expanded manner may be beneficial.

        // Set the command listener for the textbox to the current midlet
        textBox.setCommandListener( (CommandListener) this);

Now that the TextBox has been created, it is ready to be displayed on the device screen. In the following line, I am setting the current display to the newly created TextBox:

      // Set the current display of the midlet to the textBox screen
      midletDisplay.setCurrent(textBox);

The HelloWorld midlet is a simple example that uses only a few of the classes contained in the MIDP platform. In the following section, I will explore a subset of the MIDP API.

Overview of the MIDP/CLDC APIs

Due to the limited nature of the devices upon which the MIDP/CLDC APIs will run, some Java functionality has been removed or modified from the specification. The MIDP/CLDC APIs include the following class libraries:

  • java.lang.*
  • java.io.*
  • java.util.*
  • javax.microedition.io.*
  • javax.microedition.ui.*
  • javax.microedition.rms.*
  • javax.microedition.midlet.*

The java.lang package

Included in the above library is a subset of the standard classes contained in the J2SE java.lang package. One notable exception is the Float class. The MIDP does not support floating-point calculations. Here are the included classes:

  • Object
  • Class
  • Runtime
  • System
  • Thread
  • Runnable
  • Throwable
  • Math
  • String
  • Boolean
  • Short
  • Long
  • Byte
  • Character
  • Integer
  • StringBuffer

The java.io package

The java.io package contains methods needed to retrieve information from remote systems. The following classes are included in the CLDC API:

  • InputStream
  • OutputStream
  • Reader
  • Writer
  • DataInput
  • DataOutput
  • DataInputStream
  • DataOutputStream
  • ByteArrayInputStream
  • ByteArrayOutputStream
  • InputStreamReader
  • OutputStreamReader
  • PrintStream

The java.util package

The java.util package contains a small subset of the original util package. It contains only the following classes:

  • Calendar
  • Date
  • TimeZone
  • Enumeration
  • Vector
  • Stack
  • Hashtable
  • Random

The javax.microedition.io package

The main object in the javax.microedition.io package is the Connector class. You can cast that class into different connection types, described below, using the connection interface.

Connection InterfacePurpose of Connection
StreamConnectionTo open a basic connection that reads/writes simple data.
ContentConnection

To open a connection that provides content length, type,

and encoding information. This interface extends from the

StreamConnection

interface.

HttpConnection

To open a connection that provides capabilities to

interface through HTTP including getting/setting headers

and HTTP-specific handling. This interface extends

from the

ContentConnection

interface.

The Connector open() method has the following general form:

Connector.open("<protocol>:<path>;<parameters>");

The javax.microedition.ui package

The javax.microedition.ui package contains the classes that you can use to define your midlet's user interface. The APIs offer two major choices of UI design.

The Canvas, used in a following example, is used to construct a custom UI using the Graphics object. Using Canvas, you can design multithreaded video games or nontraditional user interfaces.

The Screen object and subclasses, used in the HelloMidlet quick example earlier, are used to construct form-based user interfaces. I will discuss the capabilities of those UI classes in Part 2, or you can obtain them through the Javadoc.

The javax.microedition.rms package

The javax.microedition.rms package contains the classes needed to implement a temporary storage database on the device. That database is limited in its capabilities to store and retrieve information due to the device's size restrictions.

I will explore the database APIs in Part 2 of this series.

The javax.microedition.midlet package

The javax.microedition.midlet package contains the MIDlet class. The MIDlet class executes the midlet life cycle and provides the getAppProperty(key) method to retrieve information from the application properties set in the jad file.

Getting started

Having completed the above example and explanation of the MIDP platform's power, I'll step through the process of installing the MIDP environment. In addition, I will explore the process of building and deploying the midlet classes.

Installation

A newly introduced toolkit from Sun has simplified the development of midlets. The Java 2 Micro Edition Wireless Toolkit (see J2MEWTK) provides a comprehensive toolset for midlet development.

Currently, two limitations exist in that toolkit's installation. First, it will only run in the Windows environment. Sun will likely announce Solaris and Linux versions of the toolkit in the near future. Second, the installation directory name must not contain any spaces due to the internal build process used by the tool.

After downloading the toolkit, you simply double-click on the application to execute it. Several prompts will let you specify the installation location. The J2MEWTK allows integration with the Forte development environment, also available from Sun. To install the Forte extensions to the toolkit, you select custom installation when prompted to choose between custom and typical.

The following directory structure is created in your installation directory. Please note, as mentioned above, that if the directory name includes a space, the preverification process will not run correctly.

1 2 3 Page
Recommended
Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more