0% found this document useful (0 votes)
63 views

Programming Mobile Devices With J2ME: Claude Fuhrer

The document provides an introduction to programming mobile devices with J2ME (Java Platform, Micro Edition). It discusses the key components of J2ME including profiles, configurations, and Java virtual machines. It focuses on the Connected Limited Device Configuration (CLDC), which defines specifications for memory and processing constraints for small consumer and embedded devices. The CLDC uses the Kilo Virtual Machine, a stripped down version of the Java virtual machine that removes more resource intensive features like floating point support and reflection.

Uploaded by

kafu46
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Programming Mobile Devices With J2ME: Claude Fuhrer

The document provides an introduction to programming mobile devices with J2ME (Java Platform, Micro Edition). It discusses the key components of J2ME including profiles, configurations, and Java virtual machines. It focuses on the Connected Limited Device Configuration (CLDC), which defines specifications for memory and processing constraints for small consumer and embedded devices. The CLDC uses the Kilo Virtual Machine, a stripped down version of the Java virtual machine that removes more resource intensive features like floating point support and reflection.

Uploaded by

kafu46
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction The Connected Limited Device Configuration

Programming mobile devices with J2ME


Part I
Claude Fuhrer Introduction
Bern University of Applied Sciences
School of Engineering and Information Technology

October 2010

Programming mobile devices with J2ME Programming mobile devices with J2ME
1 Introduction - Introduction 2
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

A high-level overview J2ME architecture

Profiles

From a high level view, J2ME defines the following


components :
Configurations
1 A series of virtual machines, each for use on different types of
small devices.
2 A group of libraries and API’s that can be run under the Java Virtual Machines
virtual machines;
3 Various tools for the deployment of applications and the
devices configurations. Host Operating System

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 3 Introduction - The Connected Limited Device Configuration 4
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

J2ME Configurations The CDC Configuration

Cellular phones, pagers, organizers are diverse in form of


functionality and feature.
The CDC is targeted toward powerful devices that are
However, they often use similar processors and have similar intermittently connected to a network.
amounts of memory.
The include set-top boxes, Internet TV, car navigation
Configurations define a horizontal grouping of products based systems, etc.
on the available memory budget and processing power.
The CDC contain a full-featured Java virtual Machine, similar
Currently there a two standard configuration in the J2ME
to that in use today with J2SE.
world
1 The Connected Limited Device Configuration (CLDC)
2 The Connected Device Configuration (CDC))

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 5 Introduction - The Connected Limited Device Configuration 6
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

The CDC Configuration(2) The CLDC Configuration

The resource requirements for CDC devices, as given by the


official J2ME specification :
The device is powered by a 32-bits processor
The device has 2 MB memory available for Java The second type is more prevalent in the J2ME world.
The device require the full functionality of the Java 2 "Blue
The configuration specifies much smaller footprint for
Book" virtual machine.
The device has connectivity to some kind of network, often
consumer and embedded devices than the CDC.
with wireless, intermittent connection and with limited
bandwidth.
The device may have a user interface with some degree of
sophistication, but a user interface is not mandatory.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 7 Introduction - The Connected Limited Device Configuration 8
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

Differences between standard VM and CLDC VM The CLDC in details

The differences between the standard Java virtual machine and


the CLDC virtual machine are : The Connected Limited Device Configuration (CLDC) is
1 No floating point support targeted for devices having the following characteristics :
2 No finalization 1 160 KB to 512 KB of total memory
3 Limited error handling 2 16 bits or 32 bits processors
4 No Java Native Interface 3 Connectivity to some kind of networking
5 No user-defined class loaders 4 Low power consumption
6 No support for reflection
7 No thread groups or daemon threads

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 9 Introduction - The Connected Limited Device Configuration 10
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

Differences between J2ME and J2SE The KVM (Kilo Virtual Machine)

No floating point support


The KVM is the Sun reference implementation for the CLDC
No finalization
virtual machine
Limited error handling
It is a true virtual machine
No Java Native Interface (JNI)
The KVM was specifically designed for small
No user-defined class loaders resource-constrained devices.
No support for reflection The KVM is derived from a research project called Spotless at
No thread groups or daemon thread Sun Microsystems Laboratories
No weak references

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 11 Introduction - The Connected Limited Device Configuration 12
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

The bytecode verification The CLDC security model

As seen in the "Java Security" chapter, the bytecode verifier is


responsible for rejecting invalid class files at runtime. The CLDC security model is more strict than then one likely
A Java Virtual Machine supporting CLDC must also be able to used with the J2SE
reject invalid classes. The security model is primarily concerned with two areas :
The class verification is expensive and time-consuming. It 1 Virtual machine-level security
typically takes from 35 kB to 110 kB of memory. An application executed by the KVM must not be able to
harm the device in which it is running
Therefore, the KVM designer decided to move most of the 2 Application-level security
verification off the device.
The tool preverify is responsible to do this verification.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 13 Introduction - The Connected Limited Device Configuration 14
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

The MIDlet development cycle Building a MIDlet

To write a MIDlet, one should follow the following steps :


1 Write a class extending the MIDlet class
MIDlet J2SE
class file Preverify
2 Compile it using the following command :
source compiler
javac -g:none -d tmpclasses -bootclasspath $MIDPAPI
-classpath $J2MECLASSPATH HelloMidlet.java
3 Pre-verify the bytecode produced using :
preverify -classpath $MIDPAPI:tmpclasses
-d classes tmpclasses
J2ME JAR and JAD
Packaging
Preverified 4 Create a Manifest file
VM file class file
5 Build a jar file using the command :
jar mcvf MANIFEST.MF HelloMidlet.jar HelloMidlet.class
6 Create the Java Application Descriptor file (jad-file)
7 Start the application using :
emulator -Xdescriptor:HelloMidlet.jad

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 15 Introduction - The Connected Limited Device Configuration 16
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

The Manifest file The JAD file

The Manifest file describes the content of the jar-file.


The main difference between the version 1.x and 2.x of the The Java Application Descriptor file contains informations
wireless toolkit is that the later require some informations to used by the emulator to start the application.
be added into the Manifest file. An example of a jad-file may be :
MIDlet-1: Hello,,HelloMidlet
An example of manifest file may be :
MIDlet-Name: HelloMidlet
Manifest-Version: 1.0 MIDlet-Version: 1.0
Created-By: 1.4.1_02 (Sun Microsystems Inc.) MIDlet-Vendor: ORA
MIDlet-Name: HelloMidlet MIDlet-Jar-URL: HelloMidlet.jar
MIDlet-1: Hello,,HelloMidlet MIDlet-Jar-Size: 946
MIDlet-Version: 1.0 MicroEdition-Profile: MIDP-2.0
MIDlet-Vendor: ORA MicroEdition-Configuration: CLDC_1.0
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC_1.0

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 17 Introduction - The Connected Limited Device Configuration 18
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

The HelloMidlet application The HelloMidlet code

import javax.microedition.midlet.*;
The application HelloMidlet looks like: 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);
or display.setCurrent(box);
}
Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 19 Introduction - The Connected Limited Device Configuration 20
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

The HelloMidlet code A Standard MIDlet skeleton

public class MyMidlet extends MIDlet


{
public MyMidlet()
public void pauseApp() { /* constructor*/ }
{ /* nothing */ }
public void startApp()
{ /* ... */ }
public void destroyApp (boolean unconditional)
{ /* nothing */ } public void pauseApp()
} { /* ... */ }

public void destroyApp (boolean unconditonal)


{ /* ... */ }

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 21 Introduction - The Connected Limited Device Configuration 22
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

The JAR Manifest The JAR Manifest

The following informations may / should be included into the


Manifest file :
Attribute name Required
MicroEdition-Configuration yes The version 2.0 of MIDP provides 3 other optional attributes:
MicroEdition-Profile yes Attribute name Required
MIDlet-n yes MIDlet-Permissions no
MIDlet-Data-Size no MIDlet-Permissions-Opt no
MIDlet-Description no MIDlet-Extensions no
MIDlet-Icon no
MIDlet-Info-URL yes
MIDlet-Name yes
MIDlet-Vendor yes
MIDlet-Version yes

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 23 Introduction - The Connected Limited Device Configuration 24
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

The Java Application Descriptor MIDlets states

The following informations may / should be included into the


Java Application Descriptor(jad) file :
Attribute name Required
MIDlet-Name yes
MIDlet-Version yes
MIDlet-Vendor yes
MIDlet-Jar-URL yes
MIDlet-Jar-Size yes
MIDlet-Description no
MIDlet-Icon no
MIDlet-Info-URL no
MIDlet-Data-Size no

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 25 Introduction - The Connected Limited Device Configuration 26
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

Programming Guidelines Obfuscating the code

J2ME is targetted for devices with small memory footprint. There is three main reasons to obfuscate the J2ME code
Therefore, it is crucial to make your applications run faster and 1 Protection of intellectual property
use less memory. The following tips my help you to enhance There is a lot of java decompiler one can easily find on the
your programming skills. internet. Some of these decompiler produce a pretty clean java
1 Use local variable instead fields source code and therefore may help the "reverse engineering"
2 Minimize method calls of your application.
3 Avoid string concatenation. Use class StringBuffer if
2 Footprint reduction
needed. As already mentionned, the memory of a virtual machine for a
4 Minimize object creation J2ME application is small. The use of an obfuscator may help
5 Stack is faster than heap to drastically reduce the size.
6 Avoid synchronisation.
3 Improve runtime performance
An obfuscator not only make difficult the reverse engineering
Make classes final where possible of a java program, but, with the use of some parametrisation
Use obfuscation (switches) may optimise it to enhance it efficiency. Since the
"speed" of most micro-processors used into micro devices is
Write portable code
rather low, this advantage is to be considered.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 27 Introduction - The Connected Limited Device Configuration 28
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

Obfuscating the code (cont’d) Obfuscation warning

Project Description Non ob- Obfuscated


fuscated size
1 Make sure you thoroughly test your obfuscated code. Even if
size today’s obfuscators are reliable, sometimes an obfuscated piece
of code is not supported by all virtual machines
Games Demo MIDlet 54.1K 38.7K
Obex demo Demo of Object Ex- 75.4K 70.7K 2 Platform independence may be compromised using obfuscation
change An obfuscator may introduce some functionnality only
Web Service Client J2ME WS client 11.2K 6.6K supported by some new virtual machines (for example a Java 5
Stock Quote Suite J2ME Stock Quote 16.6K 11.3K compatible VM).
MIDlet 3 Use the right parametrisation of your obfuscator
The complete table may be found at Some methods of obfuscation actually increase the size of the
http://www.devx.com/wireless/Article/28989/0/page/2 application and/or reduce performance

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 29 Introduction - The Connected Limited Device Configuration 30
Introduction The Connected Limited Device Configuration Introduction The Connected Limited Device Configuration

Some obfuscators Obfuscators references

1 Douglas L.: Protecting Java Code Via Code Obfuscation,


http://www.cs.arizona.edu/~collberg/Research/
Googling the words Java and Obfuscator returns a lot of Students/DouglasLow/obfuscation.html
results 2 Batchelder M., Hendren L.: Obfuscating Java: the most pain
Some obfuscators are commercial products and some a free for the least gain,
sofware. http://www.sable.mcgill.ca/publications/
Sun recommend the use of Proguard techreports/sable-tr-2006-5.pdf
(http://proguard.sourceforge.net/) which is a free 3 Batchelder M., Hendren L.: Java Obfuscation Techniques,
software and Retroguard http://www.sable.mcgill.ca/JBCO/examples.html
(http://www.retrologic.com/retroguard-main.html) 4 Roubtsov V.: Cracking Java byte-code encryption,
which may be used for free for academic or non-profit projects. http://www.javaworld.com/javaworld/javaqa/2003-05/
01-qa-0509-jcrypt.html
Reference list from a work of Sergio Klemensberger and Ralf
Mauerhofer
Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 31 Introduction - The Connected Limited Device Configuration 32
Introduction The Connected Limited Device Configuration MIDP GUI programming

Obfuscators references

Part II
Another web page providing a rich list of Java Obfuscators may be
found at the url:
http://www.dmoz.org/Computers/Programming/Languages/ MIDP Gui Programming
Java/Development_Tools/Obfuscators/

Programming mobile devices with J2ME Programming mobile devices with J2ME
Introduction - The Connected Limited Device Configuration 33 MIDP Gui Programming - 34
MIDP GUI programming MIDP GUI programming

MIDP GUI Programming The MIDP GUI API’s I

The MIDP GUI consists of both high-level and low-level API.


The high level is designed for application where portability is
The CLDC does not define any GUI functionality important
GUI classes are included in profiles The low level API provides little abstraction.
GUI of the MIDP are not based on the AWT It is designed for applications that need precise placement and
Why not use AWT ? control of graphic element.
1 AWT is designed for desktop computer In order show something on a MIDP device, you’ll need to
2 AWT assume certain user interaction obtain the device’s display
3 AWT has a rich feature set The Display class is defined in
4 AWT based application creates a lot of objects like events. The
javax.microedition.lcdui.Display
limited CPU and memory of handled cannot handle the burden.
There are three types of screen in the MIDP API
1 Screen that entirely encapsulate a complex user interface.
2 Generic screen that use a Form component
3 Screen used within the context of the low-level API.
Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 35 MIDP Gui Programming - MIDP GUI programming 36
MIDP GUI programming MIDP GUI programming

The MIDP GUI API’s The high-level MIDP API

Object

The first object used in MIDlet GUI is a Display object.


Displayable Command

Screen Canvas Typically, a Display object is initialized within the


Alert
ChoiceGroup
startApp() method.
<<Interface>> DateField
Display display = null;
Choice
List

...
Gauge

Form Item
public startApp() {
display = Display.getDisplay(this);
ImageItem

TextBox

StringItem
}

TextField

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 37 MIDP Gui Programming - MIDP GUI programming 38
MIDP GUI programming MIDP GUI programming

The screen structure The Screen class

The abstract Screen class formerly define the following


methods :
public String getTitle()
public void setTitle(String s)
public void setTicker(Ticker ticker)
public Ticker getTicker()
With WTK 2.0, all these methods have moved to the
Displayable class

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 39 MIDP Gui Programming - MIDP GUI programming 40
MIDP GUI programming MIDP GUI programming

The Ticker class The TextBox class

The Ticker class defines the following methods :


The TextBox class defines the following methods :
public Ticker(String str)
public String getString() public TextBox(String title, String text,
int maxSize, int constraints)
for example : public String getString()
Ticker ticker = new Ticker("Select an item to display..."); public void setString(String text)
List list = new List("",List.IMPLICIT); public void insert(String src, int position)
... // Add choices to the list public void delete(int offset, int length)
list.addCommand(okCommand); public void setConstraints(int constraints)
list.setTicker(ticker); public int getConstraints()
display.setCurrent(list);

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 41 MIDP Gui Programming - MIDP GUI programming 42
MIDP GUI programming MIDP GUI programming

The TextBox class I The Alert class

The constraints defines the "content" of the TextBox. The


following constraints are defined :
TextField.ANY Alert class defines the following methods :
public Alert(String title)
Input may be any character
public Alert(String title, String alertText,
TextField.EMAILADDR Image alertImage, AlertType alertType)
Input must be an email address public int getDefaultTimeout()
public int getTimeout()
TextField.NUMBER public void setTimeout(int time)
Input must be an integer value public AlertType getType()
TextField.PASSWD public void setType(AlertType type)
public String getString()
The text entered will be masked public void setString(String str)
TextField.PHONENUMBER public Image getImage()
Input must be a phone number public void setImage(Image img)

TextField.URL
Input must be a URL
Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 43 MIDP Gui Programming - MIDP GUI programming 44
MIDP GUI programming MIDP GUI programming

The AlertType class I The AlertType class II

The AlertType class provides an indication of the nature of


alerts.
AlertType.ALARM
The different types defined are
An ALARM AlertType is a hint to alert the user to an event
1 AlertType.INFO
for which the user has previously requested to be notified
An INFO AlertType typically provides non-threatening
information to the user. AlertType.CONFIRMATION
2 AlertType.WARNING A CONFIRMATION AlertType is a hint to confirm user
A WARNING AlertType is a hint to warn the user of a actions.
potentially dangerous operation.
AlertType.ERROR
An ERROR AlertType is a hint to alert the user to an
erroneous operation.

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 45 MIDP Gui Programming - MIDP GUI programming 46
MIDP GUI programming MIDP GUI programming

The List class The List class

void initialize() {
The List class defines the following methods : myScreen = new List("EMAIL", List.IMPLICIT);
readCommand = new Command("read",
public List(String title, int listType)
Command.SCREEN, 1);
public List(String title, int listType,
replyCommand = new Command("reply",
String[] stringElements,
Command.SCREEN, 1);
Image[] imageElements)
deleteCommand = new Command("delete",
public int size()
Command.SCREEN, 1);
public String getString(int elementNum)
myScreen.addCommand(readCommand);
public Image getImage(int elementNum)
myScreen.addCommand(replyCommand);
public boolean isSelected(int elementNum)
myScreen.addCommand(deleteCommand);
myScreen.setCommandListener(this);
}

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 47 MIDP Gui Programming - MIDP GUI programming 48
MIDP GUI programming MIDP GUI programming

Working with Forms I The Form class

A Form is a Screen that contains an arbitrary mixture of


items: The Form class defines the following methods :
images public Form(String title)
read-only text fields public Form(String title, Item[] items)
editable text fields public int append(Item item)
editable date fields public int append(String str)
gauges public int append(Image img)
public void insert(int itemNum, Item item)
choice groups
public void delete(int itemNum)
The items contained within a Form may be edited using public void set(int itemNum, Item item)
append, delete, insert, and set methods. public Item get(int itemNum)
public void setItemStateListener(
An item may be placed within at most one Form. ItemStateListener iListener)
If the item is already owned by this or another Form, an public int size()
IllegalStateException is thrown

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 49 MIDP Gui Programming - MIDP GUI programming 50
MIDP GUI programming MIDP GUI programming

The class Item The class ChoiceGroup

A ChoiceGroup is a group of selectable elements intended to


be placed within a Form.
The abstract class Item is a superclass for components that The group may be created with a mode that requires a single
can be added to a Form and Alert. choice to be made or that allows multiple choices.
It only defines the following two methods : The ChoiceGroup class defines the following constructors :
public void setLabel(String label) public ChoiceGroup(String label,
public String getLabel() int choiceType)

public ChoiceGroup(String label,


int choiceType,
String[] stringElements,
Image[] imageElements)

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 51 MIDP Gui Programming - MIDP GUI programming 52
MIDP GUI programming MIDP GUI programming

The class ChoiceGroup The class DateField

The ChoiceGroup class defines the following methods :


public int size() A DateField is an editable component for presenting date and
public String getString(int elementNum) time (calendar) information that may be placed into a Form.
public Image getImage(int elementNum)
public int append(String stringPart, Image imagePart) Value for this field can be initially set or left unset
public void insert(int elementNum, String stringElt, If value is not set then the UI for the field shows this clearly
Image imageElement)
public void delete(int elementNum) In TIME input mode the date components of Date object
public void set(int elementNum, String stringPart, must be set to the "zero epoch" value of January 1, 1970.
Image imagePart) The DateField class defines the following constructors :
public boolean isSelected(int elementNum)
public DateField(String label, int mode)
public int getSelectedIndex()
public DateField(String label, int mode,
public void setSelectedIndex(int elementNum,
TimeZone timeZone)
boolean selected)
public void setLabel(String label)

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 53 MIDP Gui Programming - MIDP GUI programming 54
MIDP GUI programming MIDP GUI programming

The class DateField The class DateField

The different modes used in this classes are defined by the


The class DateField defines the following methods : three constants :
public Date getDate()
1 DateField.DATE : Input mode for date information (day,
public void setDate(Date date) month, year).
public int getInputMode() 2 DateField.TIME : Input mode for time information (hours
public void setLabel(String label) and minutes).
3 DateField.DATE_TIME : Input mode for date (day, month,
year) and time (minutes, hours) information.

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 55 MIDP Gui Programming - MIDP GUI programming 56
MIDP GUI programming MIDP GUI programming

The class Gauge The class Gauge

The Gauge class implements a bar graph display of a value The Gauge class defines the following methods :
intended for use in a form. public void setValue(int value)
public int getValue()
Gauge is optionally interactive.
public void setMaxValue(int maxValue)
The Gauge class defines the following constructor : public int getMaxValue()
public Gauge(String label, boolean interactive, public boolean isInteractive()
int maxValue, int initialValue) public void setLabel(String label)

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 57 MIDP Gui Programming - MIDP GUI programming 58
MIDP GUI programming MIDP GUI programming

The class Gauge The class Gauge

The result of this program is :

Gauge objects may be used as shown in the following code :


Display display = Display.getDisplay(this);
Gauge progressbar = new Gauge("Progress", false,
20, 9);
Form form = new Form ("Configuring App");
form.append(progressbar);
display.setCurrent(form);

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 59 MIDP Gui Programming - MIDP GUI programming 60
MIDP GUI programming MIDP GUI programming

The class Gauge The classes Image and ImageItem

The look of an interactive Gauge is :


The Image class is used to hold graphical image data
ImageItem class that provides layout control when Image
objects are added to a Form or to an Alert.
Images can be either immutables or mutables
Immutables images are generally created by loading image
data from resource bundles or from file.
Mutable images are created in the off-screen memory and can
be modified.
Images that are to be placed within Alert, Form or
ImageItem must be immutable.

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 61 MIDP Gui Programming - MIDP GUI programming 62
MIDP GUI programming MIDP GUI programming

The class Image The class ImageItem

The class Image defines the following methods :


public static Image createImage(int width,
int height)
The class Image defines the following constructor :
public static Image createImage(String name) public ImageItem(String label, Image img,
throws IOException) int layout, String altText)
public static Image createImage(byte[] imageData, The layout parameter gives the application a hint where to
int imageOffset,
place the Image.
int imageLength)
public Graphics getGraphics() Because of device constraints, such as limited screen size, the
public int getWidth() implementation may choose to ignore layout directions.
public int getHeight()
public boolean isMutable()

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 63 MIDP Gui Programming - MIDP GUI programming 64
MIDP GUI programming MIDP GUI programming

The class ImageItem Use of ImageItem

The differents values defined are : The following code snippet gives an example how to use the
1 ImageItem.LAYOUT_DEFAULT ImageItem class :
2 ImageItem.LAYOUT_LEFT Image img = Image.createImage("/Duke.png");
3 ImageItem.LAYOUT_RIGHT ImageItem imgItem = new ImageItem("Image", img,
4 ImageItem.LAYOUT_CENTER ImageItem.CENTER_LAYOUT, "img");
5 ImageItem.LAYOUT_NEWLINE_BEFORE Form form = new Form("Duke");
6 ImageItem.LAYOUT_NEWLINE_AFTER form.append(imageItem);

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 65 MIDP Gui Programming - MIDP GUI programming 66
MIDP GUI programming MIDP GUI programming

The class StringItem The class TextField

A StringItem is a text component that may contain a string


that cannot be edited by the user.
StringItem defines only a single constructor and three A TextField is an editable text component that may be
methods : placed into a Form.
public StringItem(String label, It can be given a piece of text that is used as the initial value
String text)
public String getText()
public void setText(String text)
public void setLabel(String label)

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 67 MIDP Gui Programming - MIDP GUI programming 68
MIDP GUI programming MIDP GUI programming

The class TextField Guidelines for GUI programming for GUI devices

Be sure to make the MIDlet user interface simple and easy to


The following code shows the use of this component : use. Users may not be familiar with J2ME-enabled interface.
Display display = Display.getDisplay(this);
TextField username = Use high-level API as much as possible, so that your MIDlet
new TextField ("Login ID", "", 10, are portable
TextField.ANY);
If your application requires you to use low-level API, keep to
TextField passwd =
new TextField ("Password", "", 10, the platform-independent part of the low-level API.
TextField.PASSWORD); MIDlets should never assume specific screen size; instead they
Form form = new Form ("Sign in");
should query the size of the display and adjust accordingly
Form append (username);
Form append (passwd); Entering alphanumeric data through a handled device can be
display.setCurrent(form); tedious. If possible provide a list of choices form which the
user can select.

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 69 MIDP Gui Programming - MIDP GUI programming 70
MIDP GUI programming MIDP event model

Guidelines for GUI programming for GUI devices

MIDlets should never assume specific screen size; instead they Part III
should query the size of the display and adjust accordingly
Entering alphanumeric data through a handled device can be The MIDP Event Model
tedious. If possible provide a list of choices from which the
user can select.

Programming mobile devices with J2ME Programming mobile devices with J2ME
MIDP Gui Programming - MIDP GUI programming 71 The MIDP Event Model - 72
MIDP event model MIDP event model

The MIDP Event Model The Command class

Just like the design pattern with the same name, the Command
class encapsulates the semantic information of an action.
In AWT and Swing, events are generated when a user interact
with an application. The constructor of the class Command is defined as :
public Command(String label,
The same model holds true for the MIDP int commandType,
However, since there are two MIDP user interface APIs (high- int priority)
and low-level), there are two kinds of events. The commandType argument specifies the command’s intent.
The priority argument describes the importance of this
command relative to the other commands on the screen.

Programming mobile devices with J2ME Programming mobile devices with J2ME
The MIDP Event Model - MIDP event model 73 The MIDP Event Model - MIDP event model 74
MIDP event model MIDP event model

The Command class I The Command class II

The class Command already defines some command types. These


are :
1 Command.SCREEN : Specifies an application-defined command 7 Command.STOP : A command that will stop some currently
that pertains to the current screen. running process or operation
2 Command.SCREEN : 8 Command.EXIT : A command used for exiting from the
3 Command.BACK :A navigation command that returns the user application.
to the logically previous screen 9 Command.ITEM : With this command type the application can
4 Command.CANCEL : A command that is a standard negative hint to the implementation that the command is specific to a
answer to a dialog implemented by current screen. particular item on the screen
5 Command.OK : A command that is a standard positive answer
to a dialog implemented by current screen.
6 Command.HELP : This command specifies a request for on-line
help
Programming mobile devices with J2ME Programming mobile devices with J2ME
The MIDP Event Model - MIDP event model 75 The MIDP Event Model - MIDP event model 76
MIDP event model MIDP event model

The CommandListener interface The ItemListener interface I

This interface is used by applications which need to receive


events that indicate changes in the internal state of the
All the commands defined by the Command class contains only
interactive items within a Form screen
information about "command" not the actual action that
happens when command is activated. Item within a Form screen may be changed when the user
performs the following action :
The action is defined in a CommandListener associated with 1 Adjust the value of an interactive Gauge
the Screen 2 Enters or modifies the value of a TextField
The CommandListener only define a single method : 3 Enter a new date or time in a DateField
public void commandAction(Command c, Displayable d) 4 Changes the set of selected values in a ChoiceGroup
This interface has only one method :
public void itemStateChanged(Item item)

Programming mobile devices with J2ME Programming mobile devices with J2ME
The MIDP Event Model - MIDP event model 77 The MIDP Event Model - MIDP event model 78
J2ME security J2ME security

Java J2ME-CLDC security

The conventionnal security model is unsuitable for the Java


microedition platform
Part IV The memory budget and the cpu power targeted by J2ME
does normally not have the capabilities to run the tools and
J2ME Security controls explained above.
The lightweight security model adopted by J2ME is based onto
three points:
1 Perform an important part of the bytecode verification outside
the device
2 Adopt a simplified sandbox model
3 Provide lightweight end-to-end security mechanism

Programming mobile devices with J2ME Programming mobile devices with J2ME
J2ME Security - 79 J2ME Security - J2ME security 80
J2ME security J2ME security

Bytecode verification Off-device verification

Low level security in CLDC is mainly based on type safety


mechanisms.
The class file verified is in charge of: The verifier procede to the replacement of all jsr, jsr_w, ret
1 type safety checking and wide_ret bytecode with semantically equivalent bytecode
2 ensuring that the the bytecode cannot contain illegal
instructions The pre-verifier add a Stackmap attribute.
3 ensuring that the code cannot be executed in an illegal order Since the Stackmap attributes are ignored by the standard
4 ensuring the the code cannot contain references to invalid verifier, preverified classes as still legal classes
memory location
The bytecode verifier of the JSE environment require about
50KB for code space and between 30KB and 100 KB of ram
for execution.

Programming mobile devices with J2ME Programming mobile devices with J2ME
J2ME Security - J2ME security 81 J2ME Security - J2ME security 82
J2ME security J2ME security

On-device verification The Sandbox model

The sandbox model used by J2ME-CLDC is a simplified


The on-device verifier use the addionnal Stackmap generated version of the J2SE sandbox model.
by the preverifier In MIDP 1.0 the origin of downloaded MIDlets cannot be
The verification process consist of: authenticated and therefore they are treated as untrusted.
1 Allocate and check sufficient memory for each methods MIDlets have only a limited access to system ressources
2 Initialise methods arguments and empty operand stack for characterized by 4 requirements:
each method 1 Java class file must be properly verified
3 Performs bytecode verification by linearly iterating through 2 The processes managing the MIDlets must be built-in the
each method instruction virtual machine.
4 Check wether the las method instruction is an unconditionnal 3 Only a closed predefined set of Java API is available to the
"return" statement application programmer
4 It is not possible for an application to download new libraries
containing native functionnalities or access to native functions.

Programming mobile devices with J2ME Programming mobile devices with J2ME
J2ME Security - J2ME security 83 J2ME Security - J2ME security 84
J2ME security J2ME security

The Sandbox model (cont’d) Protecting system classes

To enforce these security restrictions, some Java features have In CLDC, the application programmer cannot override, modify or
been removed like: add any classes to the protected system package.
1 Java Native Interface (JNI) Therefore, in order to protect the sytem classes from downloaded
2 User-defined class loaders
MIDlets, system classes are always searched first when performing a
3 Thread groups or deamon threads
4 Support of reflection. class file lookup.

Programming mobile devices with J2ME Programming mobile devices with J2ME
J2ME Security - J2ME security 85 J2ME Security - J2ME security 86
J2ME security J2ME security

Security policy Protection domains

A key concept in the security of trusted MIDlets is the notion


The security policy defines the rohles governing the use of devices of protection domain.
capabilities by different Java components. More precisely:
A domain associate a device root certificate to a set of
1 Defines the sensitive device services by identifying the APIs to permissions.
be protected
For instance, one can define a "manufacturer domain”
2 Defines for each sensitive service a permission that must be associated with the public key certificate of the device
acquired before accessing the protected device manufacturer.
3 Defines the different protection domains A MIDlet signed by the manufacturer will belong to this
4 Defines the rules of authenticating the origin of the domain.
downloaded MIDlets and verifiying the integrity of downloaded For each permission granted by the protection domain, an
Jar files access level is defined for the API or function protected by the
permission domain

Programming mobile devices with J2ME Programming mobile devices with J2ME
J2ME Security - J2ME security 87 J2ME Security - J2ME security 88
J2ME security J2ME security

Protection domain’s access level Interraction modes

The access level of a permission can be either Allowed or User (but


not both).
Oneshot : a prompt is given to the user each time the MIDlet
An Allowed permission is any permission explicitly allowing
invokes the protected API
access to the protected API without involving the user (i.e
without interaction with the user) Session : The user permission is granted for the first and all
subsequent call of the API until the end of the MIDlet.
A User permission requires explicit authorisation for the user
before allowing access to the protected API Blanket : The permission is granted (or denyied) and valid
until the uninstallation of the MIDlet suite.
A prompt is given to the user. He can either deny the permission or
grant it using one of the Oneshot, Session or Blanket interaction
mode.

Programming mobile devices with J2ME Programming mobile devices with J2ME
J2ME Security - J2ME security 89 J2ME Security - J2ME security 90
J2ME security Database programming

Part V

Database and storage

Programming mobile devices with J2ME Programming mobile devices with J2ME
J2ME Security - J2ME security 91 Database and storage - 92
Database programming Database programming

Database programming The Record Management System

An RMS database consists of a collection of records that


A database is a non-volatile place for storing the state of
remain persistent after the MIDlet closes.
objects.
The RMS API is defined in the package
The persistent storage facilities provide in the J2SE platform,
javax.microedition.rms
such as the JDBC and Object Serialization APIs, are too large
for handled devices with small memory footprint. Record stores are platform dependent because they are created
in platform-unique location.
Therefore, this chapter will introduces the details of the MIDP
RMS, a persistent storage facility for the MIDlets. MIDlets within a single application can create multiple record
stores
Throughout this chapter, the terms record store and database
are used interchangeably. No mechanism is provided for sharing records between MIDlets
in differents MIDlet suites.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 93 Database and storage - Database programming 94
Database programming Database programming

The Record Management System The javax.microedition.rms package

Record stores have names that are case-sensitive and cannot The javax.microedition.rms package defines four
be more that 32 characters in length. interfaces, one class and five exception classes.
A MIDlet cannot create two record stores with the same name The list of the four interfaces is :
in the same application. RecordComparator defines a comparator to compare two
However, it can create a record store with the same name in records.
another application. RecordEnumeration represents a bidirectional record
enumerator
The MIDP RMS implementation ensures that all individual
RecordFilter defines a filter to examine a record and check
record store operations are atomic, synchronous and serialized,
if it matches, based on a criteria defined by the
so no corruption occurs with multiple access.
application.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 95 Database and storage - Database programming 96
Database programming Database programming

The javax.microedition.rms package The javax.microedition.rms package I

The five exception defined in the package are :


InvalidRecordIDException is thrown to indicate that the
RecordID is invalid
RecordListener receives records that were added, changed
RecordStoreException is thrown when a general exception
or deleted from a record store
is thrown by the RecorsStore class
The class provided by this package is : RecordStoreFullException is thrown when the record store
RecordStore represents a record store filesystem is full
RecordStoreNotFoundException is thrown when the record
store could not be found.
RecordStoreNotOpenException is thrown to indicate an
operation on a closed record store.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 97 Database and storage - Database programming 98
Database programming Database programming

Programming with the RMS Programming with the RMS

Database programming with the RMS is relative To create or open a record store, you can use the constructor
straightforward. of the RecorsStore class. This constructor is :
public static RecordStore
A record store consist of a collection of records that is uniquely
openRecordStore(String recordStoreName,
identified by its record ID, which is an integer value. boolean createIfNecessary)
The first ID has an ID of 1 throws RecordStoreException,
RecordStoreFullException,
The theoretical limit of a record store is 2’147’486’647 records. RecordStoreNotFoundException
Each record in a record store can be of different length and Record store’s names are case-sensitive and may be up to 32
can each store data differently Unicode characters in length.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 99 Database and storage - Database programming 100
Database programming Database programming

Programming with the RMS Programming with the RMS

It the openRecordStore() method is called by a MIDlet To locate a particular record store among several on the
when the record store is already open by another MIDlet in the device, the API provides the following method :
same MIDlet suite, the method return a reference to the same public static String[] listRecordStores()
RecordStore object To delete en entire record store, you can use :
Once opened, the record store will eventually be closed. This public static void
can be done by the following method : deleteRecordStore(String recordStoreName)
public void closeRecordStore() throws RecordStoreException,
throws RecordStoreNotOpenException, RecordStoreNotFoundException
RecordStoreException The size of the currently opened record store may be found
It is important to note that the record store will not actually using :
be closed until the closeRecordStore() is called as many public int getSize()
times as openRecordStore() was called. throws RecordStoreNotOpenException

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 101 Database and storage - Database programming 102
Database programming Database programming

Programming with the RMS Creating and modifying records

A record is simply an array of bytes.


To add a record to a record store, you can use the method :
public int addRecord(byte[] data,
In addition, it is possible to find out how many bytes the int offset,
current record store can still grow using : int numBytes)
public int getSizeAvailable() throws RecordStoreNotOpenException,
throws RecordStoreNotOpenException RecordStoreException,
RecordStoreFullException
The classes DataInputStream, DataOutpoutStream,
ByteArrayInputStream and ByteArrayOutputStream may
be used to pack and unpack data in and out of byte arrays.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 103 Database and storage - Database programming 104
Database programming Database programming

Creating and modifying records Creating and modifying records

To read a record from record store, you can use one of the If, for example, we have a record represented by a single string,
following methods : the following code snippet may be used to add a record
public int getRecord(int recordId,
try {
byte[] buffer,
ByteArrayOutputStream baos =
int offset)
new ByteArrayOutputStream();
throws RecordStoreNotOpenException,
DataOutputStream dos = new DataOutputStream(baos);
InvalidRecordIDException,
dos.writeUTF (record);
RecordStoreException
byte b[] = baos.toByteArray();
recordNumber = db.addRecord (b, 0, b.length);
public byte[] getRecord(int recordId)
} catch (Exception e ) {
throws RecordStoreNotOpenException,
// Handle exception
InvalidRecordIDException,
}
RecordStoreException

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 105 Database and storage - Database programming 106
Database programming Database programming

Creating and modifying records Deleting records

To extract the data from a byte array, we can do the following :


String in = null;
try {
To delete a record form the record store, the API provides the
byte[] record =
new byte [db.getRecordSize(recordNumber)]; following method :
db.getRecord(recordNumber, record, 0); public void deleteRecord(int recordId)
ByteArrayInputStream bais = throws RecordStoreNotOpenException,
new ByteArrayInputStream(record); InvalidRecordIDException,
DataInputStream dis = new DataInputStream(bais); RecordStoreException
is = dis.readUTF();
} catch (Exception e) {
// Handle exception
}

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 107 Database and storage - Database programming 108
Database programming Database programming

Filtering records Comparing records

The RecordFilter interface allos the programmer to define


filters for searching records. The RecordComparator interface allows the programmer to
This interfaces requires the programmer to supply a method define comparison operations of records.
called matches() that accept one record as a parameter. The interface defines the method compare() that takes two
This method returns a boolean indicating wether or not the records as parameters.
given record matches the user-defined search criteria.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 109 Database and storage - Database programming 110
Database programming Database programming

Comparing records The RecordListener interface

In order to monitor the addition, deletion and modification of


The method compare() returns one of the class-static values records to a record store, RMS provides the RecordListener
from RecordComparator class : interface
1 RecordComparator.EQUIVALENT if the two records are This interface defines three methods that a class must
considered equivalent
implement. Each method take two parameters, a
2 RecordComparator.FOLLOWS if the first record follows the
second
RecordStore and a recordID.
3 RecordComparator.PRECEDES if the first record precede the These methods are :
second 1 recordAdded called when a record is added
2 recordChanged called when a record is modified
3 recordDeleted called when a record is deleted

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 111 Database and storage - Database programming 112
Database programming Connecting to the world

The RecordEnumerator interface

Part VI
The RecordEnumertor interface defines a mechanism to
enumerate over all the records of a record store. Connecting the world

Programming mobile devices with J2ME Programming mobile devices with J2ME
Database and storage - Database programming 113 Connecting the world - 114
Connecting to the world Connecting to the world

The Generic connection frameworks The Generic Connection Frameworks (cont’d)

The CLDC defines an extremely flexible API for network


connection : the generic connection framework.
This framweworks is mainly contained in the package
javax.microedition.io.
This frameworks is composed of 14 interfaces.

Programming mobile devices with J2ME Programming mobile devices with J2ME
Connecting the world - Connecting to the world 115 Connecting the world - Connecting to the world 116
Connecting to the world Connecting to the world

The Generic Connection Frameworks (cont’d) Making a Connection with HTTP Get

The link between Connection interface and reality is a class


called javax.microedition.io.Connector Loading data from server is startingly simple.
The basic idea is to build a connection string which looks like For example, an HTTP Get involve 4 lines of code
an URL.
String url ="http://jonathanknudsen.com/simple";
The connection string is always built as: InputConnection ic =
<protocol>://<address>:<port>/<suppl information> (InputConnection)Connector.open(url);
For example: InputStream is =ic.openInputStream();
socket://apress.com:79/ // Read and process stuff
http://jonathanknudsen.com/simple ic.close();
sms://5550001:1234
mms://+5550000:MMSMIDlet

Programming mobile devices with J2ME Programming mobile devices with J2ME
Connecting the world - Connecting to the world 117 Connecting the world - Connecting to the world 118
Connecting to the world Connecting to the world

Wireless Messaging API The WMA (Wireless Message API)

SMS messages are sent and received via the WMA


SMS sent via WMA may be significantly larger in size than
SMS is one of the most widely available and popular services
stantard SMS
for cell phones users.
The Wireless Toolkit (WTK) allow to send and receives SMS The content of SMS sent via WMA is no longer restricted to
between phones without: simple text messages
1 Having Internet Access from the phone The WMA encode a binary message and transmit it via SMS.
2 Going through an intermediary server A long message may be splitted in up to 3 messages before it
3 Being restricted in term of routing by the carrier’s network
is sent.
WMA API is described in JSR 120 and WMA APi 2.0 is
described in JSR 205

Programming mobile devices with J2ME Programming mobile devices with J2ME
Connecting the world - Connecting to the world 119 Connecting the world - Connecting to the world 120
Connecting to the world Connecting to the world

The WMA API

javax.microedition.io package
Connection CLDC 1.0
Generic Connection Framework

InputConnection OutputConnection DatagramConnection

StreamConnection UDPDatagramConnection

WMA 1.1 newMessage()


JSR 120 Message MessageConnection

TextMessage BinaryMessage MultipartMessage

WMA 2.0 JSR 205

Programming mobile devices with J2ME Programming mobile devices with J2ME
Connecting the world - Connecting to the world 121 Connecting the world - Connecting to the world 122
Connecting to the world Connecting to the world

Programming mobile devices with J2ME Programming mobile devices with J2ME
Connecting the world - Connecting to the world 123 Connecting the world - Connecting to the world 124

You might also like