Download j2me Sam Sung - Omieno Kelvin

Document related concepts
no text concepts found
Transcript
1
Agenda
 History
 Java Universe
 Understanding Java ME
 Configuration
 Profile
 Java ME : CLDC
 Java ME : MIDP
2
History
1990: Java started as an internal project at Sun Microsystems
1995: Initial release of JDK 1.0 (applets servlets)
1999: JavaOne conference
Subdivision of Java in
• Java 2 Enterprise Edition (J2EE)
• Java 2 Standard Edition (J2SE)
 Java 2 Micro Edition (Java ME) (successor of Personal Java and
Embedded Java)
 2000/01 First mobile phones with support for J2ME
3
Java Universe
4
What is Java ME?
Java ME : Java 2 Platform, Micro
Edition
 “Java for small devices”
Java ME is downsized version on
J2SE
It is currently restricted to JRE 1.3
features
Divided in configurations, profiles
and optional APIs/JSRs
5
Existence of Java ME
In the early 1990s, Sun Microsystems created a new programming
language called Oak with cross-platform support
Primary focus on small handheld device with an LCD touch-screen
and built-in wireless networking and infrared communications
Market was not ready
Internet market was booming now oak rename java
It was now divided into two group J2SE & J2EE
After a long time demand began to grow for Java on smaller devices
and even on smart cards, thus returning Java to its roots.
J2ME born later rename it as Java ME
6
Advantage of Java ME
“Write Once, Run Anywhere”
Portability across the widest range of devices
Provide best solution for an extremely wide range of small device
Secure
Incorporation of high usability and value features
Easy to master
7
Java ME Specification
8
Configuration
At the heart of the Java ME platform is the configuration. A
configuration defines a minimal Java runtime environment suitable
for a certain class or family of devices. In particular, a configuration
defines:
The capabilities of the Java virtual machine (VM)
The native code that interfaces with the underlying system
A set of Java runtime classes for running applications
Minimal device requirements for memory and input/output
mechanisms.
Configuration
CLDC
CDC
9
How CLDC, CDC Configurations came into existence
Mobile phone , TV set-Top Boxes, Home appliances etc. having
•Limited processing power
• Limited graphical capability
•Limited battery power
•Lower power consumption
•Limited memory
• Working on intermittent connection and limited bandwidth
 CLDC targeted for?
• KVM based devices
 CDC targeted for?
• JVM based devices
10
Connected Device Configuration
 A subset of Java Standard Edition.
Contains almost all the libraries of Java SE except GUI related.
Optimized for multi-threaded low memory conditions.
2 MB or more memory for Java platform
Four profiles are based on CDC:
• Foundation Profile
• Personal Basis Profile
• Personal Profile
•Gaming Profile
 Designed for Mobile & Embedded Devices with higher
 Processing Power, Memory and Display.
 Current Release: CDC 1.1.2 (JSR 218)
11
Connected Limited Device Configuration
160 – 512K of memory available for Java.
Typically has limited power or battery operated.
Network connectivity, often wireless, intermittent, low - bandwidth.
 Core Java class libraries available on a particular category of
devices.
32 kilobytes memory for runtime memory allocation.
Two profiles are based on CLDC:
 Mobile Information Device Profile
 Information Module Profile
12
CLDC API Structure
CLDC defines a core of APIs, mostly taken from the J2SE world.
These include fundamental language classes in java.lang, stream
classes from java.io, and simple collections from java.util. CLDC also
specifies a generalized network API in javax.microedition.io.*;
13
CLDC Core API
14
Profile
A profile is layered on top of a configuration
It is a collection of Java based APIs that supplement a
Configuration to provide capabilities for a specific vertical market or
device type (for example, wireless: mobile devices, set-top box etc.).
The main goal for a profile is to provide flexibility to the Java
Community while still maintaining portability across device types.
Profiles are defined by open industry working groups (Samsung,Nokia,
Sony ericsson,LG etc.)utilizing the 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.
15
Profile
Profiles define the application life cycle model, the user interface,
and access to device specific properties.
Java ME Profiles:
Mobile Information Device Profile (MIDP)
PDA Profile (PDAP)
Foundation Profile (FP),
Personal Profile (PP) and Personal Basic Profile (PBP).
RMI Profile
Game Profile
16
Java ME Family
17
KVM
 Sun's Kilobyte virtual machine
• ~ 50K
• With libraries + KVM ~130K
 Designed from ground up to meet needs to mobile devices
 Highly configurable but limits us because of size restrictions
18
KVM Limitations
Doesn’t support float or double data types (CLDC 1.1 does)
java.util greatly reduced
Limited string, and I/O functionality
No JNI or custom class loaders
Change in classfile verification  preverification
19
KVM Limitations
java.lang subset and in some cases modified interface and
implementation signatures
•Runtime - Reduced signature to memory operations freeMemory(), gc(), totalMemory()) and exit()
•System (reduced signature)
•Threading –Thread groups or daemon threads
Provide ~8 K of data storing facility {RMS}
Unicode is supported, but far fewer encodings are supported
20
One More Glance
21
MIDP
MIDP stands for Mobile Information Device Profile.
MIDP combined with the Connected Limited Device
Configuration (CLDC), is the Java runtime environment for
today's mobile information devices (MIDs) such as phones and
set top box.
Provide Graphical User Interface
Currently MIDP 2.0/2.1 device in market
A keypad, keyboard, or touch screen
Two-way wireless networking capability
Media Support
Database support
22
MIDP features
Externally triggered Java ME activation is supported { SMS ,
MMS, CBS etc}
Access native services {dial tel number, open system browser etc}
User Interface
Multimedia access { playing tone, songs etc}
Gaming API
Network Connectivity
23
MIDP Packages
24
MIDP UI Library
25
MIDlet
What is MIDlet ?
A MIDlet is a MID Profile application
javax.microedition.midlet.MIDlet;
The application must extend this class to allow the application
management software (AMS)to control the MIDlet
javax.microedition.midlet.MIDlet;
MyApp
 It Allows AMS to create, start, pause, and destroy a MIDlet
26
Application Management System
AMS software must work in conjunction with the device's native
system software
Control app lifecycle
Starting, Stopping & Pausing
KVM Control by AMS
Java ME app run under the control of KVM
AMS list all the installed MIDlet on the system
Task done by AMS Installation, Upgrade & Version management to
removal of application software
27
AMS Action & MIDlet State
28
MIDlet lifecycle
29
MIDlet lifecycle
MIDlet belong to javax.microedition.midlet.*; package.
Every Java ME MIDlet based on three method
•startApp
•pauseApp
•destroyApp
startApp method
• The startApp method is called when the MIDlet is started.
•After startApp has completed, the MIDlet is in Active state.
• It check whether any elements have been set as the current
screen (Display).
30
MIDlet lifecycle
pauseApp
• MIDlet application start with pause state.
•pauseApp call by external event like SMS, phone call etc.
destroyApp
• When application wants to terminate MIDlet it calls destroyApp
• MIDlet goes into the Destroyed state
•destroyApp method provides unconditional parameter
•false MIDlet refuse to terminate
• true AMS terminate the MIDlet
• notifyDestroyed notifies the AMS that the MIDlet has entered
Destroyed state
31
MIDlet lifecycle
MIDlet
import javax.microedition.midlet.MIDlet;
public class FirstMidlet extends MIDlet {
public void startApp() {
// MIDlet in Active State
} public void pauseApp() {
//MIDlet in Pause state
}
public void destroyApp(boolean unconditional) {
//MIDlet in Destroyed state
}
}
32
Hands On
Hands On try it your self
33
Java ME Development Cycle
Writing the code
•Using the text editor, enter source code, save the
code as <name>.java
Compiling the code
• <name>.class
Pre-verification
• <name>.class { increase size upto 5%}
Get JAD & JAR
Run MIDlet on device
34
Java ME Development Cycle
35
MIDlet Suite
The MIDlet suite is JAR & JAD file’s that contain one or more MIDlet
JAR=Java Archive File
JAD=Java Application Descriptor
The JAD makes information available to the application
manager. With this information, the manager can determine if the
device can accommodate the MIDlet
36
Inside JAR
JSR is a production, packaged application generally consist of
many files. In addition to Java classes, other files such as images
and application data, known as resources, may be part of the
package. You bundle all this information together into a single entity,
a JAR file.
37
Inside JAD
The JAD file provides information about the JAR, there are six
attributes that must be included into the JAD file.
Required six must JAD attributes:
•MIDlet-Name -- Name of the MIDlet suite
•MIDlet-Version -- Version number of the MIDlet
•MIDlet-Vendor -- Who created the MIDlet
•MIDlet-<n> -- Information about the MIDlet(s) in the suite
•MIDlet-Jar-URL -- The URL of the JAR file
•MIDlet-Jar-Size -- The size, in bytes, of the JAR
Optional attributes:
•MIDlet-Description:
•MIDlet-Delete-Confirm:
•MIDlet-Install-Notify:
38
Inside manifest
Reside inside the JAR file to provide the additional information
about the JAR, there are six attributes that must be in the manifest file
Mandatory Attributes:
• MIDlet-Name -- Name of the MIDlet suite
• MIDlet-Version -- Version number of the MIDlet
• MIDlet-Vendor -- Who created the MIDlet
• MIDlet-<n> -- Information about MIDlet(s) in the suite
• MicroEdition-Profile -- What profile is required by the MIDlet
• MicroEdition-Configuration -- Configuration is required by the MIDlet
Optional attributes:
• MIDlet-Icon:
• MIDlet-Description:
• MIDlet-Info-URL: Location
39
Over the Air
40
Over the Air
OTA is Over the Air provisioning, users acquire the jad/jar
as required via their browser
MIDP OTA Specification
– Device Functionality
• Support for HTTP 1.0 or 1.1
• Discovery Application (to locate application and to
download)
• AMS to manage OTA Application Provisioning life
cycle.
41
J2ME MIDP packages
 Application Lifecycle package
• javax.microedition.midlet
 User Interface package
• javax.microedition.lcdui
 Networking package
• javax.microedition.io
 Core packages
• java.lang, java.io, java.util
 Record Management Store
• javax.microedition.rms
42
lcdui package
 MIDP UI is divided into two levels: the High-level and the
Low-level
43
lcdui package
44
lcdui package
User-interface classes in javax.microedition.lcdui (and
lcdui.games)
Device’s display is represented by an instance of Display.
• Accessed from factory method getDisplay()
Display keeps track of what is currently visible, which is an
instance of Displayable
 Current state of the screen is changed by passing
Displayable instances to Display’s setCurrent() method
45
High Level UI
 High-level API’s for high portability (Screen)
 High – level MIDlet look and feel is same on all devices
 No direct access to device features
• Color, device inputs, screen size
 Implementation provides interaction (scrolling, navigation,
drawing)
 Input key event handling is not available in high-level APIs by
default.
The high-level APIs are:
 Alert - A popup screen to notify the user about an event.
 Form - A screen to which Form Items can be added. The Items are
also considered high-level APIs.
 List - A screen containing a scrollable list of choices.
 TextBox - A screen in which the user can enter or edit text.
46
Example
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Form;
public class HelloMidlet extends MIDlet implements CommandListener{
private Form form = null;
private final Command cmdExit = new Command("Exit",Command.EXIT,1);
private final String name=“Hello World”;
public void startApp() {
form = new Form(name);
form.addCommand(cmdExit);
form.setCommandListener(this);
Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
destroyApp(true);
notifyDestroyed();
}
}
47
Event Handling
High Level Event Handling
Low Level Event Handling
48
High Level Event Handling
Handling events in the high-level API is based on a listener model.
•CommandListener Interface
•ItemStateListener Interface
Command - The javax.microedition.lcdui.*; package provides the
Command class
• Command(String label, int commandType, int priority)
49
High Level Event Handling
Command Type - The type specifies the command's intent. The defined
types are: BACK, CANCEL, EXIT, HELP, ITEM, OK, SCREEN, and STOP.
...
Command exitCommand = new Command("Exit", Command. EXIT, 1);
Command backCommand = new Command("Back", Command. BACK, 1);
Command moreCommand = new Command("More", Command.SCREEN, 2);
...
50
Low Level Event Handling
 Canvas allows capturing of key-press events for most of the keys
available on the device. The only way to respond keyboard input is
by overriding the following methods
•protected void keyPressed(int keyCode)
•protected void keyReleased(int keyCode)
•protected void keyRepeated(int keyCode)
Code snippet
protected void keyPressed(int keyCode){
//handle key code
}
51
Low Level Event Handling
The minimal set of keys required by the MIDP specification to be
captured is:
•The digits 0 through 9
•The star or asterisk character (*)
• The pound or hash character (#)
Standard key codes
• KEY_NUM0 To KEY_NUM9
•UP ,DOWN ,LEFT ,RIGHT ,FIRE
•GAME_A ,GAME_B ,GAME_C ,GAME_D
52
Low Level UI
Full control over the pixel
53
Low Level UI
In contrast to the high-level API, the low-level API allows full
control of the MID display at pixel level
The low-level API is composed of the Canvas, Graphics
The Canvas and Graphics classes work together to provide low-level
control over a device.
To create your own canvas must extends your class with Canvas
class.
To writing/drawing on Canvas must implement paint method
public void paint(Graphics g) {
…
}
54
Graphics
Graphics object is used by the Canvas to do all 2D geometric rendering
capability. Rendering of Graphics can be done directly to the display or
to an off-screen image buffer.
55
Canvas
It provides method to handle the low level events{ key press,
pointer events}
Issue graphics object for drawing to display
It provides methods to identify the device's capabilities and mapping
of keys to game actions
It can register Command Listener
Canvas define following keys:
•KEY_NUM0,KEY_NUM1,KEY_NUM2,KEY_NUM3,KEY_NUM4,
KEY_NUM5,KEY_NUM6,KEY_NUM7,KEY_NUM8,KEY_NUM9,
KEY_STAR,KEY_POUND.
56
Canvas
Game action Key:
•UP,DOWN,LEFT,RIGHT,FIRE,GAME_A,GAME_B,GAME_C,and
GAME_D.
Code snippet
public class MyCanvas extends Canvas{
public void paint(Graphics g){
g.drawString(...);
}
}
57
Canvas
Key Handling
…
protected void keyPressed(int keyCode) {
switch (keyCode){
… case Canvas.KEY_NUM3:
System.out.println(getKeyName(keyCode));
break;
...
}
}
…
58
Canvas
Game Action Key Handling
protected void keyPressed(int keyCode){
int action = 0;
try {
action = getGameAction(keyCode);
switch(action){
case Canvas.DOWN:
System.out.println(getKeyName(keyCode));
break;
}
}
59
Canvas
Pointer Event Handling
…
protected void pointerPressed(x, int y){
if(x>0 && y<50){
….
}
}
…
60
Low Level External Interrupts
Interruptions such as incoming calls to a Java ME application in a
device invokes hideNotify() and showNotify() on any displaying canvas.
The showNotify() method is called prior to the Canvas actually being
made visible on the display, and the hideNotify() method is called after
the Canvas has been removed from the display.
/*called when an interrupt such as incoming call is received*/
protected void hideNotify() { }
/*called when an interrupt such as incoming call is ended*/
protected void showNotify() { }
61
Example
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
public class MIDPCanvas extends Canvas implements
CommandListener, Runnable {
…
public MIDPCanvas(DemoMidlet mid) {
…
}
public void paint(Graphics g) {
g.drawImage(offScreen, 0, 0, Graphics.LEFT | Graphics.TOP);
g.drawImage(ball, ix_co, iy_co, Graphics.LEFT |
Graphics.TOP);
}
protected void keyPressed(int keyCode) {
int key = 0;
try {
key = getGameAction(keyCode);
} catch (Exception ex) {
key = keyCode;
}
switch (key) {
case Canvas.LEFT:
ix_co--;
if(ix_co<0){
ix_co=0;
}
break;
case Canvas.RIGHT:
ix_co++;
if ((ix_co + (iballWidth)) >= iScreenWidth) {
ix_co = ix_co - 1;
}
break;
case Canvas.UP:
iy_co--;
if(iy_co<0){
iy_co=0;
}
break;
case Canvas.DOWN:
iy_co++;
if((iy_co + iballHeight)>=iScreenHight){
iy_co=iy_co-1;
}
break;
}
}
}
}
}
62
Class Hierarchy of the GCF
63
Generic Connection Framework
 The CLDC has define a set of APIs for I/O called
the Generic Connection Framework.
 The GCF, part of the javax.microedition.io package,
defines interfaces & Classes for the different kinds of I/O
that are possible(such as HTTP, socket, or streams).
 The CLDC does not actually define any I/O
implementations these are left to the profiles and/or the
OEM to define.
64
GCF – Protocol Support
Its support for different connection protocols
 Connector class is used to request to open a Connection
Connector.Open("protocol:address;parameters");
Opening various connection types
•Connector.Open("socket://…");
•Connector.Open("http://...");
•Connector.Open("datagram://…");
•Connector.Open("file://...");
65
GCF - example
import java.io.*;
import javax.microedition.io.*;
…
public void run() {
try {
HttpConnection httpConn = (HttpConnection)
Connector.open(textField.getString(),
Connector.READ_WRITE);
InputStream inputStrem = httpConn.openDataInputStream();
int i=0;
...
while((i=inputStrem.read())!=-1){
…
}
…
inputStrem.close();
httpConn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}…
66
javax.microedition.lcdui.game.*;
67
javax.microedition.lcdui.game.*;
Game package API javax.microedition.lcdui.game.*; is compact and
consists of only five classes. They are:
•Game Canvas
•Layer
•Layer Manager
•Sprite
•TiledLayer
68
Canvas Vs Game Canvas
 Canvas Known as low-level user interface, it provides a rich variety
of possibilities to draw onto the display. A class which extends Canvas
has to implement the method “paint ()” with instructions that draw
elements in the screen.
 GameCanvas is a Canvas extension to simplify game development
and to fix weak points from Canvas. Using GameCanvas is easier to
control key events and update the screen. To control key events you
just have to use the method getKeyStates() instead of using 3 methods
(keyPressed, keyReleased keyRepeated) used in Canvas and to update
the screen you just use flushGraphics() method.
69
Canvas Vs Game Canvas
Using Canvas
protected void keyPressed(int keyCode)
{
switch (getGameAction(keyCode)) {
Using GameCanvas
case UP:
Public void getEventStatus(){
…
int key = getKeyStates();
break;
if ((key & LEFT_PRESSED) != 0) {
…
}
}
protected void keyRepeated(int
}
keyCode) {
switch (getGameAction(keyCode)) {
case UP:
break;
}
70
RMS
Simple record-oriented database (RMS) stored in Flash
memory
Device-independent API
Records are arrays of bytes that live in record stores
Record stores are shared within MIDlet suite
•MIDP allows for optional sharing of record stores
between MIDlet suites
Support for enumeration, sorting, and filtering
Atomic update for single records
71
RMS
Sharing of record stores
72
RMS
Create record Store
To create a recordstore you can use
RecordStore.openRecordStore() with the second parameter set to
true.
//open record if present else create a record ...
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore("RecordName", true);
} catch (Exception exe) {
//unable to open record or create record
} finally {
try{
//to close the record store
rs. closeRecordStore();
}catch(Exception ex){
}
} ...
73
RMS
Close Record Store
To close the record store you can call closeRecordStore() it will
close specific Record Store
... try{
rs. closeRecordStore();
} catch (Exception ex){
}
...
74
RMS
Add Record to RecordStore
To add record get bytes of record and call addRecord() to add the
record to the record store
...
String str= "firstRecord";
//get bytes of record
byte[] rec = str.getBytes();
try {
// added record to recordstore
rs.addRecord(rec, 0, rec.length);
} catch (Exception e) {
}
...
75
RMS
Read Record from RecordStore
Set the array of bytes using the record size and call getRecord()
method to retrieve the Record Data.
...
byte[] getData;
try {
for (int i = 1; i <= rs.getNumRecords(); i++)
{
getData = new byte[rs.getRecordSize(i)];
rs.getRecord(i, getData, 0);
}
} catch (Exception exe) {
}
...
76
RMS
Delete Records form Record Store
To delete the record of specific id call the deleteRecord(int recordID)
...
try{
for(int i=rs. getNumRecords(); i>0;i--)
{
rs.deleteRecord(i);
}
} catch(Exception ex){
}
...
77
RMS
Deleting the Record Store
...
private final String S_LOGIN = “loginRS”;
try{
RecordStore.deleteRecordStore(S_LOGIN);
}catch(Exception ex){
}
...
78