Java Programming for Wireless devices using J2ME/CLDC/MIDP
Introduction
Connected, shared and personalized information devices such as cell phones, two-way pagers, personal organizers, internet TVs etc., are becoming increasingly important in our day-to-day lives. These devices will be much more customizable and personal than the devices we have today. For eg., the new communication devices such as cell phones and two-way pagers will allow the users to customize them by downloading new services and applications from the Internet.
Such customizability will not be limited to just communication devices such as cell phones or two-way pagers. For example, the future automobile engines would possibly get the new service updates as they become available, electronic would be able to download updated game programs, and so on.
These devices would require a powerful application development platform to support such personalized applications. With the availability of a widely used programming platform such as Java, the development of such applications will become significantly easier.
This whitepaper aims at explaining some of the important concepts in programming the wireless devices using Java and shows you how to write a simple application targeted for the cell phones.
Java 2 Micro Edition (J2ME) Overview
Depending on the targeted computing platform, Sun has grouped the Java technologies into three editions: Java 2 Micro Edition (J2ME), Java 2 Standard Edition (J2SE) and Java 2 Enterprise Edition (J2EE). Each of these editions has been customized specifically for the platform it is targeting, whether it be a consumer device, a desktop computer or an enterprise network server.

Figure 2.1 Java Editions
planners, and IS managers avoid getting lost in the details of Microsoft's many operating systems, tools, technologies, and applications.
The Java 2 Micro Edition consists of the technology, APIs, tools and standards needed to create applications for consumer devices. J2ME specifically targets the consumer space, which covers the range of small commodities such as smart cards and pagers all the way up to the TV set-top boxes. J2ME provides a complete solution for creating dynamically extensible, networked products and applications for the consumer and embedded appliances.
At a high level, J2ME is currently targeted at two categories of products:
- Shared, fixed, connected information devices.Typical examples of devices in this category include TV set-top boxes, Internet TVs, Internet-enabled screenphones, high-end communicators
- Personal, mobile, connected information devices.Cell phones, pagers and personal organizers are examples of devices in this category. These devices have a large range of user interface capabilities, memory availability, processing power and persistent, high-bandwidth network connections.
- In practice, the line between these two categories is defined more by the memory budget, bandwidth considerations, battery power consumption, and physical screen size of the device, rather than by its specific functionality or type of connectivity of these devices.
J2ME Building Blocks: Virtual Machine, Configurations and Profiles
J2ME provides a range of virtual machine technologies optimized for the different processor types and memory footprints commonly found in the consumer and embedded devices.
For resource-constrained devices, J2ME supports minimal configurations of the Java virtual machine and Java APIs that consists of just the essential capabilities of each kind of device. These configurations can be extended with new APIs and VMs as new features are added to these devices and new applications are developed for them by the application vendors
This flexibility and extensibility are supported by J2ME using the following building blocks:
- Java Virtual Machine Layer.This layer is an implementation of a Java Virtual machine that is customized for a particular device's host operating system.
- Configuration Layer.A J2ME configuration defines a minimum platform for a "horizontal" category of devices which has similar memory requirements and processing power. A configuration defines the Java language and virtual machine features and minimum class libraries that a device manufacturer can expect to be available on all devices of the same category.
- Profile Layer.A J2ME device profile is layered on top of a configuration. A profile defines the specific requirements of a certain "vertical" category of devices. The main goal of a profile is to define a standard Java platform for a certain vertical device family and guarantee interoperability within them. Profiles typically include class libraries that are more domain-specific than the class libraries provided in a configuration.
The J2ME architecture currently has two configurations. The Connected Device Configuration technology (CDC) uses the CVM, a full-featured VM that is similar to a virtual machine residing on a desktop system. This configuration is intended for devices with at least a few megabytes of available memory.
For wireless devices and other systems with severely constrained memory environments, J2ME uses the Connected Limited Device Configuration technology (CLDC).
Mobile Information Device Profile (MIDP) is one of the profiles defined in the J2ME architecture which is a set of Java APIs which, together with CLDC provides a complete J2ME application run-time environment targeted at mobile information devices, such as cellular phones and two-way pagers. The MIDP profile address issues such as user interface, persistence storage, networking and application model.
Connected Limited Device Configuration (CLDC)
The configuration for mobile devices or the Connected Limited Device Configuration technology (CLDC technology) defines the Java platforms targeted for small and resource-constrained devices with small memory budgets and low processing power. The CLDC configuration is composed of the K Virtual Machine (KVM) and core class libraries that can be used on a variety of devices such as cell phones, two-way pagers, personal organizers, home appliances, and so on.
CLDC defines a set of Java virtual machines that can run on the categories of targeted devices and support the profiles layered on top of CLDC. The KVM is a particular implementation of a Java virtual machine meeting the CLDC specifications.
The primary goals of CLDC is to define a standard Java platform for small, resource constrained, connected devices and to enable third party application developers to easily create applications and content that can be deployed to those devices.
Mobile Information Device Profile (MIDP)
The Mobile Information Device Profile (MIDP) is a set of Java APIs which, together with the Connected Limited Device Configuration (CLDC), provides a complete J2ME application runtime environment targeted at mobile information devices, such as cellular phones and two-way pagers. The MIDP defines the application architecture for these devices and addresses issues such as user interface, persistence storage and networking.
The MID Profile runtime environment allows to dynamically deploy new applications and services on the end user devices. It is designed to work on top of CLDC and the software and hardware requirements of Mobile Information Devices are in addition to those for the broader range of Connected Limited Devices. The APIs defined by MIDP allows an open application development for Mobile Information Devices.

The primary goals of MIDP are to keep the implementation size minimal - must fit in small "footprint", and efficiency - must run on low-end microprocessors with limited heap size and with minimal creation of garbage.
MIDP Applications (MIDlets) and MIDlet Lifecycle
The applications written for mobile information devices such as cellular phones and pagers are called MIDlets. Like applets, MIDlets are controlled by the software that runs them. In the case of an applet, the underlying software is a browser or the appletviewer tool and in the case of a MIDlet, the underlying software is the cell phone or two-way pager device implementation that supports the CLDC and MIDP. A MIDlet is a well behaved MIDP application which lives within the resouce constraints which runs and terminates when requested.
All the devices which support MIDP are supposed to have a device-specific Application Management Software which takes care of installing, managing and removing MIDlets interactively.
MIDlet lifecycle
MIDlets move through a well defined lifecycle consisting of five phases. It is the task of the Application Management Software to move MIDlets through these phases:
- Retrieval - The AMS retrieves the MIDlet from some source and reads the MIDlet into the device's memory. The medium through which the MIDlet is downloaded depends on the device. It could be through a serial cable, an IRDA port, or a wireless network.
- Installation - Once the MIDlet is downloaded, the AMS installs the the MIDlet on the device. During the installation process, the MIDP implementation verifies that the MIDlet does not violate the device's security policies.
- Launching - A MIDlet is launched when a user selects it using the interface provided in the device. At this point, the MIDlet enters the KVM and the lifecycle methods of the MIDlet are invoked.
- Version Management - The AMS keeps track of all the MIDlets that are installed on the device including their version numbers. This information is used to upgrade a MIDlet to its new version.
- Removal - The AMS removes a MIDlet and cleans up the related resources from the memory.
A MIDlet can be in one of the three states after it is launched by the Application Management Software:
- Paused A MIDlet enters the Paused state once it is created and initialized by the AMS. It can also enter this state when it is Active.
- Active This state means the MIDlet is running normally. A MIDlet goes to the Active state from the paused state if there are no runtime exceptions during its initialization.
- Destroyed This state means the MIDlet has released all its resources and is terminated. A MIDlet can reach this state either from the paused state due to a runtime exception during its initialization or from the active state when the user has chosen to close the application.
Writing a simple MIDP Application
As mentioned in the previous section, MIDlets are small applications written in Java that run in all mobile phones and two-way pagers that support the Mobile Information Device Profile. Currently a certified MIDP reference implementation is available only in Windows, however the CLDC is available for the Solaris and Windows platforms.
To write MIDlets, you have to download and install the following software:
- JDK 1.2 or later (http://java.sun.com/j2se/)
- Connected Limited Device Configuration (CLDC)(http://www.sun.com/software/communitysource/j2me/download.html)
- Mobile Information Device Profile (MIDP)(http://java.sun.com/products/midp/)
Setup the environment variables according the the instructions after you install these softwares.
MIDP defines the following class libraries for application development :
- javax.microedition.midlet - This package contains the classes used to manage the MIDlet's application lifecycle.
- javax.microedition.lcdui - This package contains the user interface classes and interfaces that can be used to program the graphical user interface of a MIDP application.
- javax.microedition.rms - This package contains the elements used for managing persistence of a MIDP application.
- javax.microedition.io
- This package contains the classes and interfaces required for MIDP network programming.
- java.io, java.lang and java.util
- These packages contain the i/o, language and utility classes and the related interfaces.
Development Lifecycle
A MIDlet development cycle consists of the following phases :
Writing the MIDlet code using MIDP APIs
- Compiling and Preverifying the application
- Testing the application
- Packaging the application, and
- Running the packaged application
MIDlet programming is easier than J2SE programming because the MIDP API is simpler and you only need to learn about a few classes before you can start writing your own MIDlets.
Writing the MIDlet code
In this section we will write a simple MIDlet which displays the traditional "HelloWorld" message. We will also implement a command handler and add a command to exit the application.
HelloMIDlet.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
// A MIDlet which displays the "HelloWorld" message.
public class HelloMIDlet extends
MIDlet implements CommandListener
{
private Command exitCommand;
private Display display;
public HelloMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.SCREEN, 1);
}
// Start the MIDlet by creating the TextBox and
// associating the exit command and listener.
public void startApp()
{
TextBox t = new TextBox("HelloMIDlet",
"HelloWorld!!!", 256, 0);
t.addCommand(exitCommand);
t.setCommandListener(this);
display.setCurrent(t);
}
// Pause is a no-op because there are no background
// activities or record stores 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) { }
// Respond to commands. Here we are only implementing
// the exit command. In the exit command, cleanup and
// notify that the MIDlet has been destroyed.
public void commandAction(Command c, Displayable s) {
if (c == exitCommand)
{
destroyApp(false);
notifyDestroyed();
}
}
}
The first two lines import the packages required for MIDP and creating the user interface. In line 5, HelloMIDlet extends the class MIDlet from the package javax.microedition.midlet which allows for the starting, stopping and cleanup of MIDlet. The class also implements the CommandListner interface so that it can listen to command events and properly handle them. In our example we will be listening for a single command to exit the application.
The constructor of the HelloMIDlet (line 10 - 13) initializes the display for the user interface and creates an instance of Command which is used to exit the application. The Command class encapsulates the semantic information of an action. The command itself contains only information about a command, but not the actual action that happens when a command is activated. The action is defined in a CommandListener associated with the screen.
As you can see, a command contains three pieces of information: a label, a type, and a priority. The label (which is a string) is used for the visual representation of the command. The type of the
command specifies its intent. And the priority value describes the importance of this command relative to other commands on the screen. A priority value of 1 indicates the most important command, and higher priority values indicate commands of lesser importance.
When the application is executed, the device chooses the placement of a command based on the type of the command, and places similar commands based on their priorities.
The startApp() (line 17 - 22) function is called by the framework after the MIDlet is launched to allow the MIDlet to initialize itself. In this function, we create an instance of class TextBox which is the main display element of our HelloMIDlet which displays the "HelloWorld" text. We also add a command which displays an "exit" command at the bottom of the display and attach a command listener to the display. Finally, the textbox is made as the current display so that it is shown with the "HelloWorld" text when the application is executed.
The device implementation calls the pauseApp() method to stop the MIDlet temporarily. This method should release shared resources such as threads and connections. This example does not use any shared resources and has no implementation for this method. The framework might ask the MIDlet to continue by calling its startApp() method again.
The function commandAction (lines 36 - 41) is the command handler for the HelloMIDlet. This function is called by the device implementation when the user clicks one of the soft buttons on the device. In this example, we handle the command for exit button and calls the destroyApp() to cleanup the MIDlet resources and user interface and calls the notifyDestroyed() to notify the application management software that the MIDlet has entered the destroyed state. The AMS then releases the resources held by the MIDlet.
Compiling and Preverifying the code
Once the code has been written, the HelloMIDlet.java is compiled using javac command, the same way you would compile any other Java classes
For example, in my windows machine, I compile the MIDlet file as follows:
c:\> javac -classpath c:\\classes HelloMIDlet.java
After compiling the HelloMIDlet.java successfully, you get the HelloMIDlet.class in the same directory.
The next step in the process is the preverification of the compiled class using the Preverify command available in the CLDC distribution. This command preprocesses the HelloMIDlet application for use with the KVM without changing the name of the class. The Preverify command takes a class or a directory of class as input for preprocessing them and creates the new set of classes in an output directory you specify with the command. If you do not specify a target directory, a default directory named output is created in the current directory and all the new classes are placed in this directory.
For example,
c:\> preverify -classpath c:\\classes HelloMIDlet.class
creates output subdirectory and places the preverified HelloMIDlet.class in it. Now you are ready to test the HelloMIDlet.class you created.
Testing the MIDlet
You can test the HelloMIDlet application you created using the midp executable available in the MIDP distribution.
The following line shows you how to invoke the MIDP emulator to test the application you created:
C:\> midp HelloMIDlet

This brings up the MIDP emulator with the HelloMIDlet application running. The figure on the right shows the emulator with the HelloMIDlet running. It displays the "HelloWorld" message in the TextBox display and the "Exit" command at the bottom right portion of the screen. Clicking the soft button below the "Exit" command closes the application and the emulator.
Since the display element we used is a TextBox, you can also type in the text box either using the keyboard or using the numeric keys provided in the emulator. The low level user interface functions handle these keys for the TextBox and displays the corresponding characters.
The method explained above shows how to test your application if it consists of only one MIDlet. If your application consists of more than one MIDlets and if you want to give the user a choice to select the MIDlets from the list, you have to package these MIDlets into an archive file. The next section shows you how to package your applications into a single archive.
Packaging the MIDlet
If an application consists of multiple classes and resources, a JAR file is used to group all the classes together so that the application is easy to distribute and deploy. In my case, I created the JAR file as follows:
c:> jar cf Hello.jar HelloMIDlet.class
The next step in packaging is creating a manifest file (or application descriptor), which provides information about the contents of the JAR file. Manifest properties which start with MIDlet- are passed to the MIDlet when requested. The application descriptor is used by the application management software to manage the MIDlet. It is also used by the MIDlet itself to configure specific attributes. The file extension of the application descriptor must be jad, which stands for Java Application Descriptor.
There is a predefined set of attributes to be used in every application descriptor. For example, the descriptor file for the HelloMIDlet is shown below :Listing 7.2: Hello.jad
MIDlet-Name: HelloMIDlet MIDlet-Version: 1.0.0 MIDlet-Vendor: Calsoft Labs, Inc. MIDlet-Description: A simple MIDlet which shows "HelloWorld" MIDlet-Info-URL: http://www.calsoftlabs.com MIDlet-Jar-URL: Hello.jar MIDlet-Jar-Size: 1074 MicroEdition-Profile: MIDP-1.0 MicroEdition-Configuration: CLDC-1.0 MIDlet-1: HelloWorld,/icon/Hello.png, HelloMIDlet
Almost all of the attributes in the descriptor file are self explanatory. The last attribute "MIDlet-1" defines the properties of the one and only one MIDlet packaged here - HelloMIDlet. This attribute is used to define the name, icon and class properties of the MIDlet.
The name appears in the device display so the MIDlet can be selected from the list of applications deployed in the device, the icon (if one is supplied) appears next to the name, and the class is the executable called to launch the MIDlet. If you are providing an icon for the MIDlet, you have to give it in a PNG (Portable Network Graphics) format which is the graphics format supported by the MIDP.
The attribute name MIDlet-1 indicates this is the first, and in this case only, midlet. Other MIDlets, if any, referenced by this descriptor would be added as MIDLet-2, MIDlet-3, and so on.
Running the packaged MIDlet
Once the application is packaged, we can test it to see if everything works. To test the packaged application, use the -descriptor option of the midp executable as follows, which invokes the emulator and launches HelloMIDlet:
c:> midp -descriptor Hello.jad
Once you have tested your MIDlet in the MIDP emulator, you can deploy it to a web server by uploading the JAR and JAD files to the web server. Once deployed to a web server, your MIDlet is downloadable; however, you must add the following new MIME type to your mime-types configuration file and restart the web server before you can run the MIDlet:
text/vnd.sun.j2me.app-descriptor jad
Use the following command to download and launch the MIDlet:
c:> midp -transient http://hostname/path/Hello.jad
HttpMIDlet
In this section we will modify the previous example (HelloMIDlet) to read the contents to be displayed on the screen, from a web resource using HTTP protocol.
Listing HttpMIDlet.java
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class HttpMIDlet extends MIDlet implements
CommandListener
{
private Command exitCommand;
private Display display;
private String
url = "http://localhost/HelloWorld.txt";
public HttpMIDlet() {
display = Display.getDisplay(this);
exitCommand=new Command("Exit", Command.SCREEN, 1);
}
// Start the MIDlet by creating the
TextBox and reading from the web resource.
public void startApp() {
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
long len = 0;
int ch = 0;
HttpConnection c = (HttpConnection) Connector.open(url);
InputStream is = c.openInputStream();
for (int i = 0 ; i < c.getLength() ; i++ )
if ((ch = is.read()) != -1) b.append((char) ch);
is.close();
c.close();
t= new TextBox("Http Test", b.toString(), 1024, 0);
}
catch (IOException ex)
{
t = new TextBox
("Http Error", "Could not open URL", 1024, 0);
}
t.addCommand(exitCommand);
t.setCommandListener(this);
display.setCurrent(t);
}
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
//Respond to commands. Here we are only implementing
//the exit command. In the exit command, cleanup and
//notify that the MIDlet has been destroyed.
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
The startApp() (Line 18 - 45) function opens an HttpConnection to a URL, reads the contents of a file and displays it in the screen.
Line 27 uses the javax.microedition.io.Connector class to create and open an HttpConnection object. It then gets the InputStream object of the connection by calling the openInputStream() member function of the connection object. The contents of the file are then read into a buffer, which is then displayed onto the text box. Finally, the input stream and the connection objects are closed.
Summary
CLDC and MIDP technologies are in the process of evolution and efforts are being made to provide new tools and libraries to facilitate J2ME application development. Optimizations are being made to the KVM to improve performance and space usage.
MIDP is being supported by a group of around 20 companies in the wireless industry. More and more wireless companies like Motorola, LG and Nokia are coming up with new devices which support MIDP.
References
- http://java.sun.com/j2me/
- http://java.sun.com/products/cldc/
- http://java.sun.com/products/midp/
- Techpaper on WAP Development Services


