• No results found

Mobile Application Development. MIDP & GUI Programmierung

N/A
N/A
Protected

Academic year: 2021

Share "Mobile Application Development. MIDP & GUI Programmierung"

Copied!
25
0
0

Loading.... (view fulltext now)

Full text

(1)

J2ME – MIDlets

Mobile Application Development

MIDP & GUI Programmierung

Christoph Denzler

Fachhochschule Nordwestschweiz Institut für Mobile und Verteilte Systeme

Lernziele

Sie

wissen wie ein MIDlet kontrolliert wird.

kennen die GUI Komponenten des lcdui

Packages

können ein GUI konzipieren und planen

können eine MVC Architektur entwerfen und

implementieren.

haben Erfahrungen gesammelt bei der

(2)

IMVS, Ch. Denzler

Heute

Was ist ein MIDlet?

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

Entwurf einer MVC Architektur für die Fallstudie

MIDP, GUI Design 3

Heute

Was ist ein MIDlet?

Überblick

Applikationsmodell

HelloWorld Beispiel

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

(3)

IMVS, Ch. Denzler

What is a MIDlet

MIDP applications are called

MIDlets

The class

javax.microedition.midlet.MIDlet

allows the platform to control a MIDP application.

MIDP does not support the running of traditional

applications that use a static main method as their entry

point.

Its entry point is a class that extends the

javax.microedition.midlet.MIDlet class.

MIDP defines an application lifecycle model similar to the applet

model.

MIDP, GUI Design 5

What is a MIDlet Suite

One or more MIDlets are packaged together into what is

referred to as a MIDlet suite.

A MIDlet suite is basically

a standard JAR (Java archive) file and

Class files

Resource files (e.g. icons, image files, string resources) A manifest describing the JAR contents

a separate file called an application descriptor (JAD).

Midlets in a suite share

Runtime object heap Persistent storage

(4)

IMVS, Ch. Denzler

Heute

Was ist ein MIDlet?

Überblick

Applikationsmodell

HelloWorld Beispiel

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

Entwurf einer MVC Architektur für die Fallstudie

MIDP, GUI Design 7

Application Management Software

The Application Management Software (AMS)

manages the MIDlets.

The AMS is a part of the device's operating

environment and guides the MIDlets through

their various states during the execution

process.

(5)

IMVS, Ch. Denzler

MIDP State Management

The MIDlet Life Cycle

Paused

Active

Destroyed

pauseApp startApp destroyApp destroyApp new Midlet()

MIDP, GUI Design 9

MIDP State Management

State transitions initiated by application management software protected void startApp()

Midlet is (re)-started

May be called several times – use flag to decide whether first call or not Midlet initialization is usually done in the constructor

protected void pauseApp()

Midlet should release as many resources as possible Midlet can still receive asynchronous events (e.g. timer) protected void destroyApp(boolean unconditional)

Normal way to terminate a midlet. If unconditional == false the midlet may throw a MIDletStateChangeException to signal that it would like to stay alive Midlet should release its resources and save any persistent data

(6)

IMVS, Ch. Denzler

MIDP State Management

State transitions initiated by MIDlet notifyDestroyed()

Informs manager that midlet released its resources and saved data. destroyApp() will NOTbe called

Rule: call destroyApp() to perform cleanup before notifyDestroyed(). notifyPaused()

Informs manager that midlet entered the paused state. pauseApp() will NOTbe called

In the future, startApp() or destroyApp() will be called. resumeRequest()

Request to become active again (e.g. after a timer event)

MIDP, GUI Design 11

The MIDlet Class

abstract class MIDlet {

// called by the platform

abstract void startApp();

abstract void pauseApp();

abstract void destroyApp();

// can be called by the subclass

void notifyPaused();

void notifyDestroyed();

// plus various property accessors

}

(7)

IMVS, Ch. Denzler

Heute

Was ist ein MIDlet?

Überblick

Applikationsmodell

HelloWorld Beispiel

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

Entwurf einer MVC Architektur für die Fallstudie

MIDP, GUI Design 13

Simple HelloWorld Midlet

package hello;

import javax.microedition.midlet.*; import javax.microedition.lcdui.*;

public class HelloWorld extends MIDlet implements CommandListener { private Command cmdExit; // the exit command

private TextBox tb; public HelloWorld() {

cmdExit = new Command("Exit", Command.SCREEN, 2); tb = new TextBox("Hello MIDlet", "Hello World", 256,

TextField.ANY); tb.addCommand(cmdExit); tb.setCommandListener(this); }

(8)

IMVS, Ch. Denzler

Simple HelloWorld Midlet (cont.)

public void startApp() {

Display.getDisplay(this).setCurrent(tb); }

public void pauseApp() { }

public void destroyApp(boolean unconditional) { cleanup(); } public void commandAction(Command c, Displayable s) {

if (c == cmdExit) { destroyApp(true); notifyDestroyed(); } } }

MIDP, GUI Design 15

Heute

Was ist ein MIDlet?

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

(9)

IMVS, Ch. Denzler

User Interface Design

Use a Screen Map

Split the application into views

Make the application structure simple

Define a main screen for the application

Clarify the interactions between each view

Consider the navigation throughout the application

Ensure that the users can always return to where they started

MIDP, GUI Design 17

User Interface Design (cont)

Take different screen sizes into account

Do not use hard coded

UI coordinates UI size

Get screen size

Use getHeight()and getWidth()methods of the Canvas

class to get the size of the Canvas.

Note

Set canvas in full screen mode

Use the setFullScreenMode(true) method

(10)

IMVS, Ch. Denzler

Key Handling

Be Aware that

keypad layouts vary a lot

key mappings may differ from device to device

Key Handling Design

separate the control code from the application logic

enables the changing of the control handlers without modifying the application

use the key codes and game actions defined by the MIDP specification public void keyPressed( int keyCode ) {

int gameAction = getGameAction( keyCode ); switch( gameAction ) { case Canvas.DOWN: // move down break; case Canvas.LEFT: // move left break; .. }

MIDP, GUI Design 19

Modular Architecture

Separate View from Logic

Apply MVC Pattern

Separate application specifics from generic components

e.g. by designing an abstract interface

Separate device specific from application

e.g. by designing an abstract interface

Separate localization resources from code

(11)

IMVS, Ch. Denzler

Heute

Was ist ein MIDlet?

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

Übersicht

High-Level GUI Komponenten

List, Alert, TestBox Form & Items

Low-Level GUI Komponenten

Entwurf einer MVC Architektur für die Fallstudie

MIDP, GUI Design 21

The MIDP User Interface Library

Display Model

Commands

The High-Level API

Screens

Form, TextBox, List, Alert, Item

The Low-Level API

Canvas, Graphics, CustomItem

(12)

IMVS, Ch. Denzler

MIDP User Interface

Requirements

Not too many short-lived objects

Usable without pointer device / touch screen Compatibility with native phone applications

=> neither AWT nor Swing (nor SWT) were an option !

Display Types

High-level API, only abstract description of UI

Look-and-feel matches the device

Forms, Menus, Commands, Lists, Alerts

Low-level API ("Gaming")

Canvas, native drawing primitives

MIDP, GUI Design 23

MIDP UI Class Hierarchy

Display

Displayable

Screen

TextBox

List Alert Form

Canvas Item 0..1 CommandListener Command 0..1 * * * * 1 Ticker 0..1 *

(13)

IMVS, Ch. Denzler

MIDP User Interface

Screen Model

Each MIDlet consists of several screens (Displayable) On the display one Screen is displayed at each point of time The application sets and resets the current screen

Commands

Abstract Commands

Specified by a type and a priority

Can be implemented as buttons, menus, … Have to be added to each screen

Are handled in a command listener (also associated with a screen)

Display Displayable 0..1 CommandListener Command * * * 0..1

MIDP, GUI Design 25

Display

Setting Displayable Objects

Displayable getCurrent();

Returns the current displayable object void setCurrent(Displayable d)

makes next displayable object visible (may be delayed) void setCurrent(Alert alert, Displayable next)

shows the alert and after its dismiss the displayable d (may be delayed) void setCurrentItem(Item item)

makes form which contains item as next displayable

Display Access

(14)

IMVS, Ch. Denzler

Display (cont.)

setCurrent change will typically not take effect immediately Change of display occurs between event delivering calls

(not guaranteed before next event) Consequences

Call to getCurrent after a setCurrent is unlikely to return the set displayable, getCurrent returns the visible displayable

Calls to setCurrent are not queued

isShown on a Displayable may return false although it has been set with setCurrent

If after a call to setCurrent the thread is busy in a blocking operation, then it may be that the UI is not actualized

=> Blocking Operations should be executed in a separate thread! A Canvas offers methods showNotify and hideNotify

MIDP, GUI Design 27

Display (cont.)

Screen Parameters

boolean isColor() int numColors()

Number of colors or graylevels int numAlphaLevels()

Number of alpha levels (transparency of colors) int getColor(int colorSpecifier)

Returns information about foreground/background colors int getBestImageWidth/Height(int imageType)

Returns best image width&height for list/choice/alert images boolean vibrate(int millis)

Returns whether vibrator can be controlled int getBorderStyle(boolean highlighted)

(15)

IMVS, Ch. Denzler

Displayable

Commands void addCommand(Command cmd) void removeCommand(Command cmd) CommandListener void setCommandListener(CommandListener l)

replaces previous installed listeners

the same listener may be installed in several displayable objects

Visibility

boolean isShown()

Checks if the Displayable is actually visible on the display (e.g. MIDlet running, Displayable installed, no system screens)

Title

void setTitle(String title) String getTitle()

Ticker

void setTicker(Ticker t)

setTicker(null) clears the ticker

Ticker getTicker

Ticker ticker =

new Ticker("Select an item"); disp.setTicker(ticker);

disp.addCommand(exitCommand); disp.addCommand(nextCommand);

MIDP, GUI Design 29

Command

Label

String representation, may be ignored (except for SCREEN commands)

Type

SCREEN application defined command, pertained to current screen BACK previous screen, may be mapped on a back button OK confirm data and proceed

CANCEL discarding of current screen EXIT exit request

HELP on-line help request

STOP stop a process visible on the current screen ITEM specific to a particular item on the screen

Priority: >= 1; low = high priority

Nothing is done auto-matically by these commands !!!

(16)

IMVS, Ch. Denzler

CommandListener

Interface

void commandAction(Command c, Displayable d)

Indicates that a command event has occurred on displayable d

Command c may be one which has been added or an implicit List.SELECT_COMMAND of a list.

Implementation

Provided by the application, implemented e.g. as inner class Should return immediately (not necessarily called in a separate

thread)

otherwise, application could block

MIDP, GUI Design 31

Heute

Was ist ein MIDlet?

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

Übersicht

High-Level GUI Komponenten

List, Alert, TestBox Form & Items

Low-Level GUI Komponenten

(17)

IMVS, Ch. Denzler

High-Level LCDUI

Ensure highest portability

Provide a set of standard controls

Make GUI development easy

Offers high level widgets

Standard controls like lists, textbox, etc.

Look-And-Feel is determined by LCDUI implementation

application automatically adapts to runtime environment i.e. application may look different on different devices

Simple user interactions are taken care of by system

E.g. scrolling in a large dialog

No direct access to input devices

data exchange through listeners

Limited capabilities

MIDP, GUI Design 33

MIDP UI High-Level API

Screen

TextBox

List Alert Form

Item

Gauge DateField TextField ImageItem StringItem

ChoiceGroup

* 1

(18)

IMVS, Ch. Denzler

Screen

Screen

Common abstract base class of all high-level user

interface classes

No further methods (since MIDP 2.0)

MIDP, GUI Design 35

List

Functionality

list of choices (string [+ icon]), insert/append/delete scrolling handled by system (no events)

selection using select / go button

Types

IMPLICIT

menu list (=> List.SELECT_COMMAND)

EXCLUSIVE

radio buttons, getSelectedIndex() no events !

MULTIPLE

check boxes, isSelected(int)

(19)

IMVS, Ch. Denzler

TextBox

Functionality

Screen to enter and edit text

Application sets max chars and input constraints TextBox must have an associated command!

new TextBox("Enter ID", "", 10, TextField.NUMERIC);

Modifier PASSWORD UNEDITABLE SENSITIVE NON_PREDICTABLE INITIAL_CAPS_WORD INITIAL_CAPS_SENTENCE

Types ANY (0) EMAILADDR (1) NUMERIC (2) PHONENUMBER (3) URL (4) DECIMAL (5)

MIDP, GUI Design 37

Alert

Functionality

Message screen (optional with image), used for errors /

exceptions

Default Command: Alert.DISMISS_COMMAND (may be

replaced)

getTimeout() / setTimeout(int) [Alert.FOREVER => modal]

Types

ERROR INFO WARNING

ALARM (e.g. reminder, wakeup call) CONFIRMATION

Alert a = new Alert("Oops"); a.setString("something went wrong"); a.setType(AlertType.CONFIRMATION); a.setTimeout(Alert.FOREVER);

(20)

IMVS, Ch. Denzler

Form

Functionality

Combination of different items (images, textfields, gauges, choice groups)

Each item has a label (setLabel / getLabel) An item may be contained in at most one form Scrolling performed by device, no events

Methods

append(Item item) / append(Image image) / append(String str) set(int n, Item item) / insert(int n, Item item)

size() / delete(int n) / get(int n)

setItemStateListener(ItemStateListener listener)

void itemStateChanged(Item item) Called, when an item changes (e.g. text input)

MIDP, GUI Design 39

Items

StringItem

ImageItem

different layouts: center, left, right, newline before, newline after

TextField

similar to text box; with max size & constraints

DateField

types date, time, date_time; setDate / getDate

ChoiceGroup

only exclusive and multiple

Gauge

graphical value display, may be editable

Gauge(String label, boolean interactive, int max, int initial)

Spacer

(21)

IMVS, Ch. Denzler

Heute

Was ist ein MIDlet?

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

Übersicht

High-Level GUI Komponenten

List, Alert, TestBox Form & Items

Low-Level GUI Komponenten

Entwurf einer MVC Architektur für die Fallstudie

MIDP, GUI Design 41

MIDP Low-Level Interface

Low level abstraction

Gives control about positioning of elements

Exact pixel positioning

Control over look-and-feel of UI elements

Direct access to keyboard and input devices

Capturing low-level keyboard events

key pressed key released

Access to device specific properties

Display resolution Color depth Available keys

May limit portability

(22)

IMVS, Ch. Denzler

MIDP Low-Level API

Form Canvas Item * 1 Graphics CustomItem

MIDP, GUI Design 43

Canvas

Drawing

full control, but code must adapt itself to available features

(color, size, ..)

redrawing requested by system with paint(Graphics g) redrawing can be requested by application with repaint

Events

Key Events

keyPressed, keyReleased, keyRepeated Pointer Events

pointerPressed, pointerReleased, pointerDragged Visibility

(23)

IMVS, Ch. Denzler

Canvas

Drawing

full control, but code must adapt itself to available features

(color, size, ..)

redrawing requested by system with paint(Graphics g) redrawing can be requested by application with repaint

Events

Key Events

keyPressed, keyReleased, keyRepeated Pointer Events

pointerPressed, pointerReleased, pointerDragged Visibility

showNotify, hideNotify

MIDP, GUI Design 45

Canvas (cont)

Canvas Properties

Screen

getWidth, getHeight, isDoubleBuffered

Events

hasPointerEvents, hasPointerMotionEvents, hasRepeatEvents

Key Codes

Game Actions:

UP, DOWN, LEFT, RIGHT, FIRE, GAME_A, GAME_B, GAME_C,

GAME_D Key Codes:

KEY_NUM0, …, KEY_NUM9, KEY_POUND (#), KEY_STAR (*)

Support

getKeyCode(action) <-> getGameAction(key) getKeyName(key) => "press F1 to continue"

(24)

IMVS, Ch. Denzler

Graphics

Drawing

drawLine, drawRect, drawRoundRect, drawArc, drawString,

drawImage

fillRect, fillRoundRect, fillArc

Drawing State

setColor / setGrayScale

setStrokeStyle (SOLID / DOTTED) setFont

Clipping

setClip(x, y, w, h), getClipX / getClipY, getClipWidth,

getClipHeight

MIDP, GUI Design 47

Graphics (cont)

Image

getWidth() / getHeight() immutable:

createImage(String resource)

createImage(byte[] data, int offset, int len)

createImage(Image src)

mutable

createImage(int w, int h) => getGraphics()

Font

Font.getFont(face, style, size)

FACE_MONOSPACE, FACE_PROPORTIONAL, FACE_SYSTEM SIZE_LARGE, SIZE_MEDIUM, SIZE_SMALL

(25)

IMVS, Ch. Denzler

CustomItem

Purpose

Allow user to develop her own item controls

Although derived from Item

this is a low-level

class

API very similar to Canvas

class

MIDP, GUI Design 49

Heute

Was ist ein MIDlet?

Entwurf des GUIs der Fallstudie

GUI Komponenten in MIDP

References

Related documents