0% found this document useful (0 votes)
26 views122 pages

ch15 J2ME

The document provides an overview of J2ME (Java 2 Micro Edition), a platform designed for programming on resource-constrained devices such as cellphones and personal organizers. It explains the structure of J2ME, including its configurations, profiles, and optional packages, and highlights the Mobile Information Device Profile (MIDP) as the primary profile for mobile applications. Additionally, it covers the development process, including the use of MIDlets and the UI API for creating user interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views122 pages

ch15 J2ME

The document provides an overview of J2ME (Java 2 Micro Edition), a platform designed for programming on resource-constrained devices such as cellphones and personal organizers. It explains the structure of J2ME, including its configurations, profiles, and optional packages, and highlights the Mobile Information Device Profile (MIDP) as the primary profile for mobile applications. Additionally, it covers the development process, including the use of MIDlets and the UI API for creating user interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 122

J2ME 1

 Java in the Handset


 The three prong approach to java
everywhere
 J2ME micro edition technology
 Programming for CLDC
 GUI in MIDP
 UI Design Issues
 Multimedia
 Record Management System
 Communication in MIDP
 Security Considerations in MIDP
J2ME 2
 Why? – To have the ability to program to
day to day devices such as:
cellphones
smart cards
personal organizers , palmtops
 What? – A java base platform for such
customizations.
 Who? Sun!!!, But also vendors like
Nokia , …

J2ME 3
 Java – “write once run anywhere”
 But:
 Different devices have different requirements.
 Those devices doesn’t have the same environment as
regular computers (standard desktop), the constrains
we have:
 Limited memory and processor.
 Small screen sizes.
 Alternative input methods.
 One platform (solution) cannot address all the market
segments (web server, video games etc.)
 Users/developers want flexibility. They want to
choose what they want to use and what they don’t.
 Sun decided to develop a special edition
of Java – J2ME (Java 2 Micro Edition).

J2ME 4
 The Java 2 Platform is split into three editions:
 Java 2 Standard Edition (J2SE) - Desktop-based
applications.
 Java 2 Enterprise Edition (J2EE) - Server-based
applications.
 Java 2 Micro Edition (J2ME) – For handheld and embedded
devices.
 Each edition provides a complete environment for
running Java-based applications including the Java
virtual machine (VM) and runtime classes.
 What separates one edition from another, then, is
primarily the set of class libraries that each edition
defines.
 you can think of J2ME as a subset of J2SE and J2SE
as a subset of J2EE.
J2ME 5
J2ME 6
J2ME 7
J2ME 8
J2ME 9
 At the heart of Java 2 Micro Edition (J2ME)
are three core concepts: configurations,
profiles, and optional packages.
 You can't write a J2ME application without
understanding these concepts, because
they determine the features of Java that
you can use, which application
programming interfaces (APIs) are
available, and how your applications are
packaged.

J2ME 10
 Optional Packages

Profiles
 Profile: J2ME
 A collection of Java Classes
selected from one or more Profile
Java core, extension or
vertical APIs. Classes are
chosen to provide a
complete solution J2ME
for a specific vertical Libraries
market

Configuration
 Configuration: Java Language
 A subset of the Java core
APIs and Java language
functionality selected to Java Virtual Machine
provide a minimal Java
platform for a set of
vertical markets
Host Operating System

J2ME 11
 A configuration is a complete Java
runtime environment:
 Java virtual machine (VM) to execute Java.
 Set of core Java runtime classes
 Interface to the underlying system

J2ME 12
 The profile adds classes to a
configuration:
 To fill in missing functionality
 To support specific uses of a device

 The Optional Packages are set of APIs


that support additional and common
behaviors.
 Examples of optional packages :
 Bluetooth Optional Package
 JDBC Optional Package

J2ME 13
 There are 2 basic configurations.

 The superset:
 CDC (Connected Device Configuration):
 2 MB or more memory for Java platform.
 32-bit processor.
 High bandwidth network connection.
 full-featured Java 2 virtual machine (CVM).
 17 packages.
 Use for devices like Palms.

J2ME 14
 The one we use:
 CDLC (Connected Limited Device Configuration):
 160 - 512 KB of total memory
 16-bit or 32-bit processor
 Low power consumption and often operating with
battery power
 Connectivity with limited bandwidth
 Selected classes from:
 java.lang , java.io , java.util
 Limited VM (KVM) without:
 Floating point types
 Object finalization
 JNI or reflection
 Thread groups or daemon threads
 User Class loaders

J2ME 15
 The CLDC has defined a new set of APIs
for I/O called the Generic Connection
Framework.
 The GCF, part of the new
javax.microedition.io package, defines
interfaces for the different kinds of I/O
that are possible.
 Since the CDC is a superset of the
CLDC, it includes the GCF.
 CDC also requires GCF support for two
specific connection types: files and
datagrams since it includes the
relevant classes from java.io and
java.net packages.
J2ME 16
 CDC-based profiles make development
simpler due to J2SE-like APIs, but don’t
suit the low-end devices.

 CLDC-based profiles makes the


development task harder, especially
when trying to shrink the size of the
application to run on many of the small
devices.

J2ME 17
 Several profiles in various stages of
development:
 Mobile Information Device Profile (MIDP) - CLDC-
based, used for running applications on cellphones and
interactive pagers with small screens, wireless HTTP
connectivity, and limited memory.
 Personal Digital Assistant Profile (PDAP) – CLDC-
based, extends MIDP with additional classes and
features for more powerful handheld devices.
 Foundation Profile (FP) – CDC-based, extends the
CDC with additional J2SE classes.
 Personal Basis Profile (PBP) - extends the FP with
lightweight (AWT-derived) user interface classes and a
new application model.
 Personal Profile extends the PBP with applet support
and heavyweight UI classes.

J2ME 18
 The CLDC-profile used today:
MIDP (Mobile Information Device
Profile)
 The MIDP defines a platform for
dynamically and securely deploying
optimized, graphical, networked
applications.
 The MIDP specification was defined
through the Java Community Process
(JCP) by players like: Motorola, Nokia,
Ericsson, Research in Motion, and
Symbian.
J2ME 19
 MIDP is targeted at a class of devices
known as mobile information devices
(MIDs).
 Minimal characteristics of MIDs:
 Enough memory to run MIDP applications
 Display of at least 96 X 56 pixels, either
monochrome or color
 A keypad, keyboard, or touch screen
 Two-way wireless networking capability

J2ME 20
J2ME 21
 There are two versions of the MIDP:

 MIDP 1.0 - is the original specification,


provides core application functionality
required by mobile applications, including
basic user interface and network security

 MIDP 2.0 - is a revised version of the


MIDP 1.0. Have new features include an
enhanced user interface, multimedia and
game functionality, more extensive
connectivity, over-the-air provisioning, and
end-to-end security.

J2ME 22
 MIDP does not run in the “regular” Java
fashion. using: Main() , System.exit().
 Instead, we use MIDlet aplications -
which are subclasses of:
javax.microedition.midlet.MIDlet that is
defined by MIDP.
 The MIDlet class allows the application
management software to:
 control the MIDlet
 be able to retrieve properties from the
application descriptor
 notify and request state changes

J2ME 23
J2ME 24
 The extending class is the main class of the
application.
 The MIDlet class defines abstract methods
that the main class implements (for
example: startApp(), destroyApp(),
notifyDestroyed()).

J2ME 25
 One or more MIDlets are packaged
together into a MIDlet suite, composed
of:
 JAR (Java archive) file - The JAR file contains
Java classes for each MIDlet in the suite and
Java classes that are shared between MIDlets.
The JAR file also contains resource files used
by the MIDlets and a manifest file.
 JAD (Java Application Descriptor) file - This file
contains a predefined set of attributes that
allows the device application management
software to identify, retrieve, and install the
MIDlets
 Eventually the JAR / JAD files are upload
to the machine in order to run the
application.

J2ME 26
 When the Java 2 Platform, Micro
Edition (J2ME) was first introduced,
only one configuration, the Connected
Limited Device Configuration (CLDC),
and one profile, the Mobile Information
Device Profile (MIDP) had been defined
as formal specifications.
 Today, there are nearly forty J2ME-
related specifications at various stages
in the JCP, and many of these
specifications define optional
packages instead of configurations or
profiles.
J2ME 27
 An optional package is also a set of APIs,
but unlike a profile, it does not define a
complete application environment.
 An optional package is always used in
conjunction with a configuration or a
profile. It extends the runtime
environment to support device
capabilities that are not universal
enough to be defined as part of a profile
or that need to be shared by different
profiles.
 Examples:
 RMI Optional Package (Remote Method
Invocation).
 Wireless Messaging API.
 Mobile Media API

J2ME 28
 Java 2 Micro Edition defines a small footprint version of
Java for resource constrained devices. Specifically, code
space of <512K and RAM (for java heap) of 64KBytes or
more.

 The Connected Limited Device Configuration (CLDC)


defines the minimum required complement of Java
technology components and libraries for small
connected devices. Java language and virtual machine
features, core libraries, input/output, networking and
security are the primary topics addressed by this
specification.

 The Mobile Information Device Profile (MIDP) defines an


additional set of API’s on top of the Connected
Limited Device Configuration (CLDC) for small
handheld devices such as PDA’s and cellular phones.
These include UI, Persistence, Networking, Timers, and
Application Lifecycle.

J2ME 29
 Java2 SE SDK 1.4.x (Can be downloaded at:
http://java.sun.com/j2se/1.4.2/download.html)
 The Eclipse IDE 3.x (Can be downloaded at:
http://www.eclipse.org/downloads/index.php)
 A supported wireless toolkit (A List of
supported toolkits can be found at:
http://eclipseme.org/docs/support_wtk.html)
 Any kind of Emulator
 EclipseME 1.x.x
 version 1.1.0 (supports Eclipse 3.1 only)
 version 1.0.1 (either Eclipse 3.0 or Eclipse 3.1 are
supported)
 prior 1.0.0 (support Eclipse 3.0 only)

J2ME 30
 Create a new project
 File -> new -> Project

J2ME 31
 Give a name to the project and Select the location
on the disk

J2ME 32
 On the ToolBar Select File -> New -> Other

J2ME 33
 Select a Name for the Midlet, Superclass and implemented interfaces.

J2ME 34
/** First Midlet Program********/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class FirstMidlet extends MIDlet
{
private Display display;
public void startApp()
{
if( display == null) {
init();// }
}
public void pauseApp(){
}
J2ME 35
public void destroyApp(boolean
unconditional) throws
MIDletStateChangeException
{
exit();
}
private void init(){
display=Display.getDisplay(this);
}
public void exit(){
notifyDestroyed();
}
}
J2ME 36
Importing MIDP
specific
packages

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

J2ME 38
 The UI API provides a set of features for
implementation of user interfaces for MIDP
applications.
 The central abstraction of the MIDP's UI is a
Displayable object, which encapsulates
device-specific graphics rendering with user
input. Only one Displayable may be visible at a
time, and the user can see and interact with
only contents of that Displayable.
 The Screen class is a subclass of Displayable
that takes care of all user interaction with
high-level user interface component. The
Screen subclasses handle rendering,
interaction, traversal, and scrolling, with only
higher-level events being passed on to the
application.
J2ME 39
Extends MIDlet
Implements
CommandListener

public class TestMIDlet


extends MIDlet
implements CommandListener {

J2ME 40
 This interface is used by applications
which need to receive high-level events
from the implementation.

 public void
commandAction(Command c,
Displayable d) - Indicates that a
command event has occurred on
Displayabled

J2ME 41
 Abstracts:
 protected abstract void startApp() –
Signals the MIDlet that it has entered the Active state
 protected abstract void pauseApp() –
Signals the MIDlet to enter the Paused state
 protected abstract void destroyApp(boolean
arg0) -
Signals the MIDlet to terminate and enter the Destroyed
state
J2ME 42
 Inherited:
 Int checkPermission(String permission)
 String getAppProperty(String key)
 Void notifyPaused()
 Boolean platformRequest(String URL)
 Void resumeRequest()
 Void notifyDestroyed() - Used by an MIDlet to
notify the application management software
that it has entered into the Destroyed state.

J2ME 43
Creating the
form, adding
the
Commands

public TestMIDlet() {
mMainForm = new Form(“Ahalan");
mMainForm.append(new StringItem(null,
“First Message"));
mMainForm.addCommand(new Command("Exit",
Command.EXIT, 0));
mMainForm.setCommandListener(this);
}

J2ME 44
 GUI in MIDP has two core concepts: Display
and displayable.
 MIDP display is represented by the Display
class.
 All displayable elements are called
displayable.
 To show an element we use the setCurrent
method of the Display Class.
 The Lifecycle of GUI interactions is shown
below.

J2ME 46
J2ME 47
 Displayable has two main subclasses
Screen and Canvas.
 Screen is a super class for a set of
predefined UI elements.
 Predefined UI’s are called High level UI
elements and canvas elements are called
Lower level elements.
 It is always preferable to use these as they
involve less coding and are more portable.
 Canvas allows the developer to have low
level control on the screen. Games
normally use canvas.

J2ME 48
J2ME 49
 public TextBox(String title, String text, int
maxSize, int constraints).
 The title argument sets the title that appears
above the TextBox; you can set it to null if
no title is required.
 The second argument specifies the text that
will initially be displayed in the TextBox.
 maxSize - Specifies the maximum number of
characters that the TextBox can contain at
any time.
 Constraints - Specifies the type of content
that should be allowed in the TextBox.

J2ME 50
 Using this argument, you can, for example,
estrict the user to entering only numbers or
more complex things such as phone
numbers or URLs without having to write the
code to validate the content yourself.

Displaying the TextBox


 Once you've created the TextBox, the next
step is to make it visible to the user, which
requires two lines of code:
display = Display.getDisplay(this);
display.setCurrent(textBox);

J2ME 51
 Alert is a subclass of Screen that behaves
somewhat like a dialog.
 There are several standard Alert styles that can
be used; the style is specified using an
AlertType object which may be supplied when
the Alert is constructed or using the setType()
method.
 An Alert has a title, a message, and an image.
These attributes may be set at construction time
or using the setTitle(), setString() and
setImage() methods.
 An Alert with no image may be created by
calling setImage() with argument null.

J2ME 52
 An Alert will usually be displayed for a fixed
length of time, after which it will be removed
from the display and the screen previously
on view will be restored.
 The display time may be specified using the
setTimeout() method, which requires an
argument in milliseconds.
 The special value Alert.FOREVER may be
used to create an Alert that remains visible
until the user explicitly dismisses it using a
control (usually a button) provided by the
platform for that purpose.

J2ME 53
 The default time for which an Alert will be displayed
(if no explicit timeout is provided) can be obtained
using the getDefaultTimeout() method.
 Devices that have sound capability may play a
sound when displaying an Alert.
 The soundmay be a default supplied by the
platform, or a specific sound that is determined by
the AlertType associated with the Alert.
 Unlike other Displayables, an Alert may not have
application-supplied Commands or
CommandListeners and an attempt to call methods
that set these attributes will result in an
IllegalStateException.

J2ME 54
public class Alert extends Screen {
// Public Constructors
public Alert( String title);
public Alert(String title, String alertText,
Image alertImage, AlertType alertType);
// Public Constants
public static final int FOREVER; // =-2
// Property Accessor Methods (by property
name)
public int getDefaultTimeout();
public Image getImage();

J2ME 55
public void setImage( Image img);
public String getString();
public void setString( String str);
public int getTimeout();
public void setTimeout( int time);
public AlertType getType();
public void setType( AlertType type);
// Public Methods Overriding Displayable
public void addCommand( Command cmd);
public void
setCommandListener( CommandListener l);
}

J2ME 56
 This is a class that provides a set of type-
safe constants that are used to specify the
type of an Alert.
 The AlertType provides a hint to the platform
as to how it should render the Alert and
typically causes an appropriate icon to be
included along with the application-supplied
message.
 On devices that have a sound capability, a
sound (which might be type-dependent) may
also be played when the alert is displayed.

J2ME 57
 The playSound() method may be used to
play the sound associated with the
AlertType, even when no Alert is displayed.
 Since not all devices will be able to play
sounds, the playSound() method returns a
boolean indicating whether a sound was
produced, to allow the application to use an
alternate mechanism to attract the user's
attention if sound is not available.

J2ME 58
public class AlertType {
// Protected Constructors
protected AlertType();
// Public Constants
public static final AlertType ALARM;
public static final AlertType CONFIRMATION;
public static final AlertType ERROR;
public static final AlertType INFO;
public static final AlertType WARNING;
// Public Instance Methods
public boolean playSound( Display display);
}

J2ME 59
 Passed To
Alert.{Alert(), setType()}
 Returned By

Alert.getType()
 Type Of

AlertType.{ALARM, CONFIRMATION, ERROR,


INFO, WARNING}

J2ME 60
 Used to specify a group of options that the
user can specify.
 The constructor takes two parameters label
and type.
List list=new List(“IMPLICIT”,List.IMPLICIT)
 List are basically of three types-IMPLICIT,
EXCLUSIVE, MULTIPLE.

J2ME 61
J2ME 62
J2ME 63
J2ME 64
 Form is similar to its html counterpart.

 A Form is a Screen that contains an arbitrary


mixture of items: images, read-only text
fields, editable text fields, editable date
fields, gauges, choice groups, and custom
items.

 In general, any subclass of the Item class


may be contained within a form.

 The implementation handles layout,


traversal, and scrolling.

J2ME 65
 Items are added to Form.

 MIDP provides a set of predefined


Items.
 List of all items available in MIDP are
shown below.

J2ME 66
J2ME 67
 It allows users to select one or more
elements from a group.
 These groups are similar to radio button,
check boxes and drop down in html.
 Choice Group are of three different types.
 Choice Group constructor takes a label and
type value.
 Optionally images and text can be added.
 Members can be added after creation using
the append method.

J2ME 68
J2ME 69
J2ME 70
 Date Filed is an interactive item to
enter/retrieve date and time information.
 Date Field extends the Item class so can be
placed on Form objects.
 Display option for a Date Field is specified
using input mode constants in the
constructor.
 Possible Data Field mode constants are
listed below:

J2ME 71
J2ME 72
 This can be thought of as a progress bar.
 A Gauge provides a way to represent a single
selected value from a contiguous range of
integers starting from 0 and ranging up to an
application-supplied maximum.
 The Gauge class has a single constructor:
public Gauge(String label, boolean interactive,
int maxValue,int initialValue);
 The maxValue and initialValue arguments
specify, respectively, the largest value of the
range covered by the gauge and the value that
will be displayed initially.

J2ME 73
 The minimum value is always implicitly zero, and
the current value must always be positive and
not greater than the maximum.
 The interactive argument determines whether
the user can adjust the value in the gauge.
 To use a gauge as a slider, you should set this
argument to true.
 Adjustments made by the user are reported to
the ItemStateListener attached to the Form on
which the gauge is displayed.
 If interactive is false, the value of the gauge can
be adjusted only under application control.
 In this mode, the gauge acts more like a
progress bar.

J2ME 74
 The current value of a gauge can be
obtained or changed using the following
methods:
public int getValue( );
public void setValue(int value);
 The value passed to the setValue( ) method
must be nonnegative and less than or equal
to the maximum value.
 The maximum value can itself be
manipulated using similar methods:
public int getMaxValue( );
public void setMaxValue(int value);

J2ME 75
 The value passed to setMaxValue( ) must be
greater than 0.
 If the new maximum value is less than the
current value, the current value is reduced
to the new maximum.
 Note that, as with all programmatic changes,
this change in the current value is not
reported to ItemStateListeners.
 There is also a method that allows you to
determine whether a gauge is interactive:
public boolean isInteractive( );

J2ME 76
 Form form = new Form("Gauge");
 form.append(new Gauge(null, true, 100,
50));
 form.append(new Gauge(null, true, 100,
25));
 form.append(new Gauge(null, false, 100,
50));

J2ME 77
 StringItem, the simplest of the MIDP user interface
components, provides the ability to place a string or
pair of strings on a Form.
 Initial values for both strings may be supplied to the
constructor:
public StringItem(String label, String text)
 The label part is the label that is inherited by all
Items from their base class; its value can be retrieved
or changed using the Item getLabel( ) and setLabel( )
methods.
 StringItem provides similar methods for its own text
attribute: public String getText( )
public void setText(String text)
 Either or both of the label and text string may be null.

J2ME 78
Spacer class:
 It is a non interactive item used to position
the elements correctly on the screen.
 The size of the empty space is defined as
minWidth and minHeight.
 Ex

Spacer spacer=new Spacer(100,100);


form.append(spacer);

J2ME 79
J2ME 80
 ImageItem lets you place an image on a
Form with some limited control over how it is
placed relative to other Items.
 The ImageItem class has a single
constructor:
public ImageItem(String label, Image image,
int layout, String altText)
 Adding an ImageItem to a Form causes the
optional label and the image to be placed
subject to the constraints specified by the
layout argument.
 The device is free to ignore the layout
argument and apply its own layout rules.

J2ME 81
 It may also use the text supplied by the
altText argument in place of the image
when, in the words of the MIDP specification,
"the image exceeds the capability of the
device to display it”.
 The image is supplied in the form of an
Image object.
There are several ways to create an Image:
 loading data over a network connection,
using graphics primitives to compose the
Image from lines, points, curves and solid
shapes, and loading encoded data from a
file.

J2ME 82
To load an image from a file, use the following
static method of the Image class:
 public static Image createImage(String
name) throws IOException
 name is a resource name that corresponds
to the location of the file in the MIDlet suite's
JAR file.
 The indicated file must contain an image
encoded in Portable Network Graphics (PNG)
format, since this is the only graphics file
format that MIDP devices are required to
support.

J2ME 83
 The layout parameter is a bitmask made up
from legal combinations of the following
values:
ImageItem.LAYOUT_DEFAULT
 The image should be placed according to the
platform's default layout policy.
ImageItem.LAYOUT_LEFT
 The image should be left-justified in the
space available to it.

J2ME 84
ImageItem.LAYOUT_RIGHT
 The image should be right-justified in the
space available to it.
ImageItem.LAYOUT_CENTER
 The image should be centered in the space
available to it.
ImageItem.LAYOUT_NEWLINE_BEFORE
 A line break should occur before the image
is drawn.
ImageItem.LAYOUT_NEWLINE_AFTER
 A line break should occur after the image is
drawn.

J2ME 85
 you can add an image to a Form using the
following Form method:
public void append(Image image);
 This is equivalent to creating and appending
an ImageItem with layout LAYOUT_DEFAULT
and no label, that is:
form.append(new ImageItem(null, image,
ImageItem.LAYOUT_DEFAULT, null));

J2ME 86
Ex
 Image red = Image.createImage ("/ora/ ch4/
resources/ red.png");
 Image blue = Image.createImage ("/ora/ch4/
resources/blue.png");
// ImageItems with labels
 form.append(new ImageItem("Center", red,
ImageItem. LAYOUT_CENTER, null));
 form.append(new ImageItem("Left", red,
ImageItem.LAYOUT_LEFT, null));
 form.append(new ImageItem("Right", red,
ImageItem.LAYOUT_RIGHT, null));
 form.append(new ImageItem("Default", red,
ImageItem.LAYOUT_DEFAULT, null));

J2ME 87
 TextField class handles all text input.
 The constructor takes four parameters a
label or name of the item, initial text, the
input length, and constants.
 Textfield is added to a form using the
append function.
 Ex:TextField txtfld=new TextField(“My
TextField”, “You can enter text here”, 50,
TextField.ANY);

J2ME 88
 Custom Item extends the Item class, offers a
simple template for developing custom items.
 Custom Item is the directory Item, will display
a + symbol.
 When selected it will expand to display a sub
level item.
 The process involves two steps.
 First we need to extend the item class and
create our new item. Then we will use this
item in a form.

J2ME 89
J2ME 90
J2ME 91
 Canvas is an abstract class.
 To use Canvas, you have to subclass it and
implement the paint method to draw
whatever you want to appear on the screen.
 This method is called with a single
argument, which is an instance of another
low-level API class called Graphics.
 This class provides methods that allow you
to draw lines, rectangles, and arcs, fill areas
with a solid color, and render text onto the
device's screen.

J2ME 92
 The Canvas class also has methods -- which you
can override -- to receive notification of key
presses and use of the pointer (on those devices
that have one)..
Screen Attributes
 The low-level API is intended to give you much
greater control over the screen and keypad of a
MIDP device than the high-level API does.
 To make it easier to write code that adapts itself to
its environment, the Canvas and Display classes
provide methods, described in the following
sections, to allow you to query the attributes that
distinguish one device from another.

J2ME 93
Display methods
 The Display class provides the following
methods:
 public boolean isColor( )
 This method returns true if the device has a color
display, false if not.
 public int numColors( )
 Ifthe isColor( ) method returns true, numColors( )
can be used to get the number of different colors
the device supports. When isColor( ) returns
false, numColors() returns the number of shades
of gray that the device's display can provide.

J2ME 94
Display methods
 You can treat a grayscale device as if it
supported color, and the color values you
use will be converted to a shade of gray that
approximates the brightness of the original
color.
 However, you might be able to obtain better
results in some cases by coding your MIDlet
to work in grayscale if the device does not
support color.

J2ME 95
Canvas methods
 The Canvas class provides the following
methods:
 public int getWidth( )
 public int getHeight( )
 These methods return the width and height
of the Canvas, which corresponds to the
usable part of the device's screen.
 public boolean hasRepeatEvents( )
 public boolean hasPointerEvents( )
 public boolean hasPointerMotionEvents( )
 public boolean isDoubleBuffered( )

J2ME 96
J2ME 97
J2ME 98
J2ME 99
 Game API:For game development.
 Extend a class GameCanvas
 Layer:an application element’s visual part
Sprite:For animation purpose.
 Ex:Rotate duke
Image
img=Image.createImage(“/Duke.png”);
sprite=new sprite(img)
G=getGraphics();
sprite.paint(g);
Sprite.move(Xcord,Ycord);
Sprite.setTransform(Sprite.TRANS_ROT180)
;
Sprite.paint(g);
flushGraphics();
 Tiled Layer: Multiple tiles make up a single
image object.moving tile moves the
object.
 TiledLayer tiles=new
TiledLayer(x,y,Image,tileW,tileH);
 setCell(int,int,int),filllCells(int,int,int,int,int)
:
For background filler.
 Layers.append(tiles)
 User interactions generate events:
 Screen inputs.
 Item state change
 Handset data update.
 It provides interfaces for each of the events.
 These interfaces implement callback methods,
which in turn invocate application defined
methods.
 These methods perform the desired functions
in response to events.
 The three interfaces provided are:
ItemStateListener, CommandListener and
RecordListener.

J2ME 103
Command Listener.
 Is responsible for notifying the MIDlet of any
commands or events generated by the user.
 Objects extending it, implement the
commandAction method.
 This method takes two parameters a
Command object and a displayable.
(Command c,Displayable d).
 Displayable.setCommandListener(Command
Listener L) sets the listener L to a
Displayable.

J2ME 104
Item State Listener.
 Informs the MIDlet of changes in the state of
an interactive item.
 It calls the itemStateChanged(Item I) method
in response to an internal state change.
 Form.setItemStateListener(ItemStateListener
L) sets the item state listener L for the given
displayable.
Record Listener
 Is related to database events .

J2ME 105
 Command is a class that represents an
operation that the may be represented in the
user interface.
 Commands may be added to any Displayable
with the exception of Alerts and are rendered
in a platform-dependent way, often using
buttons or as entries in a menu system.
 When the user activates the user interface
control associated with a Command, the
CommandListener associated with the
Displayable is notified.

J2ME 106
 A Command has three attributes that are set
at construction time.
 Once set, the values of these attributes can
be obtained using the getLabel(),
getCommandType() and getPriority()
methods, but cannot be changed.
 Label:The command name that the user will
see in the user interface.
 Type:A constant value that indicates the
semantic intent of the command.

J2ME 107
 Priority:An integer value that gives the priority of
this command relative to others of the same
type. Lower values indicate higher priority.
 The type is used to indicate to the platform
whether the command is one of the standard
types that it knows about and might provide
special display handling for, or an application-
private command.
 The standard types, whose meanings should be
obvious from their names, are BACK, CANCEL,
EXIT, HELP, OK and STOP.
 Application-private commands are assigned
types of ITEM or SCREEN.

J2ME 108
 Command does not contain the
implementation of the action to be carried
when it is activated - it is simply a value that
a CommandListener can use to determine
which operation the user wants to perform.

J2ME 109
 public class Command {
// Public Constructors
public Command(String label, int
commandType,
int priority);
// Public Constants
public static final int BACK; // =2
public static final int CANCEL; // =3
public static final int EXIT; // =7
public static final int HELP; // =5
public static final int ITEM; // =8
public static final int OK; // =4
public static final int SCREEN; // =1

J2ME 110
public static final int STOP; // =6
// Public Instance Methods
public int getCommandType();
public String getLabel();
public int getPriority();
}

J2ME 111
 Provides support for audio capability.
 No support for video or graphics formats.
 Manager:Creating and controlling audio
resources.
 Player:actual job.
 Contol:regulate features.
 Play a simple tune include
 Manager.playTone(ToneControl.C4,100,100).
 User created tone:

Private byte[] MyTune=


{
ToneControl.VERSION,1,c4,d4,e4,g4);
Where byte C4=ToneControl.C4;
byte D4=(byte)(C4+2);
byte E4=(byte)(C4+4);
byte G4=(byte)(C4+7);
}
• Play the tune:
– Player
player=Manager.createPlayer(Manager.TONE_
DEVICE_LOCATOR).
• Player lifecycle has 5 states:
– UNREALIZED
– REALIZED
– PREFETCHED
– STARTED
– STOPPED
• Connection call:
• ConnectionType conn=(Connector Type)
Connector.open(URI);
• Uri:
<protocol>:<address>:<parameters>.
• Support 4 protocols:
– HTTP connection
– DatagramConnection
– SocketConnection
– ServerSocketConnection
• Allow applications to register for incoming
connection or time-bounded requests.
• Application need to register to
AMS(Application Management Software).
• Done in 2 ways:
– Static :access in the app descriptor.
– Dynamically :registerConnection() API
• Once registered ,responsibility of AMS to
launch application in respone to the
event for registered.
 Midlet push attribute is

 Name,url,class name,origin server.


 Post registration:
 Not active
 Is active
 Application security:
 Security domain defines the access
permissions for an application.
 Applications belong to
 Trusted domain:use API’s
 Untrusted domain:restricted access
 Domain policy defines a set of
permissions allowed and user can be
granted to MIDLET.
 RecordStore security:
 Shared record stores :
 openRecordStore(name,creator,AUTHMODE_A
NY,writable) throws exception..
 Used carefully as this exposes all the data to
caller.
 Communication channel security:
 With HTTPs and secure domains.
 Security framework .
 Push registry:
 Only permissioned midlets launch push
registry.
 To support additional features :
 JDBC
 WMA(Messaging API)
 MMAPI(Media)
 RMI
 Forbluetooth
 GAMEAPI
 Location API

You might also like