Professional Documents
Culture Documents
Syllabus:
Module 1 - Overview of the J2ME Module 6 - Managing Data on the
Architecture Device
J2ME (Java 2 Micro Edition) is an advanced technology in Java, developed with the help
of Java Community Process Program.
J2ME is a reduced version of the Java API and Java Virtual Machine that is designed to
operate within the limited resources available in the embedded computers and
microcomputers.
A key benefit of using J2ME is compatibility with all Java-enabled devices. Motorola,
Nokia, Panasonic all have Java-enabled devices.A J2ME application is a balance between
local and server-side processing.
The Java Community Process Program used a two approaches to addressing the needs of
small computing devices.
Configurations: It is the Java run-time environment and core classes that operate on each device. A configuration
defines the Java Virtual Machine for a particular small computing device. There are two configurations.
o CLDC for handheld devices:The CLDC (Connected Limited Device Configuration) is designed for
16-bit or 32-bit small computing devices with limited memory. These devices usually have between
160KB and 512KB of available memory. Usually these are powered by battery. They use small-
bandwidth network wireless connection. These devices uses a stripped-down version of the JVM the
KJava Virtual Machine (KVM). These devices include pagers, personal digital assistants, cell
phones, dedicated terminals, and handheld consumer device.
o CDC for plug-in devices:CDC(Connected Device Configuration) devices use a 32-bit architecture,
have at least 2 MB of memory available, and implement a complete functional JVM. CDC devices
include digital set-top boxes, home appliances, navigation systems, point-of-sale terminals, and
smart phones.
Profiles: It is defined for categories of small computing devices. A profile consists of classes that enable
developers to implement features found on a related group of small computing devices.List of J2ME Profiles:
What is J2ME? Cut away the hype and the excess fat and you are left with yet another (set of) Java APIs. Since these APIs
cannot run on a traditional Java Virtual Machine (JVM), due to the limited size of mobile devices in regards to memory and
resource availability, J2ME defines a limited version of the JVM as well. In a nutshell:
J2ME combines a resource constrained JVM and a set of Java APIs for developing applications for mobile devices.
Do you, as a developer, have to install this JVM and the APIs on mobile devices? No. Device manufacturers install and
prepackage their devices with this JVM (and associated APIs). As a developer, you only need to develop applications
targeting these devices and install them. Easier said than done!
��.1a configuration,
��.2profile, and
��.3optional packages.
A configuration contains the JVM (not the traditional JVM, but the cut-down version) and some class libraries;
Aprofile builds on top of these base class libraries by providing a useful set of APIs;
And optional packages, are well, an optional set of APIs that you may or may not use when creating your applications.
Optional packages are traditionally not packaged by the device manufacturers, and you have to package and distribute them
with your application. The configuration and profile are supplied by the device manufacturers and they embedded them in
the devices.
The most popular profile and configuration that Sun provides are the Mobile Information
Device Profile (MIDP) and Connected Limited Device Configuration (CLDC).
As the name suggests, CLDC is for devices with limited configurations; for example, devices
that have only 128 to 512KB of memory available for Java applications. Consequently, the JVM
that it provides is very limited and supports only a small number of traditional Java classes.
(This limited JVM is actually called the KVM.)
Its counterpart, the Connected Device Configuration (CDC) is for devices with at least 2MB
of memory available and supports a more feature-rich JVM (but still not a standard JVM).
The MID profile complements the CLDC configuration very well because it minimizes both the
memory and power required for limited devices. It provides the basic API that is used for
creating application for these devices. For example, it provides the
javax.microedition.lcdui package that allows us to create the GUI elements that
can be shown on a (limited) device running the MID profile on top of a CLDC configuration.
Note that MIDP cannot be used with CDC devices. CDC devices get their own set of
profiles, like the Foundation and Personal profiles. However, I will not cover these profiles or
the CDC here, and will concentrate on using MIDP and CLDC only.
The latest versions of MIDP and CLDC are 2.0 and 1.1.
J2ME Architecture
There are 5 layers in J2ME Architecture.Those are:
MIDP (TopMost Layer): Which contains Java APIs for user network connections, persistence storage, and the
user interface. It also has access to CLDC libraries and MIDP libraries.
J2ME API’s(Profiles): Which consists of the minimum set of application programming interfaces for the small
computing device
Configurations: Which handles interactions between the profile and the JVM.
JVM
Midlets.
A MIDlet is a J2ME application which operate on an MIDP. A MIDlet is defined with at least a
single class that is derived from the javax.microedition.midlet.MIDlet abstract class.
Common programming is grouping related MIDlets into a MIDlet suite, which is contained
within the same package and implemented simultaneously. All MIDlets within a MIDlet suite
are considered a group and must be installed and uninstalled as a group. MIDlets from the same
MIDlet suite run the same class. Benefit of the relationship among MIDlet suite members is that
they share the same data.
A MIDlet is an event-based application. All routines executed in the MIDlet are invoked in
response to an event reported to the MIDlet by the application manager. The initial event that
occurs is when the MIDlet is started and the application manager invokes the startApp() method.
The startApp() method in a typical MIDlet contains a statement that displays a screen of data and
prompts the user to enter a selection from among one or more options. The nature and number of
options is, MIDlet and screen dependent. A Command object is used to present a user with a
selection of options to choose from when a screen is displayed. Each screen must have a
CommandListener. A CommandListener monitors user events with a screen and causes the
appropriate code to execute based on the current event.
Here we dicuss about Application Manager Responsibilities which is running on the device
which is provided by the Device manufacturer:
JAR Files
Nine attributes are defined in this file.The first six attributes are necessary.
The file’s extension is changed to .mf when the MIDlet is prepared for deployment.
All entries are name:value pairs.
Each pair must be terminated with a carriage return.
Whitespace between the colon and the attribute value is ignored.
JAD Files
JAD Files are used to pass parameters to a MIDlet without modifying the JAR file . Also
used to provide the application manager with additional content information about the JAR file to
determine whether the MIDlet suite can be implemented on the device. There are five necessary
attributes for a JAD file:
Programs:
A MIDlet is a class that extends the MIDlet class and is the interface between application
statements and the run-time environment , which is controlled by the application manager
. A MIDlet class must contain three abstract methods that are called by the application
manager to manage the life cycle of the MIDlet. These abstract methods are.
startApp(): called by the application manager when the MIDlet is started and contains statements that are
executed each time the application begins execution. Public and have no return value nor parameter list.
pauseApp(): called before the application manager temporarily stops the MIDlet. The application manager
restarts the MIDlet by recalling the startApp() method. Public and have no return value nor parameter list.
destroyApp(): called prior to the termination of the MIDlet by the application manager. Public method without a
return value. It has a boolean parameter that is set to true if the termination of the MIDlet is unconditional, and
false if the MIDlet can throw a MIDletStateChangeException.
MIDP API classes are used by the MIDlet to interact with the user and handle data management.
User interactions are managed by user interface MIDP API classes. These APIs prompt the
user to respond with an appropriate command. The command causes the MIDlet to execute
one of three routines:
Perform a computation.
The data-handling MIDP API classes enable the developer to perform four kinds of data
routines:
Floating-point math is missing in J2ME. MIDlet cannot use any floating-point data types or calculations.
JVM for small computing devices requires a custom class loader that is supplied by the device manufacturer and
cannot be replaced or modified.
We cannot group threads. All threads are handled at the object level.
The class file verification is replaced with two processes called Preverificaton and Validation. Preverification
occurs prior to loading the MIDLet’s and Validation occurs after loading the MIDLet.
Some J2SE applications require classes that are not available in J2ME.
Java applications won’t run in the J2ME environment without requiring modification to the code.
Devices that use the CDC configuration use the full Java Virtual Machine implementation, while devices that
use the CLDC configuration use the Kjava Virtual Machine implementation.
MIDlets are controlled by application management software (AMS). So we cant invoke a MIDLET like a J2SE
Application.
The KVM and CVM:
These are the names of Java virtual machines for the CLDC (KVM) and the CDC
(CVM).
It should be noted, however, that the CLDC and CDC specifications do not require the use
of the KVM or the CVM, only the use of a VM that adheres to the requirements of the
specification in question.
While many device manufacturers license the KVM or CVM from Sun Microsystems to
serve as the core of their J2ME implementation, they are not required for J2ME compliance.
It is a mistake, therefore, to consider the CLDC and KVM as synonymous, and similarly for
the CDC and the CVM
Click Next.
For this application, choose Default Color Phone, CLDC-1.0, and MIDP-1.0 options.
Click Finish.
Understanding the Process of MIDlet Creation--Using the Toolkit:
In the section Acquiring and Installing J2ME Development Kit above, you downloaded the Toolkit and
installed it in the folder C:\WTK22 (as far as this article series is concerned; you may have downloaded
and installed it in a different folder). Let's explore the contents of this folder.
Note that the default installation of the Toolkit would not have created the article folder, and that you
created it in the previous section.
As far as a MIDlet developer is concerned, the most important folders are the apps and bin folders, but
here is a short summary of each of these folders.
Folder
Folder Description
Name
Directory that acts as a simulation for mobile
appdb
device file system
MIDlets created using the Toolkit reside in this
apps
directory
Contains executables for the various tools,
bin including the Toolkit itself, and various other
tools like the preverifier and the emulator
The Wireless Toolkit documentation including
docs
API documentation for MIDP 2.0 and MIDP 1.1
Contains the JAR files for MIDP (both 2.0 and
lib 1.1), CLDC (both 1.1 and 1.0) and several other
optional libraries
Directory where network and profiling sessions
sessions
are maintained
Contains the libraries for the Toolkit itself,
wtklib including the properties of various device
emulators
The apps folder is the directory where all the MIDlets that are created using the Toolkit are installed.
Browse this folder, and you will notice several example MIDlets provided in their own folders. These
have their own directory structure that allows clean separation of source code, libraries, and rest of the
files associated with a MIDlet project.
The bin folder contains the executables for the Toolkit. The most important one is ktoolbar.exe
(on Windows), which starts the main interface window for the Toolkit. This folder contains other
executables as well, some of which we came across earlier (for example, preverify.exe and
emulator.exe). Let us, however, concentrate on using the Toolkit now by running the
ktoolbar.exe from the bin folder.
Mobile devices, whether emulators or real, interact with a MIDlet using their own software,
which is called Application Management Software (AMS). The AMS is responsible for initializing,
starting, pausing, resuming, and destroying a MIDlet. (Besides these services, AMS may be
responsible for installing and removing a MIDlet, as well.) To facilitate this management, a MIDlet can
be in one of three states which is controlled via the MIDlet class methods, that every MIDlet extends
and overrides. These states are active, paused and destroyed.
Pause State:
An installed MIDlet is put into a paused state by the AMS creating an instance of it, by calling
its no-args constructor. This is of course, not the only way that the MIDlet can be in a paused
state. It can enter this state when the AMS calls the pauseApp() method on an active MIDlet
(and the method returns successfully).
It can also enter this state when the MIDlet pauses itself by calling the notifyPaused()
method, as opposed to the pauseApp() method, which is called by the AMS. However, what
exactly is happening with the MIDlet in the paused state?
In a paused state, the MIDlet is waiting for a chance to get into the active state.
Theoretically, in this state, it should not be holding or using any of the device resources
and should be passive in nature. Once the MIDlet is created, this is the state to be in
before becoming active. Also, entering the paused state is necessary when the device
requires it to consume fewer resources, because these resources may be required for
handling other device functions, like handling an incoming call. This is when the device
invokes the pauseApp() method through the AMS. If the MIDlet should inform the AMS
that it has paused, it should invoke the notifyPaused() method, which tells the AMS that
the MIDlet has indeed paused.
One final way in which a MIDlet can get into a paused state is when the MIDlet's
startApp() method, which is called when the AMS invokes it to start the MIDlet (either the
first time or from a paused state), throws a MIDletStateChangeException. Essentially,
in case of an error, the MIDlet takes the safe road of staying in the paused state.
Active State:
The active state is where every MIDlet wants to be! This is when the MIDlet can do its
functions, hold the device resources and generally, do what it is supposed to do.
As said previously, a MIDlet is in an active state when the AMS calls the startApp()
method on a paused MIDlet (actually, the MIDlet enters the active state just before this method
is called by the AMS).
A paused MIDlet can request to go into the active state by calling the method
resumeRequest(), which informs the AMS that the MIDlet wishes to become active.
The AMS may of course, choose to ignore this request or, alternatively, queue it if there are
other MIDlets requesting the same.
Destroy State:
The destroyed state is entered when a MIDlet's destroyApp(boolean
unconditional) method is called and returns successfully, either from an active or paused
state.
This method is called by the AMS when it feels that there is no need for the MIDlet to keep
running and is the place the MIDlet may perform cleanup and other last minute activities.
The MIDlet can enter this state itself, by calling the notifyDestroyed() method, which
informs the AMS that the MIDlet has cleaned up its resources and is eligible for destruction. Of
course, since in this case, the destroyApp(boolean unconditional) method is not
called by the AMS, any last-minute activities must be done before this method is invoked.
However, if this flag is false, effectively, the AMS is telling the MIDlet that it wants the
MIDlet to be destroyed, but if the MIDlet is doing something important, it can raise a
MIDletStateChangeException, and the AMS will not destroy it just yet.
However, note that even then, there are no guarantees that the MIDlet will not be destroyed, and
it remains up to each device to decide how they should handle the request. If the device does
honor the MIDlet's request, it may try and invoke the destroyApp(boolean
unconditional) at a later stage.
Note :
A destroyed state means that the MIDlet instance has been destroyed, but not uninstalled
from the device.
The MIDlet remains installed in the device, and a new instance of it may be created later.
MIDlets can be pure background applications or applications interacting with the user.
Interactive applications can get access to the display by obtaining an instance of the Display
class.
A MIDlet can get its Display instance by calling Display.getDisplay (MIDlet midlet), where
the MIDlet itself is given as parameter.
The Display class and all other user interface classes of MIDP are located in the package
javax.microedition.lcdui.
The Display class provides a setCurrent() method that sets the current display content of the
MIDlet.
The actual device screen is not required to reflect the MIDlet display immediately—the
setCurrent() method just influences the internal state of the MIDlet display and notifies the
application manager that the MIDlet would like to have the given Displayable object displayed.
The difference between Display and Displayable is that the Display class represents the
display hardware, whereas Displayable is something that can be shown on the display.
The MIDlet can call the isShown() method of Displayable in order to determine whether
the content is really shown on the screen.
The MIDP user interface API is divided into a high- and low-level API.
The high-level API provides input elements such as text fields, choices, and gauges. In
contrast to the AWT, the high-level components cannot be positioned or nested freely.
There are only two fixed levels: Screens and Items. The Items can be placed in a Form,
which is a specialized Screen.
The high-level Screens and the low-level class Canvas have the common base class
Displayable.
All subclasses of Displayable fill the whole screen of the device. Subclasses of Displayable can
be shown on the device using the setCurrent() method of the Display object.
The display hardware of a MIDlet can be accessed by calling the static method getDisplay(),
where the MIDlet itself is given as parameter.
High-Level API:
Alerts:
Furthermore, it is possible to set a period of time the Alert will be displayed before another
Screen is shown.
If the Alert does not fit on the screen and scrolling is necessary to view it entire contents, the
time limit is disabled automatically.
A Form can hold any number of Items such as StringItems, TextFields, and ChoiceGroups.
The Item class itself is an abstract base class that cannot be instantiated.
The label is optional, and a null value indicates that the item does not have a label.
Item Description
ChoiceGroup Enables the selection of elements in group.
DateField Used for editing date and time information.
Gauge Displays a bar graph for integer values.
ImageItem Used to control the layout of an Image.
StringItem Used for read-only text elements.
TextField Holds a single-line input field.
StringItem:
StringItems are simple read-only text elements that are initialized with the label and a text
String parameter only.
After creation, the label is added to the main form in the constructor of the HelloMidp
application:
public HelloMidp () {
mainForm = new Form ("HelloMidp");
StringItem versionItem = new StringItem ("Version: ", "1.0");
mainForm.append (versionItem);
}
The label of the StringItem can be accessed using the setLabel() and getLabel() methods
inherited from Item.
To access the text, you can use the methods setText() and getText().
ImageItem:
In addition to the label, the ImageItem constructor takes an Image object, a layout
parameter, and an alternative text string that is displayed when the device is not able to
display the image.
All images loaded from the MIDlet suite's JAR file are not mutable.
Constant Value
LAYOUT_CENTER The image is centered horizontally.
LAYOUT_DEFAULT A device-dependent default formatting is applied to
the image.
LAYOUT_LEFT The image is left-aligned.
LAYOUT_NEWLINE_AFTER A new line will be started after the image is drawn.
LAYOUT_NEWLINE_BEFORE A new line will be started before the image is drawn.
LAYOUT_RIGHT The image is aligned to the right.
public HelloMidp () {
display = Display.getDisplay (this);
mainForm = new Form ("HelloMidp");
try {
ImageItem logo = new ImageItem
("Copyright: ", Image.createImage ("/mcp.png"),
ImageItem.LAYOUT_CENTER | ImageItem.LAYOUT_NEWLINE_BEFORE
| ImageItem.LAYOUT_NEWLINE_AFTER, "Macmillian USA");
mainForm.append (logo);
}
catch (IOException e) {
mainForm.append (new StringItem
("Copyright", "Sams Publishing; Image not available:" + e));
}
}
TextFields:
The constructor of TextField takes four values: a label, initial text, a maximum text size,
and constraints that indicate the type of input allowed.
In addition to avoiding input of illegal characters, the constraints may also influence the
keyboard mode.
Several MIDP devices have a numeric keyboard only, and the constraints allow the
application manager to switch the key assignments accordingly.
Constant Value
ANY Allows any text to be added.
EMAILADDR Adds a valid e-mail address, for instance
myemail@mydomain.com.
NUMERIC Allows integer values.
PASSWORD Lets the user enter a password, where the entered text is masked.
PHONENUMBER Lets the user enter a phone number.
URL Allows a valid URL.
ChoiceGroups:
The ChoiceGroup is an MIDP UI widget enabling the user to choose between different elements
in a Form.
These elements consist of simple Strings, but can display an optional image per element as
well.
ChoiceGroups can be of two different types. Corresponding type constants are defined in the
Choice interface.
These constants are used in the List class as well; the List class allows an additional third type.
Constant Value
EXCLUSIV Specifies a ChoiceGroup or List having only one element selected at the
E same time.
IMPLICIT Valid for Lists only. It lets the List send Commands to indicate state
changes.
MULTIPLE In contrast to EXPLICIT, MULTIPLE allows the selection of multiple
elements.
Additionally, a String array and an Image array containing the elements can be passed to the
constructor.
In both cases, the image parameter may be null if no images are desired.
Using Commands:
The lcdui package does not provide buttons or menus, but an abstraction called
Command.
Commands can be added to all classes derived from the Displayable class.
These classes are Screen and its subclasses such as Form, List, and TextBox for
the high-level API and Canvas for the low-level API.
Constant Value
Command.BACK Used for navigation commands that are used to return the user
to the previous Screen.
Command.CANCEL Needed to notify the screen that a negative answer occurred.
Command.EXIT Used to specify a Command for exiting the application.
Command.HELP Passed when the application requests a help screen.
Command.ITEM A command type to tell the application that it is appended to an
explicit item on the screen.
Command.OK Needed to notify the screen that a positive answer occurred.
Command.SCREEN A type that specifies a screen-specific Command of the
application.
Command.STOP Interrupts a procedure that is currently running.
The Command constructor takes the label, the command type and the priority as
input.
The Command class provides read() methods for all these fields, but it is not possible to
change the parameters after creation.
Using the addCommand() method, commands can be added to a Form or any other
subclass of Displayable.
The lcdui package contains the interface CommandListener, for detecting command
actions.
The commandAction() callback method provides the Displayable class where the command
was issued and the corresponding Command object as parameters.
Gauge:
If a Gauge is interactive, the user is allowed to change the value using a device-dependent
input method. Changes to the gauge value will cause ItemEvents if a corresponding
listener is registered to the form.
The current value of the Gauge can be set using the method setValue() and read using the
method getValue().
Analogous setMaxValue() and getMaxValue() methods let you access the maximum value
of the Gauge.
DateField:
The DateField is a specialized widget for entering date and time information in a simple
way.
The appearance of the DateField is specified using three possible input mode constants in
the constructor.
Constant Value
DATE Passed if the DateField should be used for entering a date only.
DATE_TIME Used for creating a DateField to enter both date and time information.
TIME Used to enter time information only.
The DateField has two constructors in which a label and the mode can be specified.
Lower-Level API:
The lower level aPI composed of two classes.I. Canvas II. Graphics
Canvas class is a abstract class so we need to extend and provide the implementation for
paint(Graphics g) methood.
The Canvas and Graphics classes work together to provide low-level control over a device.
The class MyCanvas extends Canvas and overrides the paint() method.
The paint() method is called as soon as the canvas is made the current displayable element
(by setCurrent(myCanvas))
The paint() method accepts a Graphics object, which provides methods for drawing 2D
objects on the device screen.
The Canvas class provides methods to interact with the user, including predefined game
actions, key events, and, if a pointing device is present, pointer events.
You can even attach high-level commands to a canvas, similar to attaching commands on a
high-level UI element.
Each Canvas class automatically receives key events through the invocation of the
keyPressed(int keyCode), keyReleased(int keyCode), and
keyRepeated(int keyCode).
The default implementations of these methods are empty, but not abstract, which allows
you to only override the methods that you are interested in.
Similar to the key events, if a pointing device is present, pointer events are sent to the
pointerDragged(int x, int y), pointerPressed(int x, int y), and
pointerReleased(int x, int y) methods
The Canvas class defines constants for key codes that are guaranteed to be present in all
wireless devices.
These key codes define all of the numbers (for example, KEY_NUM0, KEY_NUM1,
KEY_NUM2, and so on) and the star (*) and pound (#) keys (KEY_STAR and KEY_POUND).
This class makes it even easier to capture gaming events by defining some basic gaming
constants.
There are nine constants that are relevant to most games: UP, DOWN, LEFT, RIGHT, FIRE,
GAME_A, GAME_B, GAME_C, and GAME_D.