View
2
Download
0
Category
Preview:
Citation preview
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
1
J2ME J2ME Programming
J2ME
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
2
J2ME J2ME Programming
References
● Java Community Processhttp://jcp.org/en/home/index/
● Java 2 Platform, Micro Edition (J2ME)http://java.sun.com/j2me/
● Sun Developer Networkhttp://developers.sun.com/techtopics/mobility/
● Core J2ME Technology and MIDPJ. W. Muchow, 2002, ISBN 0130669113
● Developing with J2ME, Second EditionJ. Knudsen, 2003, ISBN 1590590775
● Wireless J2ME Platform ProgrammingV. Piroumian, 2002, ISBN 0130449148
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
3
J2ME J2ME Programming
Java started small, aimed at television set top boxes and other interactive devices. Of course, once it got aimed toward web browsers and applets, the brakes were off. As a result, the platform got all kinds of amazing features like Swing, Java 2D, Java 3D, JDBC, EJB, and so on. With each new API, the size of the platform got bigger and bigger and bigger. So did the runtime footprint. These days, it is not uncommon to see Java virtual machines with a gigabyte or more of heap space.
Whether it is called featuritis, bloat, or customer responsiveness, the fact remains that the Java 1 platform was big, and the standard Java 2 platform is huge.
History
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
4
J2ME J2ME Programming
In 1995 the first version of Java, now known as Java 2 Standard Edition (J2SE), was released. Since that time its landscape has changed significantly.
Standard Edition (J2SE)Designed to run on desktop and workstation computers.
Enterprise Edition (J2EE)This edition is aimed at server-based applications. Contains buit-in support for Servlets, JSP and XML.
Micro Edition (J2ME)Designed for devices with limited memory, display and processing power.
Java Editions
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
5
J2ME J2ME Programming
Java
2 E
nte
rpri
se E
dit
ion
(J2EE)
Java Virtual Machine KVM
Java Editions
CLDC
MIDP
CDCJava
2 S
tandard
Edit
ion
(J2SE)
Java 2 Standard Edition(J2SE)
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
6
J2ME J2ME Programming
Generic J2ME Architecture
Profile
Host Operating System
ApplicationNative
Applications
AMSConfiguration
Libraries
JavaVirtual Machine
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
7
J2ME J2ME Programming
There are three main areas that distinguish the Java Language for CLDC versus that defined in the Java Language Specification.
● Floating Point MathThe CLDC 1.0 implementation of the Java language does not support floats. CLDC 1.1 specifies such support. But MIDP 2.0 only requires CLDC 1.0.
● FinalizationThe CLDC does not support the finalize() method because an overhead and processor requirements are too steep.
● Error HandlingThe JVM supports a limited set of error handling exceptions due a signicant demand on the system's device-dependent.
Java Language Differences
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
8
J2ME J2ME Programming
The Java virtual machine supporting CLDC differs from theJava Virtual Machine Specication.
● Floating Point MathThe implementation of the JVM for CLDC 1.0 lacks support for floating point numbers.
● Java Native InterfaceTo reduce the potential of corruption to system level
information support for invoking native methods was eliminated.
● Custom Class LoaderThere are tight controls on a class loader|it cannot be replaced, overriden or modified. The loader itself is device-dependent.
continued ►
Java Virtual Machine Differences
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
9
J2ME J2ME Programming
◄ continued
● ReflectionReflection is not available on a JVM supporting the CLDC.
● Thread GroupsThe JVM does not support the ThreadGroup class.
● FinalizationThe JVM lacks support for finalization.
● Weak ReferencesThe JVM does not support weak references to objects.
Java Virtual Machine Differences
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
10
J2ME J2ME Programming
Any device running a Java application needs protection from malicious code that may access system information or resources. Advanced security model provided by the J2SE is too memory-consuming to be included in CLDC devices. The security model, which is provided in the CLDC devices, is the so called sandbox model. In the sandbox model, the applications are run in a closed environment in which the application can only access not secure-sensitive resources.
Regardless of the JVM, this type of “low-level” security is implemented using class file verication.
Handling Security
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
11
J2ME J2ME Programming
Verifying the integrity of class files is not a trivial operation. To spread the work load on a mobile device, verification is done in two steps.
● Pre-verication A software program is run to insert additional attributes into the class file. This information reduces the amount of time and memory necessary when the JVM carries out step 2 of verification.
● In-device VericationOnce a device loads a pre-veried class le, the in-device verifier runs through each instruction. There are several checks done to validate the code.
Class File Verification
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
12
J2ME J2ME Programming
Capabilities of devices within the J2ME may vary greatly. A PDA may have a much larger display than a pager. One Java platform will most definetely not fit all. In order to accommodate a broad range of consumer electronics and embeded devices J2ME introduces two new concepts: configurations and profiles.
Configurations and Profiles
Profile
Libraries
Java Virtual Machine
Configuration
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
13
J2ME J2ME Programming
A conguration defines a Java platform for a broad range of devices. A configuration is closesly tied to a JVM. In fact, a conguration defines the Java language features and the core Java libraries of the JVM for that particular configuration.
The dividing line as to what a configuration applies is for the most part based on memory, display, network connectivity and processing power available on a device. Configuration provides the lowest common denominator for a group of devices.
Currently, there are two configurations defined:● Connected Limited Device Configuration (CLDC) and● Connected Device Configuration (CDC).
Configuration
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
14
J2ME J2ME Programming
This conguration is designed for devices with more memory, faster processors and greater network bandwith. It is appropriate, at least in the near term, for home automation and automotive enteratinment, navigation, and telemetry systems.
A programming model closer to J2SE simplies porting existing desktop clients for enterprise systems to mobile devices that support CDC.
Connected Device Conguration
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
15
J2ME J2ME Programming
This conguration is intended for devices with intermittent network connections, small processors and limited memory. Expected targets included two-way pagers, mobile phones and entry-level PDAs.
However, in practice, the functionality delivered by CLDC and the associated profiles and optional packages is very close to that of CDC. As a consequence it is used today on most high-end mobile phones, or smartphones, which are replacing PDAs in the marketplace.
Connected Limited Device Conguration
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
16
J2ME J2ME Programming
CDC is a subset of J2SE plus some extra classes. CLDC is a subset of CDC.
CLDC versus CDC
J2SE
CDC CLCD
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
17
J2ME J2ME Programming
A profile supplements a configuration to provide capabilities for a specific family of devices or specific industry segment application need.
For example, a configuration provides a generic Java API for battery powered, limited display and processing capability systems, while a profile provides a supplemental Java API specific to cellular telephones, which is a member of this larger group of devices. A profile must supplement a configuration.
A profile will not work without the configuration and virtual machine providing the core classes/API and runtime environment.
Profile
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
18
J2ME J2ME Programming
The Mobile Information Device Profile (MIDP) is a key element of the Java 2 Platform, Mobile Edition (J2ME). When combined with the Connected Limited Device Configuration (CLDC), MIDP provides a standard Java runtime environment for today's most popular mobile information devices, such as cell phones and mainstream personal digital assistants. The profile can be characterized by the following features:
● rich user interface capabilities,● extensive connectivity,● multimedia and game functionality,● over-the-air-provisioning,● end-to-end security.
Mobile Information Device Profile
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
19
J2ME J2ME Programming
The IMP is a strict subset of the MIDP 1.0 specification. The primary difference is that IMP removes MIDP's display and input mechanisms. Instead, IMP devices must provide their own implementation-specific classes to handle any interaction with the user they need.
Information Module Profile
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
20
J2ME J2ME Programming
Excerpt from J2ME FAQ: Configurations and Profiles are defined by open industry working groups utilizing Sun’s Java Community Process Program. In this way industries can decide for themselves what elements are necessary to provide a complete solution targeted at their industry. For more information on the Sun Community Process Program, see: http://jcp.org.
How are Configurationis and Profiles Defined?
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
21
J2ME J2ME Programming
A MIDlet is a Java program for embedded devices, more specifically the J2ME virtual machine. Generally, these are games and applications that run on a cell phone.
MIDlets will (should) run on any device that implements J2ME MIDP. Like all Java programs, MIDlets are “compile once, run anywhere.”
A MIDlet must extend the MIDlet class found in the javax.microedition.midlet package.
MIDlet
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
22
J2ME J2ME Programming
A MIDlet goes through several phases as part of its lifecycle and is always considered to be in on of three states.
Lifecycle
Paused
Destroyed
ActivestartApp()
pauseApp()
destroyApp()destroyApp()
MIDlet()
AMS reclaims MIDlet
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
23
J2ME J2ME Programming
The MIDlet class serves as the gateway for communicating application-state changes to the AMS and vice versa.
Lifecycle
Paused
Shutdown
Running
startApp()pauseApp() destroyApp()AMS
Startup
MIDlet()
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
24
J2ME J2ME Programming
MIDlet should not have a main() method. If one is found then Application Management Software (AMS) ignores it.
public class Empty extends MIDlet { protected void startApp() throws MIDletStateChangeException { }
protected void pauseApp() { }
protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { }}
Structure
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
25
J2ME J2ME Programming
Creation
.java
Compilation
.class
Pre-verification
.jar
Packaging
manifest.txt
Deploying.jad
Internet
.class
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
26
J2ME J2ME Programming
This collection of MIDlets encapsulated in a JAR file is referred to as a MIDlet suite. MIDlets within a MIDlet suite share a common name space for persistent storage, runtime object heap, and static fields in classes. The contents of the MIDlet suite’s JAR file include the following components:
● the class files implementing the MIDlets,● any resource files used by the MIDlets: for example, icon or
image files, and so forth,● a manifest describing the JAR contents.
MIDlet Suite
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
27
J2ME J2ME Programming
The JAR manifest specification provides for name-value pairs which MIDP uses to encode MIDlet attributes. These attributes can be retrieved by a MIDlet using the getAppProperty() method.
All attribute names that start with "MIDlet-" are reserved for use by the MIDP expert group to define MIDlet attributes.
The following attributes must be in the JAR manifest:
● MIDlet-Name,● MIDlet-Version,● MIDlet-Vendor,● A MIDlet-<n> for each MIDlet,● MicroEdition-Profile,● MicroEdition-Configuration.
MIDlet Suite's Manifest File
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
28
J2ME J2ME Programming
METAFILE.MF Example
MIDlet-Name: TeaTime MIDlet SuiteMIDlet-Version: 1.1.9MIDlet-Vendor: Krtek PolniMIDlet-1: TeaTime, /glasswatch.png, tea.TimerMIDletMIDlet-2: TeaEdit, /tea.png, tea.EditorMicroEdition-Profile: MIDP-2.0MicroEdition-Configuration: CLDC-1.1
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
29
J2ME J2ME Programming
In addition to the JAR file, the MIDP provides for a separate and optional file called the application descriptor. The application descriptor allows the system to verify that the associated MIDlet suite is suited to the device before loading the full JAR file of the MIDlet suite. It also allows MIDlet attributes to be supplied to the MIDlet suite without modifying the JAR file.
The following attributes must be in the JAD manifest:● MIDlet-Name,● MIDlet-Version,● MIDlet-Vendor,● MIDlet-Jar-URL,● MIDlet-Jar-Size.
Application Descriptor
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
30
J2ME J2ME Programming
JAR File ContentsThe getResourceAsStream() method of class Class gives access to resources stored in JAR file.
Class c = getClass();InputStream input = c.getResourceAsStream("/META-INF/MANIFEST.MF");
META-INF/META-INF/MANIFEST.MFtea/tea/TimerMIDlet.classtea/Tea.classtea/CoundDownForm.classglasswatch.pngwarning.png
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
31
J2ME J2ME Programming
GUI
GUI
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
32
J2ME J2ME Programming
UI Classes
Display
Displayable
Screen
Canvas
Alert
List
TextBox
Form
Item
StringItem
ImageItem
TextField
DateField
Gauge
ChoiceGroup
0..1
0..*
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
33
J2ME J2ME Programming
Display
Each MIDlet has a reference to one Display object. This object can retrieve information about the current display and includes methods for requesting visual objects to be displayed. The Display object is best thought of as the manager of the display controlling what is shown on the device and when.
private Display display;
public Welcome() { super(); display = Display.getDisplay(this); ...
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
34
J2ME J2ME Programming
Displayable
A Displayable is an object that has the capability of being placed on the display. There are two types of Displayable object.
CanvasLow-level objects that allow the application to provide the graphics and handle input.
ScreenHigh-level object that encapsulates a complete user interface component (for example, classes Alert, List, TextBox, or Form).
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
35
J2ME J2ME Programming
Low-Level User Interface
The low-level user interface API for Canvas is designed for applications that need precise placement and control of graphic elements, as well as need access to lowlevel input events. Typical examples are a game board, a chart object, or a graph. Using the low-level user interface API, an application can:
● control what is drawn on the display,● handle primitive events like key presses and releases,● access concrete keys and other input devices.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
36
J2ME J2ME Programming
High-Level User Interface
The high-level user interface API is designed for business applications whose client components run on mobile information devices. To achieve portability, the high-level user interface API employes a high level of abstraction and provides very little control over look and feel.
● Drawing to the display is performed by the device's system software. Applications do not dene the visual appearance (such as shape, color, font, and so forth) of the components.
● Navigation, scrolling, and other primitive interactions with the user interface components are performed by the device. The application is not aware of these interactions.
● Applications cannot access concrete input mechanisms, such as individual keys.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
37
J2ME J2ME Programming
Commands
Since the MIDP user interface is highly abstract, it does not dictate any concrete user interaction technique such as soft buttons or menus.
MIDP applications define Commands, and the implementation can provide user control over these with buttons, menus, or whatever mechanisms are appropriate for the device.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
38
J2ME J2ME Programming
Command Listener Pattern
The CommandListener interface is used by applications which need to receive high-level events from the implementation. An application will provide an implementation of a CommandListener and will then provide the instance to the addCommand method on a Displayable in order to receive high-level events on that screen.
Command Displayable
addCommand()removeCommand()setCommandListener()
CommandListener
commandAction()
0-10-*
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
39
J2ME J2ME Programming
Command Registration
Command yes = new Command("Yes", Command.OK, 0);Command no = new Command("No", Command.BACK, 0);
Displayable warning = new WarningMessage(...
warning.addCommand(yes);warning.addCommand(no);warning.setCommandListener(this);
Display display = Display.getDisplay(this);display.setCurrent(warning);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
40
J2ME J2ME Programming
Listener
The application-level handling of commands is based on a listener model. Each Displayable object has a single listener.
public class TeaTime extends MIDlet implements CommandListener { private Command yes, no;
public void commandAction(Command c, Displayable d) { if (c == yes) { // Delete the tea from list. ... } else if (c == no) { // Do nothing. }
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
41
J2ME J2ME Programming
MenuAbstract commands that cannot be mapped onto physical buttons are placed in a menu and the label "Menu" is mapped onto one of the programmable buttons.
cancel = new Command("Cancel", Command.BACK, 0);edit = new Command("Edit", Command.ITEM, 1);create = new Command("Create New", Command.ITEM, 1);delete = new Command("Delete", Command.ITEM, 1);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
42
J2ME J2ME Programming
List
The List class is a Screen that contains a list of choices. Each choice has an associated string and may have an icon.
List objects may be created as one of the three types: exclusive, multiple and implicit.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
43
J2ME J2ME Programming
List Initialization
List list = new List("Select ...", List.IMPLICIT);for (int i = 0; i < teas.size(); i++) { Tea tea = (Tea)teas.elementAt(i); list.append(tea.getName(), null);}
list.setCommandListener(this);
display.setCurrent(list);
Implicit Lists can be used to construct menus by providing operations as List elements.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
44
J2ME J2ME Programming
Selection in Implicit List
public void commandAction(Command c, Displayable d) { if (c == List.SELECT_COMMAND) { List list = (List)d; int index = list.getSelectedIndex(); ... } else if (c == select) { ...
When the user performs select operation in implicit list, the system will invoke the select command by notifying the List's CommandListener. The default select command is the system-provided command SELECT_COMMAND.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
45
J2ME J2ME Programming
TextBoxThe TextBox class defines a Screen that allows the user to enter and edit text.
String title = tea + " Description";String description = ...
TextBox text = new TextBox(title, description, 256, TextField.ANY);text.addCommand(save);text.addCommand(cancel);
display.setCurrent(text);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
46
J2ME J2ME Programming
AlertAlerts are best used in informational or error messages that stay on the screen for a short period of time and then disappear.
Alert alert = new Alert("Tea Time");alert.setTimeout(Alert.FOREVER);alert.setType(AlertType.ALARM);alert.setString("Your tea has ... ");alert.setImage(image);
display.setCurrent(alert);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
47
J2ME J2ME Programming
Form
A Form is a Screen that may contain a combination of Items including Strings, Images, editable TextFields, editable DateFields, Gauges and ChoiceGroups. Any of the subclasses of Item.
An item may be placed within at most one Form. If the application attempts to place an item into a Form, and the item is already owned by this or another Form, an IllegalStateException is thrown.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
48
J2ME J2ME Programming
Form Item Management
TextField name = new TextField("Name", "", 16, TextField.ANY);TextField time = new TextField("Infus...", "", 4, TextField.NUMERIC);TextField description =
Form form = new Form("Tea ...");form.append(name);form.append(time);
form.addCommand(save);form.addCommand(cancel);form.setCommandListener(this);
Items contained within a Form may be edited using append(), delete(), insert(), and set() methods.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
49
J2ME J2ME Programming
Exclusive and Multiple Choice
A ChoiceGroup is a group of selectable elements intended to be placed within a Form.
ChoiceGroup group = ...
// Choice.EXCLUSIVEint index = group.getSelectedIndex();
// Choice.MULTIPLEboolean[] selected;group.getSelectedFlags(selected);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
50
J2ME J2ME Programming
Popup Choice
The selection behavior of a popup choice is identical to that of an exclusive choice. However, a popup choice differs from an exclusive choice in presentation and interaction. In a popup choice, the selected element should always be displayed, and the other elements should remain hidden until the user performs a specific action to show them.
ChoiceGroup group = new ChoiceGroup("Select ...", Choice.POPUP);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
51
J2ME J2ME Programming
Gauge
Implements a graphical display, such as a bar graph, of an integer value. The Gauge contains a current value that lies between zero and the maximum value, inclusive. A Gauge may be interactive or non-interactive.
Gauge gauge = new Gauge(null, true, tea.getTime(), 0);append(gaute);
while (gauge.getValue() - gauge.getMaxValue()) { ... gauge.setValue(gauge.getValue() + 1);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
52
J2ME J2ME Programming
TickerA Ticker implements a “ticker-tape,” a piece of text that runs continuously across the display. The direction and the speed of scrolling are determi-ned by the device.
Tickers can be set on any Screen. A Ticker object can be shared between Screens, so that when switching between Screens the message appears continuously.
Screen screen = ...screen.setTicker(new Ticker("Select a tea to infuse"));
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
53
J2ME J2ME Programming
Custom Item
A CustomItem is customizable by subclassing to introduce new visual and interactive elements into Forms. Subclasses are responsible for their visual appearance including sizing and rendering and choice of colors, fonts and graphics. They are also responsible for calling notifyStateChanged() to trigger notification of listeners that the CustomItem's value has changed.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
54
J2ME J2ME Programming
Custom Item
public class ProgressItem extends CustomItem { protected int getMinContentWidth() { ... protected int getMinContentHeight() { ... protected int getPrefContentWidth(int w) { ... protected int getPrefContentHeight(int h) { ... protected void paint(Graphics g, int w, int h) { ...
Form form = new DownloadForm();...ProgressItem progress = new ProgressItem();progress.setLayout(Item.LAYOUT_2|Item.LAYOUT_CENTER);form.append(progress);
A CustomItem can be appended to a Form and manipulated with as any other subclass of the Item.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
55
J2ME J2ME Programming
Canvas
The Canvas class provides the display surface, its dimensions, and callbacks used to deliver events for key and pointer events and for painting the display when requested.
Applications may draw by using this graphics object only for the duration of the paint() method.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
56
J2ME J2ME Programming
Redrawing Mechanism
The application is responsible for redrawing the screen whenever repainting is requested. The application implements the paint() method in its subclass of Canvas. Painting of the screen is done on demand.
To request a repaint of the entire display or its portion only, the application calls the repaint() method of the Canvas object.
Since painting is done asynchronously, the application might need to wait for repaint requests to be completed before it can continue. The serviceRepaints() method blocks until all of the repaint requests queued have resulted in a paint() call.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
57
J2ME J2ME Programming
Color Model
The 24-bit color model has eight bits for each of red, green, and blue. The current color is set using the setColor() method. The current color is used for all lines, text, and fills for rectangles and arcs.
Few devices support full 24 bits of color. The device maps the color requested by the application into a color available on the device. The details of the mapping are device specific.
The Display.isColor() method determines if the display is capable of supporting multiple colors or supports grayscale or black and white only. The number of distinct colors or gray levels is available by the method Display.numColors().
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
58
J2ME J2ME Programming
Fonts
The Font.getFont() method returns the Font associated with a given style, size, and face. It is up to the device to select a font that most closely matches the requested attributes. The following attributes can be used to request a font:
● FacePROPORTIONAL, MONOSPACE, SYSTEM;
● StylePLAIN, BOLD, ITALIC, UNDERLINED;
● SizeSMALL, MEDIUM, LARGE.
Font font = Font.getFont(Font.PROPORTIONAL, Font.BOLD, Font.LARGE);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
59
J2ME J2ME Programming
Font Metrics
The Font class provides methods to access the font metrics, including getHeight() and getBaselinePosition(). The whitespace for interline and intercharacter spacing is included in the metrics and is below and to the right of the characters, respectively. The metrics allow an application to precisely place text relative to graphics.
base
line
heig
ht
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
60
J2ME J2ME Programming
String WidthsIt is possible to determine width of string or character typed using given font.
drawWord(Graphics graphics, Font font, String word) { int w = font.stringWidth(word); if ((x + w) > width) { x = 0; y += font.getHeight(); }
graphics.setFont(font); graphics.drawString(word, x, y, ... x += w + font.charWidth(' ');}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
61
J2ME J2ME Programming
Canvas Visibility
When the application's choice of current screen is a Canvas, the canvas is notied when its visibility changes. The showNotify() and hideNotify() methods are invoked automatically the canvas shown and hidden, respectively.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
62
J2ME J2ME Programming
Key Events
If the application needs to handle key events in its Canvas, it must override methods keyPressed(), keyReleased(), and keyRepeated(). The Canvas class defines basic codes to support the ITU-T telephone keys.
protected void keyPressed(int key) { if (key == KEY_NUM2) {
The Canvas class has methods and codes for handling portable action events.
protected void keyReleased(int key) { if (key == FIRE) {
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
63
J2ME J2ME Programming
Graphics
The Graphics class provides methods to paint lines, rectangles, arcs, text, and images to a Canvas or an Image. Applications may draw by using this graphics object only for the duration of the paint() method.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
64
J2ME J2ME Programming
Coordinates
The coordinate system represents locations between pixels, not the pixels themselves. Therefore, the first pixel in the upper-left corner of the display lies in the square bounded by coordinates (0,0), (1,0), (0,1), (1,1).
0 x
y
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
65
J2ME J2ME Programming
Anchor Points
Anchor points are used to minimize the amount of computation required when placing text.
g.drawString("T", x, y, Graphics.LEFT|Graphics.TOP);
TOP
BASELINE
BOTTOM
LEFT CENTER RIGHT
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
66
J2ME J2ME Programming
Clipping
The clip is the set of pixels in the destination of the Graphics object that may be modified by graphics rendering operations.
The only pixels modified by graphics operations are those that lie within the clip. Pixels outside the clip are not modified by any graphics operations.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
67
J2ME J2ME Programming
Clippinggraphics.setClip(leftL, topL, widhtL, heightL);graphics.setColor(colorL);graphics.drawString(label, x, y, anchors);
graphics.setClip(leftR, topR, widhtR, heightR);graphics.setColor(colorR);graphics.drawString(label, x, y, anchors);
graphics.setClip(0, 0, getWidth(), getHeight();
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
68
J2ME J2ME Programming
Double Buffering
The double buffering technique is often used to perform smooth effect animation. In this technique, it is not drawn to the display, but instead to a copy of the display (an off-screen buffer) that is maintained in memory. When the drawing to the buffer is done, the contents of the buffer is copied to the display.
New devices are equiped with build-in double buffering. It can be determined by the Graphics.isDoubleBuffered()method.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
69
J2ME J2ME Programming
Double BufferingMutable images are used for the bouble buffering. The getGraphics() method returns a Graphics object that can beused for drawing into the Image. All normal graphics methods operate on the Image.
public void paint(Grahpics graphics) { bufferGraphics.drawLine(...); bufferGraphics.drawImage(pen, ...);
graphics.drawImage(buffer);}
Image buffer = Image.createImage(width, height);Graphics bufferGraphics = buffer.getGraphics();
Image pen = Image.createImage("/pen.png");
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
70
J2ME J2ME Programming
Persistent Storage
Persistent storage is a non-volatile place for storing the state of objects. The MIDP provides a mechanism for MIDlets to persistently store data and retrieve it later. This mechanism is a simple record-oriented database called the Record Management System (RMS).
A record store consists of a collection of records which will remain persistent across multiple invocations of the MIDlet.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
71
J2ME J2ME Programming
Record Store
RecordStore store = RecordStore.openRecordStore("contacts", true);
String user = ...byte[] data = user.getBytes();int id = store.addRecord(data, 0, data.length);...store.setRecord(id, data, 0, data.length);...store.deleteRecord(id);store.closeRecordStore();
Records are uniquely identified within a given record store by their id, which is an integer value. This id is used as the primary key for the records. The first record created in a record store will have id equal to one.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
72
J2ME J2ME Programming
Enumerating Records
RecordStore store = RecordStore.openRecordStore("contacts", false);RecordEnumeration records = store.enumerateRecords(null, null, false);while (records.hasNextElement()) { byte[] record = records.nextRecord(); ...}
The RecordEnumeration logically maintains a sequence of the ids of the records in a record store. An optional RecordFilter can be used to choose a subset of the records that match the supplied filter. By using an optional RecordComparator, the enumerator can index through the records in an order determined by the comparator.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
73
J2ME J2ME Programming
Multi Threading
MULTITHREADING
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
74
J2ME J2ME Programming
ThreadsThere is often need to turn a program into separate, independently running subtasks. Each of these independent subtasks is called a thread, and is programmed as if each thread runs by itself and has the CPU to itself. The thread model is a programming convenience to simplify juggling several operations at the same time within a single program. There is several reasons why to do this.
● There can be one thread controlling and responding to a GUI, while another thread carries out the tasks or computations requested, while a third thread does file I/O, all for the same program.
● Some programs are easier to write if they are split into threads. The classic example is the server part of a client/server. When a request comes in from a client, it is very convenient if the server can spawn a new thread to process that one request.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
75
J2ME J2ME Programming
Class Thread
public class CountDownThread extends Thread { private static int threads = 0; private int thread = threads++; public void run() { for (int i = MAX_COUNT; i > 0; i--) System.out.println("thread #" + thread + ": " + i); }}
Thread thread = new CountDownThread();thread.start();
The simplest way to create a thread is to inherit from class java.lang.Thread. The most important method for Thread is run(), which is the code that will be executed simultaneouslywith the other threads in a program.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
76
J2ME J2ME Programming
Interface Runnable
public class CountDownThread implements Runnable { private static int threads = 0; private int thread = threads++; public void run() { for (int i = MAX_COUNT; i > 0; i--) System.out.println("thread #" + thread + ": " + i); }}
Thread thread = new Thread(new CountDownThread());thread.start();
Sometimes it is impossible or inconvenient to inherit from Thread class. The java.lang.Runnable interface, declaring the run() method, can be implemented in these cases.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
77
J2ME J2ME Programming
The Life Cycle of a ThreadA thread goes through several states during its life cycle:
● Creating When a thread is created, it is merely an empty object. No system resources are allocated. The thread in this can be only started.
● Starting The start() method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread's run() method.
● Making a Thread Not Runnable A thread becomes Not Runnable when one of these
events occurs: its sleep() or wait() method is invoked.
● Stopping A program does not stop a thread directly. Rather, a
thread arranges for its own death by leaving its run()method.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
78
J2ME J2ME Programming
Synchronization
public class Game { private Player black, white, previous; public synchronized void turn(Player player) { if (player == previous) throw new IllegalPlayerException(...); ...
There are many interesting situations where separate, concurrently running threads do share data and must consider the state and activities of other threads. Java provides a synchronization mechanism based on monitors. Each object in Java has a lock and a monitor to manage the lock. A block marked as synchronized forces any thread wishing to enter the block to acquire corresponding lock first. If another thread already holds the lock, the acquiring thread will block until the lock will be released. The lock is released when the thread leaves the block.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
79
J2ME J2ME Programming
Producer-Consumer Problem
public interface SharedData { public int getSize(); public void put(int[] data); public int[] get();}
The producer-consumer problem is a classic synchronization problem. The producer and consumer processes share a common data. The producer executes a loop in which it puts new items into the data and the consumer executes a loop in which it removes items from the data.
ConsumerProducer
SharedData
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
80
J2ME J2ME Programming
Producer
public class Producer extends Thread { private SharedData data; public void run() { for (int i = 0; i < 10; i++) { int[] array = new int[data.getSize()]; System.out.print("put"); for (int j = 0; j < array.length; j++) { array[j] = i; System.out.print(" " + array[j]); } System.out.println(); data.put(array); } } ...
The producer executes a loop in which it puts new items into the data store.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
81
J2ME J2ME Programming
Consumer
public class Consumer extends Thread { private SharedData data; public void run() { for (int i = 0; i < 10; i++) { int[] array = data.get(); System.out.print("got"); for (int j = 0; j < array.length; j++) System.out.print(" " + array[j]); System.out.println(); } } } ...
The consumer executes a loop in which it removes items from thedata store.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
82
J2ME J2ME Programming
Naïve Shared Data
public class NaiveSharedData implements SharedData { private int[] data; public void put(int[] data) { for (int i = 0; i < data.length; i++) this.data[i] = data[i]; } public int[] get() { int[] data = new int[this.data.length]; for (int i = 0; i < data.length; i++) data[i] = this.data[i]; return data; } ...
Traditional implementation of the SharedData interface seems to be all right, but ...
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
83
J2ME J2ME Programming
Putting It All Together
SharedData data = new NaiveSharedData(3);Producer producer = new Producer(data);Consumer consumer = new Consumer(data);producer.start();consumer.start();
Output produced by the program is incorrect, because it containsinconsisten sequence 0 0 1.
The producer-consumer problem can be assembled by a few lines of code.
...put 1 1 1got 0 0 1got 1 1 1put 2 2 2...
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
84
J2ME J2ME Programming
Acquiring a Lock
public class BetterSharedData extends NaiveSharedData { public synchronized void put(int[] data) { super.put(data); } public synchronized int[] get() { return super.get(); }
The code segments within a program that access the same object from separate, concurrent threads are called critical sections. A critical is identified with the synchronized keyword. A lock is associated with every object that has synchronized code.
...put 2 2 2got 2 2 2got 2 2 2put 3 3 3
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
85
J2ME J2ME Programming
Releasing a Lock (I)
public class PerfectSharedData extends BetterSharedData { private boolean read = true; public synchronized void put(int[] data) { try { while (!read) wait(); super.put(data); read = false; notifyAll(); } catch (InterruptedException e) { ...
A thread releases an object's lock when it enters into wait()method of the object. The wait() method causes the thread to wait until another thread invokes the notify() or the notifyAll() method for the object.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
86
J2ME J2ME Programming
Releasing a Lock (II)
public synchronized int[] get() { int data[] = null; try { while (read) wait(); data = super.get(); read = true; notifyAll(); } catch (InterruptedException e) { e.printStackTrace(); } return data;}
The InterruptedException is thrown by the wait() method if another thread interrupts the current thread.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
87
J2ME J2ME Programming
Scheduling TasksThere are two classes, Timer and TimerTask, to facilitate running of tasks in a background thread.
● Scheduling one-time tasksExecutes a task after specified delay.
● Scheduling repeating tasks Executes a task at regular intervals. There are two
variations for scheduling repeating tasks.
● Fixed-delayEach execution of a task is based solely on how long it was since the previous task finished.
● Fixed-rateEach execution of a task is based on when the first task started and the requested delay between tasks.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
88
J2ME J2ME Programming
Timer Task
public class DrawerTask extends TimerTask { private AnimationCanvas canvas; public DrawerTask(Canvas canvas) { this.canvas = canvas; } public void run() { canvas.drawNextFrame(); }
}
A subclass of TimerTask defines what is to be done. It declares abstract method run() which has be implemented by the subclass.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
89
J2ME J2ME Programming
Animation Canvas
public class AnimationCanvas extends Canvas { private Image[] frames = new Image[FRAMES]; int currentFrame = 0; public AnimationCanvas() throws IOException { for (int i = 0; i < frames.length; i++) { frames[i] = Image.createImage("/frame" + (i+1) + ".png"); } } public void drawNextFrame() { currentFrame = (currentFrame+1)%frames.length; repaint(); } ...
The drawNextFrame() is invoked repeatedly by a DrawerTask.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
90
J2ME J2ME Programming
Timer
AnimationCanvas canvas = new AnimationCanvas();TimerTask task = new DrawerTask(canvas);
Timer timer = new Timer();// Repeat the task each 1 second.timer.schedule(task, 0, 1000);
The timer executes its task reapeatedly, which in turn affects the animation canvas, forcing it to repaint.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
91
J2ME J2ME Programming
Networking
NETWORKING
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
92
J2ME J2ME Programming
Identifying a Machine
Machines are uniquely identified within the Internet by IP address which can exist in two forms:
● familiar Domain Name System associating machines with human readable form, for instance www.cs.vsb.cz;
● alternatively, there is the dotted quad form which is four numbers separated by dots, such as 158.196.157.94.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
93
J2ME J2ME Programming
Identifying an ApplicationAn IP address is not enough to identify a unique server, since many servers can exist on one machine. Each IP machine also contains ports, and when a client or a server is set up, a port must be chosen.
The port is not a physical location in a machine, but a software abstraction. Typically, each service is associated with a unique port number on a given server machine.
25 80 443
eximapache
Net
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
94
J2ME J2ME Programming
URIConnector's methods accept a URI. The general form of the name parameter is as follows:
<scheme>:<address>;<parameters>
● scheme identifies how the connection is made, for example socket, http, file, datagram, ...,
● address identifies what to connect to,● parameters identify other information required by the
scheme to establish a connection, such as a connection speed.
Some examples of URIs are shown in the following list:● http://www.cs.vsb.cz/j2me/images/logo.png● socket://conference.chat.org:531● datagram://<host>:<port>● comm:<port>;<options>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
95
J2ME J2ME Programming
Generic Connection Framework
Connection InputConnection
OutputConnection
DatagramConnection
ContentConnection
StreamConnection
The Generic Connection Framework (GCF) provides the foundation for all network communications within the J2ME architecture. Within the configuration layer the GCF interface is defined along with a number of basic interfaces. The GCF provides no protocol implementations.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
96
J2ME J2ME Programming
HTTP Networking
HttpConnection interface defines necessary methods and constants for an HTTP connection.
The Connector.open() method opens a URL, reads and processes headers, and returns an HttpConnection object. When the input stream is opened, data sent by HTTP server can be read.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
97
J2ME J2ME Programming
Open HTTP Connection
String url = "http://...";HttpConnection connection = (HttpConnection)Connector.open(url);
int response = connection.getResponseCode();if (response != HttpConnection.HTTP_OK) throw new IOException("HTTP response code: " + response);
long length = connection.getLength();InputStream input = connection.openInputStream();...
HTTPConnection processes headers automaticaly. Response code should be tested before an input stream is opened. Amount of available data can be obtained by the getLength() method.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
98
J2ME J2ME Programming
Open HTTPS Connection
HTTPS is the secure version of HTTP. It is usually implemented using TLS v1.0 or SSL v3.0. They offer encryption, source authentication, and data integrity as means to protect information exchanged over insecure, public networks.
String url = "https://...";HttpsConnection connection = (HttpsConnection)Connector.open(url);
SecurityInfo info = connection.getSecurityInfo();Certificate certificate = info.getServerCertificate();
InputStream input = connection.openInputStream();...
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
99
J2ME J2ME Programming
Socket Connection
String uri = "socket://" + name + ":" + port;StreamConnection connection = (StreamConnection) Connector.open(uri, Connector.READ_WRITE);InputStream input = connection.openInputStream();OutputStream output = connection.openOutputStream();
// Send a message.String outgoing = ...output.write(outgoing.getBytes());// Receive a response.byte buffer[] = new byte[SIZE];int read = input.read(buffer);
Establish a socket connection using Connector and read/write data using associated input/output streams.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
100
J2ME J2ME Programming
Socket Connection Server
ServerSocket server = new ServerSocket(port);while (true) { Socket client = server.accept(); RequestHandler handler = new RequestHandler(client); handler.start();}
The ServerSocket listens to traffic on given port on localhost. The accept() method returns a socket representing client side.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
101
J2ME J2ME Programming
Server's Request Handler
public class EchoRequestHandler extends Thread { public void run() { try { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); int read; byte data[] = new byte[BUFFER_SIZE]; while ((read = input.read(data)) != -1) { output.write(data, 0, read); output.flush(); } } ...
In order to ensure handling of multiple clients, the request handler is executed by an independent thread of execution.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
102
J2ME J2ME Programming
AntAnt is a platform-independent scripting tool that enables to construct build scripts in much the same fashion as the make tool in C or C++.
Apache Ant is a Java-based build tool. In theory, it is kind of like make, without wrinkles.
Ant documentation
Ant uses an XML buildfile, usually called build.xml. Each buildfile contains one project and at least one (default) target.
Source: http://www.ii.uni.wroc.pl/~nthx/java/ant.html
<?xml version="1.0" ?><project name="trivial" default="idle"> <target name="idle"> </target></project>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
103
J2ME J2ME Programming
The <project> TagThe <project> tag is root element of the Ant buildfile and has three attributes: name, default and basedir. Optionally, a description for the project can be provided as a top-level <description> element.
Source: http://www.ii.uni.wroc.pl/~nthx/java/ant.html
<?xml version="1.0" ?><project name="trivial" default="compile" basedir="."> <description> This is a demo project ... </description> ... <target name="compile"> ... </target></project>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
104
J2ME J2ME Programming
The <target> TagThe <target> tag defines a logical target that should be attained. Each <target> can depend on other <target>. Ant's depends attribute only specifies the order in which targets should be executed. It does not affect whether the target that specifies the dependency gets executed if the dependent target did not (need to) run.
Source: http://ant.apache.org/manual
<?xml version="1.0" ?><project name="Trivial" default="package"> <target name="deploy" depends="package"> </target> <target name="package" depends="compile"> </target> <target name="compile"> </target></project>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
105
J2ME J2ME Programming
Ant TasksA task is a piece of code that can be executed. There is a set of built-in tasks, along with a number of optional tasks, but it is also very easy to write user-defined task.
Source: http://ant.apache.org/manual
<project name="anttest" default="package"> <target name="compile"> <javac srcdir="src" destdir="dest" debug="on"/> </target> <target name="package" depends="compile"> <jar destfile="package.jar" basedir="dest"/> </target></project>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
106
J2ME J2ME Programming
Ant PropertyA project can have a set of properties. A property has a nameand a value. Properties may be used in the value of task attributes. This is done by placing the property name between "${" and "}" in the attribute value.
Source: http://ant.apache.org/manual
<property name="src" value="src"/><property name="dest" value="dest"/>
<target name="compile"> <javac srcdir="${src}" destdir="${dest}"/></target><target name="package" depends="compile"> <jar destfile="package.jar" basedir="${dest}"/></target>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
107
J2ME J2ME Programming
Ant Path-like StructuresAnt contains powerful tags enabling manipulation of path-like structures.
Source: http://ant.apache.org/manual
<javac srcdir="${src.dir}"> <classpath> <pathelement location=".../classes"/> <pathelement path="${utils.jar}:${db.jar}"/> <fileset dir="${lib.dir}"> <include name="**/*.jar"/> </fileset> <dirset dir="${build.dir}"> <include name="**/classes"/> <exclude name="**/*Test*"/> </dirset> </classpath></javac>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
108
J2ME J2ME Programming
Ant ReferencesAny project element can be assigned an identifier using its idattribute. In most cases the element can subsequently be referenced by specifying the refid attribute on an element of the same type.
Source: http://ant.apache.org/manual
<path id="class.path"> <pathelement location=".../classes"/> <pathelement path="${utils.jar}:${db.jar}"/> <fileset dir="${lib.dir}"> <include name="**/*.jar"/> </fileset></path>
<javac srcdir="${src.dir}"> <classpath refid="class.path"/></javac>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
109
J2ME J2ME Programming
Ant ConditionSets a property if the condition holds true. The property value is set to true by default; otherwise, the property is not set. The value can be set to something other than the default by specifying the value attribute.
Source: http://ant.apache.org/manual
<condition id="javamail.complete"> <and> <available classname="javax.....DataHandler"/> <available classname="javax.mail.Transport"/> </and></condition>
Note: There is number of predefined conditions available in Ant: and, or, not, uptodate, os, equals, isset, istrue, isfalse, http, socket, contains, filesmatch, isreference, length, ...
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
110
J2ME J2ME Programming
Ant File Manipulation TagsAnt defines several file-manipulation tags. They enable to execute standard file operations, such as creating, removing, copying, testing, etc.
Source: http://ant.apache.org/manual
<target name="clean"> <delete failonerror="false"> <fileset dir="${dest.dir}"> <include name="**/*.class"/> <include name="**/*.jar"/> </fileset> </delete></target>
Note: Except the delete tag, there is number of another file-related tags: checksum, concat, copy, get, mkdir, move, patch, sync, tempfile, touch, ...
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
111
J2ME J2ME Programming
Ant Execution TagsSometimes it is necessary to execute an external, OS dependent process. Ant enables to manipulate external processes.
Source: http://ant.apache.org/manual
<target name="preverify" depends="compile"> <exec executable="${j2me.home.dir}/bin/preverify"> <arg value="-classpath"/> <arg pathref="class.path"/> <arg line="-d ."/> <arg value="demo"/> </exec></target>
Note: Except the exec tag, there is number of another process-related tags: ant, java, parallel, sequential, sleep, waitfor, ...
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
112
J2ME J2ME Programming
Ant Task DefinitionAnt uses the <taskdef> tag to add a task definition to the current project. The newly defined task can be used in the current project.
Source: http://ant.apache.org/manual
<taskdef name="sms" classname="....SMSTask"/>
<sms to="+420603..." message="..."/>
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
113
J2ME J2ME Programming
Overview of Ant TasksAnt defines large number of tasks. They can be divided into the following categories:
● archive,● compile,● deployment,● documentation,● execution,● logging,● mail,● .NET,● pre-processor,● property,● remote,● testing.
Source: http://ant.apache.org/manual
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
114
J2ME J2ME Programming
Bluetooth
The Bluetooth wireless connectivity technology was originally envisioned in 1994 by the Swedish phone equipment maker Ericsson as a way for mobile devices to communicate with each other at short ranges, up to 10 meters. In 1998, Ericsson, IBM, Intel, Nokia, and Toshiba formed the Bluetooth Special Interest Group consortium to develop a royalty-free, open specification for short-range wireless connectivity.
Since then, more than 2000 companies have joined the Bluetooth SIG, including virtually all manufacturers of phone, computer, and PDA equipment.
Source: http://developers.sun.com/techtopics/mobility/midp/articles/bluetooth1
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
115
J2ME J2ME Programming
Bluetooth Network TopologyBluetooth-enabled devices are organized in groups called piconets. A piconet consists of a master and up to seven active slaves. A master and a single slave use point-to-point communication; if there are multiple slaves, point-to-multipoint communication is used. A master unit is the device that initiates the communication. A device in one piconet can communicate to another device in another piconet, forming a scatternet.
Source: http://developers.sun.com/techtopics/mobility/midp/articles/bluetooth1
m
s
s
ss&m
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
116
J2ME J2ME Programming
Bluetooth ProfilesBluetooth profiles are intended to ensure interoperability among different devices and applications. A profile defines the roles and capabilities for specific types of applications.
● Generic Access Profile
Defines connection procedures, device discovery, and link management. At a minimum all Bluetooth devices must support this profile.
● Service Discovery Application and Profile
Defines the features and procedures for an application to discover services registered in other devices.
● Serial Port ProfileDefines the requirements for Bluetooth devices that need to set up connections that emulate serial cables.
● ...Source: http://developers.sun.com/techtopics/mobility/midp/articles/bluetooth1
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
117
J2ME J2ME Programming
Java APIs for Bluetooth Wireless Technology
While Bluetooth hardware has advanced, there has been no standardized way to develop Bluetooth applications, until JSR 82came into play. It hides the complexity of the Bluetooth protocol stack behind a set of Java APIs that allow you to focus on application development rather than the low-level details of Bluetooth.
Like all JSRs, the Java APIs for Bluetooth are being developed through the Java Community Process. Its expert group has members representing 20 companies. The final specification is available for download.
JSR 82 consists of two optional packages: the core Bluetooth API and the Object Exchange (OBEX) API. The latter is transport-independent and can be used without the former.
Source: http://developers.sun.com/techtopics/mobility/midp/articles/bluetooth1
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
118
J2ME J2ME Programming
Device ManagementThe Java Bluetooth APIs contain the classes LocalDevice and RemoteDevice, which provide the device-management capabilities defined in the Generic Access Profile.
● The LocalDevice class retrieves the device's type and the kinds of services it offers.
● The RemoteDevice class represents a remote device and provides methods to retrieve information about the device, including its Bluetooth address and name.
LocalDevice local = LocalDevice.getLocalDevice();String address = local.getBluetoothAddress();String name = local.getFriendlyName();
RemoteDevice remote = RemoteDevice.getRemoteDevice...String address = remote.getBluetoothAddress();String name = remote.getFriendlyName();
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
119
J2ME J2ME Programming
Requesting a Connection
LocalDevice local = LocalDevice.getLocalDevice();UUID uuid = new UUID("00112233445566778899AABBCCDDEEFF", true);DiscoveryAgent agent = local.getDiscoveryAgent();String url = agent.selectService(uuid, ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);if (url == null) throw new IOException("Device not found");StreamConnection connection = Connector.open(url);InputStream input = connection.openInputStream();
Bluetooth services are uniquely identified by a 128-bit Universally Unique Identifier (UUID). Every service has a UUID including generic low-level protocols and profiles.
Note: For convenience the Service Discovery Protocol allows the use of 16-bit or 32-bit alias (“short”) UUIDs.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
120
J2ME J2ME Programming
Offering a Connection
LocalDevice local = LocalDevice.getLocalDevice();local.setDiscoverable(DiscoveryAgent.GIAC);UUID uuid = new UUID("00112233445566778899AABBCCDDEEFF", true);String url = "btspp://localhost:" + uuid.toString();StreamConnectionNotifier notifier = Connector.open(url.toString());StreamConnection connection = notifier.acceptAndOpen();InputStream input = connection.openInputStream();OutputStream output = connection.openOutputStream();
The acceptAndOpen() method makes the server ready to accepth a client connections. It blocks until the server accepts the client connection.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
121
J2ME J2ME Programming
Device Discovery
Because wireless devices are mobile they need a mechanism that allows them to find other devices and gain access to their capabilities. The DiscoveryAgent class and DiscoveryListener interface provide the necessary discovery services.
The DiscoveryAgent class provides methods to perform device and service discovery. A local device must have only one DiscoveryAgent object.
LocalDevice local = LocalDevice.getLocalDevice();DiscoveryAgent agent = local.getDiscoveryAgent();
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
122
J2ME J2ME Programming
Discovery ListenerThe DiscoveryListener interface allows an application to receive device discovery and service discovery events.
DiscoveryAgent
startInquiry()cancelInquiry()searchService()
DiscoveryListener
deviceDiscovered()inquiryCompleted()serviceDiscovered()serviceSearchCompleted()
1
public class Discoverer implements DiscoveryListener { ... public void startDiscovery() { agent = local.getDiscoveryAgent(); agent.startInquiry(DiscoveryAgent.GIAC, this); }
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
123
J2ME J2ME Programming
Discovery Listener
The inquiryCompleted() method is called by the implementation when the device inquiry has completed.
public void deviceDiscovered(RemoteDevice device, DeviceClass type) { ...
public void inquiryCompleted(int status) { if (status == INQUIRY_COMPLETED) ... if (status == INQUIRY_TERMINATED) ... if (status == INQUIRY_ERROR) ...
When a device is discovered the deviceDiscovered() method is called by an implementation. It may be called many times.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
124
J2ME J2ME Programming
Connection ProtocolsJSR 82 specifies support for three communication protocols:
● L2CAPThe Logical Link Control and Adaption Protocol (L2CAP) is the lowest level data transmission protocol in the Bluetooth stack. Data is sent and received in packets, whose maximum size is defined by the Maximum Transmission Unit (MTU).
● RFCOMMThe RFCOMM layer provides a stream–based connection protocol analogous to serial port communication and is the basis of the Serial Port Profile (SPP).
● OBEXOBEX is the highest level communication protocol available in JSR 82, sitting on top of RFCOMMM and L2CAP. OBEX, the Object Exchange protocol, can be used to send and receive complete objects (e.g. files, images etc).
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
125
J2ME J2ME Programming
Service Discovery
The inquiryCompleted() method is called by the implementation when the device inquiry has completed.
DiscoveryAgent agent;
agent.startInquiry
public void inquiryCompleted(int status) { if (status == INQUIRY_COMPLETED) ... if (status == INQUIRY_TERMINATED) ... if (status == INQUIRY_ERROR) ...
The DiscoveryAgent class also encapsulates the functionality provided by the service discovery application profile.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
126
J2ME J2ME Programming
Service Discovery
The inquiryCompleted() method is called by the implementation when the device inquiry has completed.
public void deviceDiscovered(RemoteDevice device, DeviceClass type) { ...
public void inquiryCompleted(int status) { if (status == INQUIRY_COMPLETED) ... if (status == INQUIRY_TERMINATED) ... if (status == INQUIRY_ERROR) ...
When a device is discovered the deviceDiscovered() method is called by an implementation. It may be called many times.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
127
J2ME J2ME Programming
Offering a Bluetooth Service
The steps involved in registering a service are defined in the Service Discovery Protocol (SDP), which is part of the Bluetooth Specification, and are as follows:
● create a service record,● add the service record to the Service Discovery Database,● set security measures associated with connections to
clients,● accept connections from clients.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
128
J2ME J2ME Programming
Offering a Bluetooth Service
Each Bluetooth service offered by a host is represented by a Service Record in the Service Discovery Database (SDDB). To connect to a service a client obtains a Service Record from the server and uses the information therein to connect to the service.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
129
J2ME J2ME Programming
XML Processing
From a developer’s perspective, Java makes an application portable among platforms and XML makes data portable among applications.
Sou
rce
: W
irele
ss Java
Pro
gra
mm
ing w
ith Java
2 M
icro
Edit
ion
For traditional Java applications, several Java-based XML parsers are available from different software vendors. These XML parsers provide a rich set of features for dealing with XML data within enterprise applications. But these parsers are too big for J2ME MIDP applications.
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
130
J2ME J2ME Programming
Event- and Tree-based XML Parser
Two types of interfaces are available for parsing XML documents.● Event-based
Reports parsing events directly to the application through callback methods. It provides a serial-access mechanism for accessing XML documents. Applications that use a parser’s event-based interface need to implement the interface’s event handlers to receive parsing events.
● Tree-basedReads an entire XML document into an internal tree structure in memory. Each node of the tree represents a piece of data from the original document. It allows an application to navigate and manipulate the parsed data quickly and easily.
Sou
rce
: W
irele
ss Java
Pro
gra
mm
ing w
ith Java
2 M
icro
Edit
ion
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
131
J2ME J2ME Programming
XML Parsers
There are three models of XML parsers.● Push
The parser generates a transient flow of events. Each caught event is handled immediately and the relevant information is passed on with the event. A push parser reads through an entire XML document. As it encounters various parts of the document, it notifies a listener object.
● ModelFirst, the parser creates a tree-like data structure, that models the XML source document; then the application walks through the tree. A model parser reads an entire document and creates a representation of the document in memory.
● PullA pull parser reads a small amount of a document at once. The application drives the parser through the document by repeatedly requesting the next piece.
Sou
rce
: A
dd X
ML
pars
ing t
o y
our
J2M
E a
pplic
ati
ons
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
132
J2ME J2ME Programming
Push Parser
The javax.xml.parsers.SAXParserFactory enables applications to configure and obtain a SAX-based parser.
SAXParserFactory factory = SAXParserFactory.newInstance();factory.setValidating(true);SAXParser parser = factory.newSAXParser();
The SAXParser.parse() method starts the parse process of givent input data.
InputStream input = ...CountHandler handler = new CountHandler();parser.parse(input, handler);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
133
J2ME J2ME Programming
SAX Event HandlerThe org.xml.sax.helpers.DefaultHandler is default imple-mentation of class receiving and parsing events.
public class CountHandler extends DefaultHandler { ... public void startDocument() throws SAXException { count = 0; }
public void startElement(String nameSpace, String localName, String qualifiedName, Attributes attributes) throws SAXException { if (localName.equals(wanted)) count++; }}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
134
J2ME J2ME Programming
Pull ParserPull parsing makes it easier to deal with state changes because you can pass parser to different functions, which can maintain their own state variables.
InputStreamReader reader = ...XmlParser parser = new XmlParser(reader);
while(true) { ParseEvent event = parser.read(); int type = event.getType(); String name = event.getName(); if (type == Xml.START_TAG && name.equals(wanted)) { count++; continue; }}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
135
J2ME J2ME Programming
DOM ParserA DOM is the entire document tree kept in memory with each tag separated into Node objects.
XmlParser parser = ...Document document = new Document();document.parse(parser);
Element root = document.getRootElement();int children = root.getChildCount();for (int i = 0; i < children; i++) { Element child = root.getElement(i); String name = child.getName(); if (name.equals(wanted)) count++;}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
136
J2ME J2ME Programming
Pull Parser
...
while(true) { ParseEvent event = parser.read(); int type = event.getType(); String name = event.getName(); if (type == Xml.START_TAG && name.equals(wanted)) { count++; continue; } if (type == Xml.END_DOCUMENT) break;}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
137
J2ME J2ME Programming
XML Serializer
All XML generating can be done by using XmlSerializer interface.XmlPullParserFactory factory = XmlPullParserFactory.newInstance();XmlSerializer serializer = factory.newSerializer();
serializer.setOutput(...);serializer.startDocument("utf-8", Boolean.TRUE);serializer.startTag(namespace, "course") .text("J2ME") .endTag(namespace, "course");serializer.endDocument();
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
138
J2ME J2ME Programming
Programming Strategies
The limitations that are inherent in small devices require to changethe way in which applications are designed and coded.
● If in Doubt, Do Not Use Java
The strategy to consider is simple, if perhaps a bit heretical. One should avoid using Java until it is sure that it meets an application requirements—not only in features, but in performance.
● Move Computation to the Server
Avoid running computationally intensive tasks on small device. Instead, let a server computer run them.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
139
J2ME J2ME Programming
Build Smaller Applications
A smaller application takes up less memory on the device and requires less time to install.
● StartupA significant part of the startup time is spent uncompressing, verifying and otherwise preparing the individual classes that an application requires. If startup time is an issue, try to build an uncompressed JAR.
● ObfuscationAn obfuscator makes the code and the symbolic information in your class files harder to read by converting identifiers to short, undistinguished character sequences and by performing other tricks that still result in a legal class file. A side effect of the obfuscation is a reduction in the size of the final class file.uesting the next piece.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
140
J2ME J2ME Programming
Use Less Memory at Run Time
The runtime memory capacity of a small computing device can be quite limited.
● Scalar typesEach object must be allocated from the runtime memory
heap. The object’s constructor runs as part of that allocation process. Therefore, each object impacts an application’s performance as well as the amount of memory that it requires. To reduce the number of objects that are allocated, consider using scalar types—the non-object types such as int and boolean—in place of objects whenever possible.
● Help the garbage collectorBe sure to help the garbage collector do its work by setting object references to null whenever you are finished with them. Clearing out object references make it easier for the garbage collector to find and reclaim unreferenced objects.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
141
J2ME J2ME Programming
Use Lazy Instantiation
To reduce overall and peak memory usage is to only allocate objects as they are needed. The technique is usually refered to as lazy instantiation.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
class LazyInitialization { private Vector items;
public Vector getItems() { if (items == null) items = new Vector(); return items; }}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
142
J2ME J2ME Programming
Release Resources Early
Whether writing for small devices or for desktop systems, it makes sense to release resources as soon as possible.
● Do not hang onto them longer than necessaryThis frees the resource for use by another application, but
it also enables the system to free any memory associated with that resource.
● Do not depend on finalizersFinalizers might never run, and as we will see later, they
are not even supported by some Java interpreters. Always provide methods for explicitly freeing the resources, and document their use.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
143
J2ME J2ME Programming
Reuse Objects
A technique that can pay good dividends is to reuse objects insteadof continually allocating and abandoning them.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
class ReuseObject { private Vector items;
public void initialize() { if (items == null) items = new Vector(); }
public void deinitialize() { items.removeAllElements(); }}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
144
J2ME J2ME Programming
Avoid Exceptions
Java’s built-in support for exception handling is extremely convenient. Exceptions are sometimes overused, however. In general, you want to reserve exceptions for unusual or unexpected (exceptional) situations.
Errors that are expected to occur in the normal course of running an application should be handled through other means. By avoiding exceptions, you can reduce the size of the class files and also reduce the number of objects that are allocated (because each exception throws an exception object).
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
145
J2ME J2ME Programming
Use Local Variables
It is generally slower to access class members than to access local variables. It also makes sense when dealing with arrays. Each time an array element is accessed, the Java interpreter performs a bounds check in order to ensure that the array index is valid.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
char[] buffer = ...for (int i = 0; i < buffer.length; i++) { char ch = buffer[i]; if (ch == '\r' || ch == '\n') ... else if (ch >= '0' && ch <= '9') ...}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
146
J2ME J2ME Programming
Optimize Loops
Avoid repeated invoking of a method if it is obvious that the result is the same. Cache that value.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
Vector items = ...int size = items.size();for (int i = 0; i < size; i++) { ...}
String command = ...int length = command.length();for (int i = 0; i < length; i++) { ...}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
147
J2ME J2ME Programming
Avoid String Concatenation
Java makes it easy to build strings by concatenation. String concatenation involves creating a new StringBuffer object, calling its append() method, and then calling its toString() method in order to obtain the final string. The better solution is to do most of the work yourself.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
String concatStrings(String[] strings) { StringBuffer result = new StringBuffer(); for (int i = 0; i < strings.length; i++) result.append(strings[i]);
return result.toString();}
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
148
J2ME J2ME Programming
Use Threads, but Avoid Synchronization
Threads are an important part of Java, and your application should take advantage of them whenever possible. The usual rule is that any operation that will take more than a tenth of a second to run should run on a separate thread so that it will not block the user interface.
When using threads, controled access to shared data have to be ensured. It is performed using the synchronized keyword. But there is an overhead associated with handling of a lock.
Sou
rce
: M
obile
Info
rmati
on D
evi
ce P
rofile
for
Java
2 M
icro
Edit
ion
public Vector getItems() { if (items == null) { synchronized (this) { if (items == null) items = new Vector(); } ...
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
149
J2ME J2ME Programming
Use Buffered I/O
Don’t read bytes one at a time from a stream, and don’t write them out one at a time. Although the stream classes provide methods that read and write a single byte, you should avoid them if at all possible. It will almost always be more efficient to read or write a whole array full of data.
Sou
rce
: W
irele
ss Java
: D
eve
lopin
g w
ith Java
2 M
icro
Edit
ion
int read, total = 0;byte buffer[] = new byte[1024];do { read = input.read(buffer); total += read;}while (read == buffer.length);
by Roman Szturc2006
Department of Computer ScienceVŠB-Technical University of Ostrava
150
J2ME J2ME Programming
Separate the Model
When writing an application for small devices, one have to adapt a user interface to each device’s form factor. A common technique for dealing with this problem is to separate the logic of the application from the code that controls the presentation.
Separating models and presentations takes some effort. However, the separation will make it easier to adapt—or possibly rewrite—user interface code to work on different devices. Separating the model means that there will not be a need to rewrite the entire application.
Recommended