Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Information Management

Mobile Application Programming

Java 2 Micro Edition


IP-MAD, SS09, Peter Salhofer, FH JOANNEUM

Informationsmanagement

Java Editions

Informationsmanagement

J2ME Overview
Java ME is a collection of technologies and specifications that implementers and developers can choose from and combine to construct a complete Java runtime environment that closely fits the requirements of a particular range of devices and target markets. Each combination is optimized for the memory, processing power, and I/O capabilities of a related category of devices. The result is a common Java platform that takes full advantage of each type of device to deliver a rich user experience. Java ME is divided into configurations, profiles and optional packages.
[http://java.sun.com/javame/technologies/index.jsp#1] 3

Informationsmanagement

J2ME Configurations
Configurations are specifications that detail a virtual machine and a base set of class libraries which provide the necessary APIs that can be used with a certain class of device. They provide the base functionality for a particular range of devices that share similar characteristics, such as network connectivity and memory footprint. The virtual machine is either a full Java Virtual Machine (JVM) or some subset of the full JVM. The set of APIs is customarily a subset of the Java SE APIs. Currently, there are two Java ME configurations: the Connected Limited Device Configuration (CLDC) and the Connected Device Configuration (CDC).
4

Informationsmanagement

Connected Limited Device Configuration (CLDC)


The Connected Limited Device Configuration (CLDC) defines the base set of application programming interfaces and a virtual machine for resourceconstrained devices like mobile phones, pagers, and mainstream personal digital assistants. When coupled with a profile such as the Mobile Information Device Profile (MIDP), it provides a solid Java platform for developing applications to run on devices with limited memory, processing power, and graphical capabilities.
[http://java.sun.com/products/cldc/]

Informationsmanagement

Connected Device Configuration (CDC)


The Connected Device Configuration (CDC), developed within the Java Community Process (JCP), is a framework for using Java technology to build and deliver applications that can be shared across a range of network-connected consumer and embedded devices, including smart communicators, high-end personal digital assistants (PDAs), and set-top boxes.
[http://java.sun.com/products/cdc/]

Informationsmanagement

J2ME Profiles
Profiles complement a configuration by adding more specific APIs to make a complete runtime environment for running applications in a specific device category. A profile is a set of higher-level APIs that further define the application life-cycle model, the user interface, persistent storage and access to devicespecific properties. A widely adopted example is to combine CLDC with the Mobile Information Device Profile (MIDP) to provide a complete Java application environment for mobile phones and other devices with similar capabilities. Currently there are two versions of MIDP: 1.0 and 2.0
[http://java.sun.com/javame/technologies/index.jsp#1] 7

Informationsmanagement

J2ME Optional Packages


Extend the Java ME platform by adding functionality to the technology stack that includes either CLDC or CDC and an associated profile(s). Created to address very specific application requirements, optional packages offer standard APIs for using both existing and emerging technologies such as database connectivity, wireless messaging, multimedia, 3D graphics, and Web Services. Optional packages can be implemented alongside virtually any combination of configurations and profiles.
[http://java.sun.com/javame/technologies/index.jsp#1]

Informationsmanagement

MIDP

Mobile Application Development

Informationsmanagement

MIDlets
All applications for the Mobile Information Device Profile (MIDP) must be derived from a special class, MIDlet. The MIDlet class manages the life cycle of the application. It is located in the package javax.microedition.midlet. MIDlets can be compared to J2SE applets. A MIDlet can exist in four different states: loaded, active, paused, and destroyed. The Application Manager is responsible to manage the MIDlets' life cycle

10

Informationsmanagement

A MIDlet's Life Cycle I

[http://www.developer.com/java/j2me/article.php/10934_1561591_1] 11

Informationsmanagement

Hello World!
public class HelloWorldMidlet extends MIDlet { private Form form; public void startApp() { Display.getDisplay(this).setCurrent(form); } public HelloWorldMidlet() { this.form = new Form("Hello!"); this.form.append("Hello World!"); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } }
12

Informationsmanagement

A MIDlet's Life Cycle II


pauseApp(): application should stop animations and release resources that are not needed while paused. This should avoid resource conflicts with the application running in the foreground and battery consumption. destroyApp(): method provides an unconditional parameter; if it is set to false, the MIDlet is allowed to refuse its termination by throwing a MIDletStateChangeException. MIDlets can request to resume activity by calling resumeRequest().
13

Informationsmanagement

A MIDlet's Life Cycle III


If a MIDlet decides to go to the paused state (programmatically), it should notify the application manager by calling notifyPaused(). In order to terminate (by calling destroyApp(..)), a MIDlet can call notifyDestroyed(). Note that System.exit() is not supported in MIDP and will throw an exception instead of terminating the application.
Note - Some devices might terminate a MIDlet under some circumstances without calling destroyApp(), for example on incoming phone calls or when the batteries are exhausted. Thus, it might be dangerous to rely on destroyApp() for saving data entered or modified by the user.
14

Informationsmanagement

Display
MIDlets can be pure background applications or applications interacting with the user. Interactive applications can get access to the display by obtaining an instance of the Display class. A MIDlet can get its Display instance by calling Display.getDisplay(MIDlet midlet). The Display class and all other user interface classes of MIDP are located in the package javax.microedition.lcdui. The Display class provides a setCurrent() method that sets the current display content of the MIDlet. This method accepts any subclass of Displayable as argument.
15

Informationsmanagement

MIDP GUI Classes

[http://www.developer.com/java/j2me/article.php/10934_1561591_1]

16

Informationsmanagement

javax.microedition.lcdui.StringItem
Constructors
o StringItem(String label, String text) Creates a new StringItem object. o StringItem(String label, String text, int appearanceMode) Creates a new StringItem object with the given label, textual content, and appearance mode.

Appearance Modes
o Item.PLAIN, o Item.BUTTON o Item.HYPERLINK
17

Informationsmanagement

TextField
TextField(String label, String text, int maxSize, int constraints) Creates a new TextField object with the given label, initial contents, maximum size in characters, and constraints. Constraints
o o o o o o ANY EMAILADDR NUMERIC PHONENUMBER URL DECIMAL
See http://java.sun.com/javame/reference/ apis/jsr118/javax/microedition/ lcdui/TextField.html for a detailed description!

18

Informationsmanagement

ImageItem
ImageItem(String label, Image img, int layout, String altText)
Creates a new ImageItem with the given label, image, layout directive, and alternate text string.

ImageItem(String label, Image image, int layout, String altText, int appearanceMode) Creates a new ImageItem object with the given label, image, layout directive, alternate text string, and appearance mode.

19

Informationsmanagement

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, or might have indefinite range (non interactive). The application can control the current value and maximum value. A Gauge may be interactive or non-interactive. Applications may set or retrieve the Gauge's value at any time regardless of the interaction mode. The implementation may change the visual appearance of the bar graph depending on whether the object is created in interactive mode.

20

Informationsmanagement

Gauge II
public Gauge(String label, boolean interactive, int maxValue, int initialValue) Parameters:
label - the Gauge's label interactive - tells whether the user can change the value o maxValue - the maximum value, or INDEFINITE initialValue - the initial value in the range [0..maxValue], or one of CONTINUOUS_IDLE, INCREMENTAL_IDLE, CONTINUOUS_RUNNING, or INCREMENTAL_UPDATING if maxValue is INDEFINITE. o o
[http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Gauge .html] 21

Informationsmanagement

DateField
A DateField is an editable component for presenting date and time (calendar) information Instance of a DateField can be configured to accept date or time information or both of them public DateField(String label, int mode) Parameters:
o label - item label o mode - the input mode, one of DATE, TIME or DATE_TIME o timeZone - a specific time zone, or null for the default time zone
[http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/DateFi eld.html] 22

Informationsmanagement

ChoiceGroup
A ChoiceGroup is a group of selectable elements intended to be placed within a Form. The group may be created with a mode that requires a single choice to be made or that allows multiple choices. ChoiceGroup(String label, int choiceType) or ChoiceGroup(String label, int choiceType, String[] stringElements, Image[] imageElements)
o o o o label - the item's label (see Item) choiceType - EXCLUSIVE, MULTIPLE, or POPUP stringElements - set of strings specifying the string parts of the elements imageElements - set of images specifying the image parts of the elements
[http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/ChoiceGroup.html] 23

Informationsmanagement

Other Screens
Alert List TextBox

24

Informationsmanagement

Alert
An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions. Alert(String title) or Alert(String title, String alertText, Image alertImage, AlertType alertType)
o o o o title - the title string, or null if there is no title alertText - the string contents, or null if there is no string alertImage - the image contents, or null if there is no image alertType - the type of the Alert, or null if the Alert has no specific type
[see: http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Alert.html]

25

Informationsmanagement

List
List(String title, int listType) or List(String title, int listType, String[] stringElements, Image[] imageElements) Parameters:
o title - the screen's title o listType - one of IMPLICIT, EXCLUSIVE, or MULTIPLE o stringElements - set of strings specifying the string parts of the List elements o imageElements - set of images specifying the image parts of the List elements
26

Informationsmanagement

TextBox
TextBox(String title, String text, int maxSize, int constraints) Parameters:
o title - the title text to be shown with the display o text - the initial contents of the text editing area, null may be used to indicate no initial content o maxSize - the maximum capacity in characters. o constraints similar to TextField (see http://java.sun.com/javame/reference/apis/jsr118/jav ax/microedition/lcdui/TextField.html#constraints )

27

Informationsmanagement

Event Handling: Commands


The Command class is a construct that encapsulates the semantic information of an action The command itself contains only information about a command, but not the actual action that happens when a command is activated. The actual action handling code is defined in a CommandListener associated with the event source All Items (Textfield, StringItem,...) as well as all subclasses of Displayable (Screen, Canvas, Form, ...) can be used as containers for commands

28

Informationsmanagement

Commands: Example
public class CommandTestMidlet extends MIDlet implements CommandListener{ private Form form; private final static Command exitCommand = new Command("Exit", Command.EXIT, 1); public CommandTestMidlet() { form = new Form("Command test"); form.addCommand(exitCommand); form.setCommandListener(this); Display.getDisplay(this).setCurrent(form); } public void commandAction(Command command, Displayable displayable) { if (command == exitCommand) { destroyApp(true); } } ...

29

Informationsmanagement

The Command Class


Command(String label, int commandType, int priority) or Command(String shortLabel, String longLabel, int commandType, int priority)
o shortLabel - the command's short label o longLabel - the command's long label, or null if none o commandType - the command's type: BACK, CANCEL, EXIT, HELP, ITEM, OK, SCREEN, and STOP. o priority - the command's priority value: 1,2, ...

commandType and priority are hints for the device to place the command

30

Informationsmanagement

Command Listeners
Depending on whether you are interested in commands registered with Displayable or Item objects you have to provide either a CommandListener or an ItemCommandListener. ItemCommandListener:
o commandAction(Command c, Item item)

CommandListerner:
o commandAction(Command c, Displayable d)

31

Informationsmanagement

MIDP Low Level UI API


Displayable

Canvas

LayerManager

Layer

GameCanvas

Sprite

TiledLayout

32

Informationsmanagement

Canvas
The Canvas class is a base class for writing applications that need to handle low-level events and to issue graphics calls for drawing to the display. It provides the developer with methods to handle game actions, key events, and pointer events (if supported by the device) The paint() method is declared abstract, and so the application must provide an implementation in its subclass.

33

Informationsmanagement

Canvas Example
public class TestCanvas extends Canvas { public TestCanvas() { } protected void paint(Graphics g) { g.setColor(0,0,255); g.fillRect(0,0,this.getWidth(),this.getHeight()); int d = Math.min(this.getHeight(),this.getWidth()); g.setColor(255,255,0); g.fillArc((getWidth()-d)/2, (getHeight()-d)/2,d,d,0,360); } }

34

Informationsmanagement

Canvas: Key Events


Applications receive keystroke events in which the individual keys are named within a space of key codes. Every key for which events are reported to MIDP applications is assigned a key code. Applications may use the getKeyName() method to find a key's name keyPressed(), keyRepeated(), keyReleased() are the key event handler methods and receive the key's code pointerPressed(), pointerDragged(), pointerReleased() are the joystick event handler methods and receive the position of the pointer. The hasPointerEvents() method may be called to determine if the device supports pointer events.

35

Informationsmanagement

Canvas: Key Events Example


private String key = ""; protected void paint(Graphics g) { g.setColor(0,0,255); g.fillRect(0,0,this.getWidth(),this.getHeight()); int r = Math.min(this.getHeight(),this.getWidth()); g.setColor(255,255,0); g.fillArc((getWidth()-r)/2,(getHeight()-r)/2,r,r,0,360); if (!"".equals(key)) { g.setColor(0,0,0); g.drawString(keyName, getWidth()/2, getHeight()/2, Graphics.BASELINE | Graphics.HCENTER);; } } protected void keyPressed(int keyCode) { key = getKeyName(keyCode); repaint(); }

36

Informationsmanagement

GameCanvas
The GameCanvas class provides the basis for a game user interface. In addition to the features inherited from Canvas (commands, input events, etc.) it also provides game-specific capabilities such as an off-screen graphics buffer and the ability to query key status (since games typically run their own game threads in which the query the key status regularly instead of reacting to events). A dedicated buffer is created for each GameCanvas instance. Since a unique buffer is provided for each GameCanvas instance, it is preferable to re-use a single GameCanvas instance in the interests of minimizing heap usage The flushGraphics method is used to write the buffer to the screen
37

Informationsmanagement

Sprite
A Sprite is a basic visual element that can be rendered with one of several frames stored in an Image Different frames can be shown to animate the Sprite. Several transforms such as flipping and rotation can also be applied to a Sprite to further vary its appearance. As with all Layer subclasses, a Sprite's location can be changed and it can also be made visible or invisible.
38

Informationsmanagement

Sprite Frames
The raw frames used to render a Sprite are provided in a single Image object, which may be mutable or immutable. If more than one frame is used, the Image is broken up into a series of equally-sized frames of a specified width and height.

39

Informationsmanagement

Frame Sequence
A Sprite's frame sequence defines an ordered list of frames to be displayed. The default frame sequence mirrors the list of available frames, so there is a direct mapping between the sequence index and the corresponding frame index. This also means that the length of the default frame sequence is equal to the number of raw frames. For example, if a Sprite has 4 frames, its default frame sequence is {0, 1, 2, 3}.
40

Informationsmanagement

Defining Special Frame Sequences


The setFrameSequence allows for specifying a custom sequence of frames By calling nextFrame() each time the display is updated (from the games loop thread) an animation is created

41

Informationsmanagement

Reference Pixel
Sprite inherits various methods for setting and retrieving its location such as setPosition(x,y), getX(), and getY(). These methods all define position in terms of the upper-left corner of the Sprite's visual bounds; however, in some cases, it is more convenient to define the Sprite's position in terms of an arbitrary pixel within its frame, especially if transformations are applied to the Sprite. Therefore, Sprite includes the concept of a reference pixel. The reference pixel is defined by specifying its location in the Sprite's untransformed frame using defineReferencePixel(x,y). By default, the reference pixel is defined to be the pixel at (0,0) in the frame. If desired, the reference pixel may be defined outside of the frame's bounds.
42

Informationsmanagement

Reference Pixel II

43

Informationsmanagement

Sprite Transforms
Various transforms can be applied to a Sprite. The available transforms include rotations in multiples of 90 degrees, and mirrored (about the vertical axis) versions of each of the rotations. A Sprite's transform is set by calling setTransform(transform).
44

Informationsmanagement

Sprite Transforms and Reference Pixel


When a transform is applied, the Sprite is automatically repositioned such that the reference pixel appears stationary in the painter's coordinate system. Thus, the reference pixel effectively becomes the center of the transform operation.

45

Informationsmanagement

TiledLayer
A TiledLayer is a visual element composed of a grid of cells that can be filled with a set of tile images. This class allows large virtual layers to be created without the need for an extremely large Image. This technique is commonly used in 2D gaming platforms to create very large scrolling backgrounds

46

Informationsmanagement

TiledLayer - Tiles
The tiles used to fill the TiledLayer's cells are provided in a single Image object which may be mutable or immutable. The Image is broken up into a series of equally-sized tiles; the tile size is specified along with the Image. Note: While sprite indices start with 0, the index of the first tile is 1. Zero indicates that no tile is associated to a cell

47

Informationsmanagement

Animated Tiles
Animated tiles are created using the createAnimatedTile(int) method, which returns the index to be used for the new animated tile. The animated tile indices are always negative and consecutive, beginning with -1. Once created, the static tile associated with an animated tile can be changed using the setAnimatedTile(int, int) method. There is no animation sequence for animated tiles The collidesWith method allows for easy collision detection between different Layers
48

Informationsmanagement

Cells
The TiledLayer's grid is made up of equally sized cells; the number of rows and columns in the grid are specified in the constructor, and the physical size of the cells is defined by the size of the tiles.

49

Informationsmanagement

LayerManager
The LayerManager manages a series of Layers (Sprites, TileLayers,..). The LayerManager simplifies the process of rendering the Layers that have been added to it by automatically rendering the correct regions of each Layer in the appropriate order. The LayerManager maintains an ordered list to which Layers can be appended, inserted and removed. A Layer's index correlates to its z-order; the layer at index 0 is closest to the user while a the Layer with the highest index is furthest away from the user. The indices are always contiguous; that is, if a Layer is removed, the indices of subsequent Layers will be adjusted to maintain continuity.
50

Informationsmanagement

LayerManger: View Window


The view window controls the size of the visible region and its position relative to the LayerManager's coordinate system. Changing the position of the view window enables effects such as scrolling or panning the user's view. For example, to scroll to the right, simply move the view window's location to the right.

51

Informationsmanagement

Resources
http://java.sun.com/javame/reference/apis.jsp http://java.sun.com/javame/reference/apis/jsr118/ http://developers.sun.com/techtopics/mobility/mid p/articles/gameapi/ J2ME Application Development by Michael Kroll and Stefan Haustein, Sams Publishing (ISBN:0-672-323095-9) see also http://www.developer.com/java/j2me/article.php/10934_1561591_1

52

You might also like