Learning Path: MIDlet Life Cycle

   
. .
.   Prerequisites .
.
 
 

Java Tutorial

New to Java Programming Centre

Learning Path: Getting Started with MIDP 2.0

 
 
.

. .
.   Resources .
.
 
 

Retrieving MIDlet Attributes

Managing the MIDlet Life-Cycle with a Finite State Machine

Wireless Application Programming: MIDP Programming and Packaging Basics

Wireless Development Tutorial Part 1

 
 
.

. .
.   Related Materials .
.
 
 

JAR File Specification

JSR 30: J2ME Connected Limited Device Configuration (CLDC) 1.0

JSR 118: Mobile Device Information Profile (MIDP) 2.0

Introduction to OTA Application Provisioning

An Overview of JSR 124: J2EE Client Provisioning

 
 
.

. .
.   About MIDlet Life Cycle .
.
 
 

Audience: Beginner and Intermediate
Estimated time: 10 hours

 
 
.

by Richard Marejka
February 2005

Welcome to the MIDlet Life-Cycle Learning Path! Here you'll find a brief introduction to the life-cycle of an application based on the Java 2 Platform, Micro Edition (J2ME), and links you can follow to articles, sample code, and specifications that will give you a solid grounding in this crucial area of J2ME-based development.

The MIDlet Life-Cycle learning path is a bit different from others in format. Many simply state goals and prerequisites briefly, then provide links to the content. This one provides the basic content directly, and along the way furnishes links to other resources.

This learning path will focus on source code. Why? Ultimately in a product life-cycle, someone must actually create an instantiation of a design that was based an architecture that was begotten by an idea. Business cases, designs, and architectures cannot be compiled to run on devices. Someone actually has to produce code that embodies the design, meets high standards of quality, and meets users' needs. This coding task includes crafting a build environment, managing a source base, and serving it all up in a form that allows the the developers to crank out the product in its deliverable form, on demand. Control and repeatability are key elements of software product management.

So where does all this lead? Virtually all source code is layered on top of existing application progamming interfaces (APIs). How well you understand the APIs you consume, and how correctly you use them, directly affect the quality of your product. Merely reading the API specifications isn't enough. Code that reflects a deep understanding of the API, and that demonstrates correct patterns of use, both reinforce the specification and provide idioms that can be directly employed by other developers. The purpose of this learning path is to help you produce that kind of code.

 



Introduction

Understanding the MIDlet life-cycle is fundamental to creating any MIDlet. The life-cycle defines the execution states of a MIDlet – creation, start, pause, and exit – and the valid state transitions. The application management software (AMS) is the software on a device that manages the downloading and life-cycle of MIDlets. The AMS provides the runtime environment for a MIDlet. It enforces security, permissions, and execution states, and provides system classes and scheduling.

JADs and JARs

The basic components of any MIDlet suite you will deliver are the Java Application Descriptor (JAD) file and the Java Archive (JAR) file. Together, these two items are the MIDlet suite.

The JAD file, as the name implies, describes a MIDlet suite. The description includes the name of the MIDlet suite, the location and size of the JAR file, and the configuration and profile requirements. The file may also contain other attributes, defined by the Mobile Information Device Profile (MIDP), by the developer, or both. Attributes beginning with MIDlet- or MicroEdition- are reserved for use by the AMS. The JAD file syntax is similar to that of the java.util.Properties class found in the J2SE environment.

A MIDlet suite on a device is identified by the attribute tuple (MIDlet-Name, MIDlet-Version, MIDlet-Vendor). The JAR file will be installed from the location MIDlet-Jar-URL. The size of the download must agree with the MIDlet-Jar-Size value.

The JAR contains one or more MIDlets, specified in the JAD using the MIDlet-<n> attribute. The syntax is:

MIDlet-
             n :  
             MIDletName , [
             IconPathname] ,  
             ClassName
          
  • n is the MIDlet number, starting at 1 and incremented by 1 for each MIDlet.
  • MIDletName is the user-visible name of the MIDlet.
  • IconPathname is the absolute pathname of a .png image file within the JAR.
  • ClassName is the name of a class that extends javax.microedition.midlet.MIDlet and has a public, zero-argument constructor.


A manifest file is located at /META-INF/MANIFEST.MF within the JAR. The manifest has the same syntax as the JAD file and it may share the same attributes. The rules for attribute location and lookup are described in the technical tip " Retrieving MIDlet Attributes." The manifest is a key component of the MIDP 2.0 signed-MIDlet model. In a signed MIDlet suite, attributes in the JAD must agree with those in the manifest. While you can modify the JAD file attributes easily, you can't modify those in the signed MIDlet without re-signing the MIDlet suite.

In addition to the Java class files and the manifest, the JAR file may contain other resources. These may be images that the MIDlet can load using the javax.microedition.lcdui.Image.createImage(String) method. The application can also use java.lang.Class.getResourceAsStream(String) to access any resource in the JAR file as a java.io.InputStream  – any resource execpt a class file, that is. The String argument that either method expects is a pathname identifying a resource in the JAR file. The definition and rules for pathname use are found in the "Application Resource Files" section of the JSR 118: Mobile Information Device Profile (MIDP) 2.0 specification, on page 36.

The Security Model

The J2ME security model is a scaled-down version of the J2SE model. It has been adapted to work within the contrained resources common among J2ME devices.

The rules are:

  • Class files are verified for interface compliance before inclusion in a JAR file.
  • There is a limited API set: the Connected Limited Device Configuration (CLDC), one or more related profiles, and licensee open classes.
  • Downloading and management of Java applications take place in native code within the Java virtual machine 1. There are no user-defined class loaders.
  • There is no Java Native Interface (JNI), and no user extensions are allowed.
  • System classes cannot be overridden.


The short of it is:

  • You cannot modify the runtime environment.
  • You cannot modify yourself.
  • You cannot escape the runtime environment.


Installation

There are two ways to install a MIDlet suite. The first, called direct, involves some direct connection between the device and the development platform – commonly cable, infrared, or Bluetooth link. In the case of the Nokia 6100, for example, it's a Nokia DKU-5 USB cable and the Nokia PC Suite software, which includes Nokia Application Installer. You develop the MIDlet suite, perhaps test it in an emulator, then install it using the USB cable and Nokia Application Installer. While this method is efficient for testing on your own device, it is hardly suitable for deploying an application to millions of end users.

Over-the-air provisioning (OTA) makes large-scale deployment possible – even easy. A device can install a MIDlet suite from a remote server using the device's built-in browser. Simply entering the URL of the suite's JAD file into the browser address field starts the installation process. In general terms:

  1. The client device sends an HTTP GET request to the server for the given URL.
  2. The server sends an HTTP response with the suite's JAD file as the message body.
  3. The client verifies the HTTP response and extracts the suite's MIDlet-Jar-File and MIDlet-Jar-Size attributes.
  4. The device sends an HTTP GET request for the JAR file.
  5. The server sends an HTTP response with the JAR file as the message body.
  6. The device verifies the message and the JAR file.
  7. The device asks the user to verify installation.


This description omits steps relating to signed MIDlet suites, permissions, and push-registry entries, collapsing them into the "verifies message and JAR file" step. Error handling has also been omitted to simplify presentation.

The success of the installation process depends on correct functioning of the web server and the device's browser. Characteristics of the network between the device and server can affect installation too. One frequent cause of OTA failure is a size limit that network elements impose on the size of the JAR file. Another is specifying incorrect MIME types for JAD and JAR files. The correct MIME type for a JAD file is text/vnd.sun.j2me.app-descriptor and for a JAR file is application/java-archive.

Removal

Here's the easiest part: Because a MIDlet suite is a self-contained entity, deleting it is simple. Most devices allow the user to select a MIDlet suite and choose a Delete option from a menu. At this point the device likely asks for confirmation; a positive response removes the MIDlet suite, including any push-registry entries and record stores created by any MIDlet in the suite.

On a Sony Ericsson T616, for instance, the deletion process looks like this:

  1. Press the joystick button to access the application page.
  2. Using the joystick, scroll to the Entertainment icon and select it.
  3. Select the Games & More item from the list.
  4. Select a MIDlet from the list.
  5. Press the More button.
  6. Select the Delete option from the list.
  7. Select Yes in the Delete confirmation dialog. (The MIDlet is deleted.)
  8. Select OK in the Deleted confirmation dialog.


The Quintessential First Program

Since the days of Kernighan and Ritchie's The C Programming Language (1978), the first program most developers attempt when they begin using a new language or environment is Hello World. The C version contains only a few lines, including the specification of an I/O library, and the output is only a simple greeting, but this venerable program gives you the chance to prove much: that you can write, build, debug (if necessary), and run a program. So developers using Java technology won't be left out, the article " Wireless Development Tutorial Part I" provides a J2ME version of Hello World and instructions on building it.

Execution States

When a MIDlet begins execution, the AMS first calls the zero-argument constructor to create a new instance of the MIDlet. The constructor typically does little or no initialization. The AMS framework provides transitions that you can use as control points for resource management, as you'll soon see. When the constructor returns, the AMS places the MIDlet in the Paused state. To shift the MIDlet to the Active state the AMS calls the midlet.startApp() method.

A transition from the Active state back to the Paused state occurs whenever the AMS calls midlet.pauseApp(). You can think of this method as the inverse of startApp(). The MIDlet is not being terminated, but it should release any resources it obtained in startApp(). The MIDlet may shift from Paused to Active or back any number of times during its execution, each time on a call to startApp() or pauseApp().

These transition methods give you the opportunities you need to manage resources effectively. Typically, you'll use startApp() to allocate record stores, network connections, UI components, and such, and use pauseApp() to release these resources.

public class Mandy extends MIDlet {

    private boolean once = false;

    Mandy() {
    }

    public void startApp() {
        if ( once == false ) {
            once = true;
            // acquire one-time resources
        }
        // acquire "other" resources
    }

    public void pauseApp() {
        // release "other" resources
    }
}

  • UI components are generally regarded as one-time resources.
  • Background threads can be regarded as one-time resources.
  • Timers and Tasks are usually one-time resoruces.
  • Network connections and IO streams are usually not one-time resources.
  • Resources that can be shared between MIDlets are not one-time resources.
stack

The MIDlet may enter the Destroyed state from either Paused or Active, on a call to midlet.destroyApp(). This method releases any resources acquired in the constructor, and saves any state information.

There are a few variations on this Paused/Active/Destroyed theme. First, a MIDlet may voluntarily enter the Paused state by calling midlet.notifyPaused(). In a similar fashion, it may call midlet.notifyDestroyed() to inform the AMS that the MIDlet can now be considered Destroyed. The destroyApp() method is actually called with a boolean argument. If this boolean is true, the MIDlet will be in the Destroyed state when destroyApp() returns. If this boolean is false, however, the MIDlet can request not to enter the Destroyed state by throwing a MIDletStateChangeException. Note that this is only a request to the AMS. Finally, a call to midlet.resumeRequest() will tell the AMS that the MIDlet is interested in entering the Active state. How can a Paused MIDlet make the call to resumeRequest(), you ask? While it's idle in most ways, a MIDlet in the Paused state may handle asynchronous events such as timers and callbacks.

There are still some open questions here, about the interactions between the AMS and the MIDlet. These can be characterized as the why and the when. For example, when is startApp() called, and why is pauseApp() called? The specification is intentionally vague in these areas, allowing implementations to follow the rules while also allowing host runtime environments to vary. By way of an example: Suppose a mobile phone detects an incoming Multimedia Messaging Service (MMS) message. The AMS may pause an executing MIDlet to free up memory needed by the MMS message. If the pause operation doesn't free enough memory, the AMS may then invoke destroyApp() to release more. The indeterminate answers to such questions may not be the ones developers are looking for, but they are as definitive as the specification writers can make them.

Sample Source

Source code available from the Java mobility site comes in two forms: one for online viewing and another for download. The download version is in J2ME Wireless Toolkit application format. The following table also supplies a reference to the article relevant to each sample. If you're using the J2ME Wireless Toolkit, you can begin working with the source files simply by unzipping the archive and moving the applications into the apps subdirectory of your toolkit installation.

Article Online Download
Retrieving MIDlet Attributes MyMidlet.java attributes.zip
Managing the MIDlet Life-Cycle with a Finite State Machine FsmMIDlet.java
FSM.java
fsm.zip
Wireless Application Programming: MIDP Programming and Packaging Basics FirstMIDlet.java
HelloMIDlet.java
getstart.zip
Wireless Development Tutorial, Part I HelloMIDlet.java wtoolkit.zip

Which brings us to the toolkit itself – the J2ME Wireless Toolkit, of course, a state-of-the-art toolbox for developing wireless applications based on MIDP. The current release at this writing, 2.2, supports CLDC 1.0 and 1.1, MIDP 1.0 and 2.0, and seven other J2ME JSRs. The toolkit allows the developer to choose the JSRs that best match the target environment, build JAD and JAR files, and run MIDlets in an emulator before deploying them on target devices. The toolkit is available for download.

Summary

This learning path has described the basics of the MIDlet runtime environment, the AMS, including its security model, available APIs, and execution-state machine. Several sample MIDlets, with related articles, are available in both online and download formats for your further education. Future learning paths will cover such topics as network and resource I/O, user interface, persistent storage (RMS), and a collection of miscellaneous subjects.

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


Back To Top