You are on page 1of 100

This product or document is protected by copyright and

distributed under licenses restricting its use, copying,


distribution and decompilation. Please view Mark of
Authenticity label to establish proper licensed usage. No
part of this document may be copied, reproduced, printed,
distributed, modified, removed, amended in any form by
any means whether electronic, mechanical, digital, optical,
photographic or otherwise without prior written
authorization of NIIT and its authorized licensors, if any.
Information in this document is subject to change by NIIT
without notice. The names of companies, products, people,
characters, and/or data mentioned herein are fictitious and
are in no way intended to represent any real individual,
company, entity, services, product or event, unless
otherwise noted.
All products are registered trademarks of their respective
organizations.
All software is used for educational purposes only.
Disclaimer: The documents and graphics on this
courseware could include technical inaccuracies or
typographical errors/translation errors. Changes are
periodically added to the information herein. NIIT may
make improvements and/or changes herein at any time.
NIIT makes no representations about the accuracy of the
information contained in the courseware and graphics in
this courseware for any purpose. All documents and
graphics are provided "as is". NIIT hereby disclaims all
warranties and conditions with regard to this information,
including all implied warranties and conditions of
merchantability, fitness for any particular purpose, title
and non-infringement. In any event, NIIT and/or its
licensor(s)/supplier(s) shall not be liable to any party for
any direct, indirect, special or other consequential
damages for any use of the courseware/translated
courseware, the information, or on any other hyper linked
web site, including, without limitation, any lost profits,
business interruption, loss of programs or other data on
your information handling system or otherwise, even if
NIIT is expressly advised of the possibility of such
damages.
Due to the dynamic nature of the internet, the URLs and
web references mentioned in this document may be (are)
subject to changes, for which NIIT shall not hold any
responsibility.

DMAJ - II/SG/10-M06-V02
Copyright NIIT. All rights reserved.

COURSE DESIGN-STUDENT
GUIDE

Objectives

About This Course


Prologue
Description
This course focuses on developing mobile application by
using Java Micro Edition (Java ME). Although the Java
platform is extensively used for developing Desktop
applications and Web-based applications, Java ME is a
popular platform for developing applications for mobile
devices, such as mobile phones and Personal Digital
Assistants (PDA).
This course covers the implementations of software
solutions for mobile devices. It begins by introducing the
Java ME architecture and wireless technology. The course
explains how to create high-level and low-level user
interfaces. In addition, it explains managing storage of
information and implementing security. Also, the course
explains how to create multimedia applications, wireless
messaging applications, and gaming applications by using
Java ME. Finally, this course will enable the students to
develop, debug, test, and securely deploy mobile
applications.

Rationale
The availability of wireless Internet services on mobile
devices such as mobile phones is making communication
possible anywhere and at anytime. When connected to the
Internet, the functionality provided by these mobile
devices becomes seamlessly endless.
Java is a very popular technology. It has been accepted as
the de facto standard by the mobile industry for
developing mobile applications. However, the standard
edition of Java cannot be used for creating applications for
mobile devices since it uses a lot of memory. Therefore,
Sun Microsystems released Java ME for developing
applications for resource-restricted devices. Java ME
offers a flexible and robust platform for mobile application
development with enterprise-class performance, reliability,
and value.
Java ME aims at developing applications for micro
devices like mobile phones and Personal Digital Assistants
which have limited application capacity. It allows
developers to use the Sun Java wireless toolkit to create
applications and programs for wireless and mobile
devices.

After completing this course, students will be able to:


Explain the profiles and configurations in Java
ME technology
Execute a MIDlet, and package and run MIDlet
suites using NetBeans 6.0.1
Describe MIDP User Interface components and
their hierarchy
Create User Interfaces using High Level UI APIs
Create user interfaces using low-level APIs
Store and manipulate data in MIDlet by using
RMS
Establish network connection using the GCF
Implement MIDlet Security
Play sounds and videos using MMAPI package
Create, send, and receive SMS messages using
WMA
Develop gaming application
Identify the use of push registry
Deploy MIDlets through local Machine and Web
Server

Entry Profile
The students wanting to undergo this course are
recommended to have the following skills:
Knowledge of core Java
Basic knowledge of XML

Exit Profile
After completing this course, the student should be able to:
Develop Mobile Applications by using the Java
ME Technology

Conventions
Convention

Indicates...
Note

Just a minute

Tip

Identifying GCF Interfaces

Chapter 8
Implementing MIDP Networking
and Communication
At times, mobile users need to retrieve information from a
Web server to their mobile devices. For example, a mobile
device user might need to get stock information from a
stock server. To display this information on the mobile
device, the application has to connect to the server and
retrieve the required information. Such connections need
to implement wireless network connectivity.
Various protocols are available to build network
connections in mobile devices. MIDP uses Generic
Connection Framework (GCF) that provides various
classes and interfaces for establishing network
connections. These classes and interfaces are provided in
the javax.microedition.io package.
This chapter discusses various classes and interfaces
provided by GCF. It explains the process of establishing
network connections by using GCF. Further, it discusses
various protocols available in MIDP for implementing
network connectivity. In addition, it explains the creation
of enterprise applications by using Java ME.

GCF is defined in the configuration layer of the Java ME


architecture. GCF is supported by both CDC and CLDC
and is used to create network-based applications.
To establish a network connection between two mobile
devices, vendors need to implement protocols, such as
HTTP, in the mobile devices.
GCF itself does not provide any protocol implementation,
but it allows vendors implementing MIDP to implement
the required protocol. For example, GCF allows you to
establish an HTTP-based network connection by using the
HttpConnection interface provided by MIDP. The
HttpConnection interface is not a part of GCF, but it
is derived from the GCF interface named
ContentConnection.
The interfaces of GCF are defined in the
javax.microedition.io package and are organized
in a hierarchy, as shown in the following figure.

Objectives
In this chapter, you will learn to:
Establish network connection by using GCF
Implement network connectivity by using MIDP

Creating Network Connections


Using Generic Connection
Framework
Mobile devices exchange information with other mobile
devices or servers through a wireless network connection.
CLDC consists of classes, called as GCF that is used for
wireless network communication.
GCF enables mobile application developers to use various
protocols, such as HTTP, for wireless communication.
GCF provides a common foundation API for all
connection types. This generalization is implemented in
mobile application by using:
A set of seven interfaces
Two classes, the Connector class and the
ConnectionNotFoundException
exception class

The GCF Hierarchy


The interfaces provided by GCF are:
Connection: Is the root of the GCF interface
hierarchy. This interface consists of only one
method, close() that closes the network
connection.
StreamConnectionNotifier: Creates a
network connection based on streams as soon as
a port supporting the streams becomes active.
This interface consists of only one method,
acceptAndOpen(). The acceptAndOpen
() method returns an instance of the
StreamConnection interface that represents
a server-side socket connection.
InputConnection: Manages a network
connection based on the input stream. This
interface consists of two methods,
openDataInputStream() and
openInputStream(). The
openDataInputStream() method opens a
data input stream from a network connection. The
openInputStream() method opens an input

stream from a network connection.


OutputConnection: Manages a network
connection based on the output stream. This
interface consists of two methods,
openDataOutputStream() and
openOutputStream(). The
openDataOutputStream() method opens a
data output stream from a network connection.
The openOutputStream() method opens an
output stream from a network connection.
DatagramConnection: Manages packetbased connections. This interface consists of
eight methods that enable you to perform several
tasks, such as creating, sending, and specifying
the length of a datagram packet. The eight
methods of the DatagramConnection
interface are:
int getMaximumLength(): Returns
the maximum length of a datagram.
int getNominalLength(): Returns
the nominal length of a datagram.
Datagram newDatagram(byte[]
buf, int size): Creates a new
datagram object. This method takes two
parameters, the buffer that has to be
allocated and the buffer size.
Datagram newDatagram(byte[]
buf, int size, String addr):
Creates a new datagram object. The buffer
to be allocated, buffer size, and address to
which datagram will be sent are passed as
an argument to this method.
Datagram newDatagram(int
size): Creates a new datagram object.
This method takes only one parameter, the
size of the buffer. The buffer is
automatically allocated to the new
datagram object.
Datagram newDatagram(int
size, String addr): Creates a new
datagram object. The buffer size and
address to which the datagram will be sent
are passed as arguments to the method.
void receive(Datagram dgram):
Receives a datagram.
void send(Datagram dgram):
Sends a datagram.
StreamConnection: Manages attributes,
such as speed, of a stream. This interface forms
the root of the InputConnection and
OutputConnection interfaces. The
StreamConnection interface consists of four
methods that are inherited from the
InputConnection and

OutputConnection interfaces, besides the


close() method inherited from the
Connection interface. The four methods
inherited from the InputConnection and
OutputConnection interfaces are:
DataInputStream
openDataInputStream(): Opens and
returns a data input stream for a
connection. This method is inherited from
the InputConnection interface.
InputStream openInputStream
(): Opens and returns an input stream for
a connection. This method is also inherited
from the InputConnection interface.
DataOutputStream
openDataOutputStream(): Opens
and returns a data output stream for a
connection. This method is inherited from
the OutputConnection interface.
OutputStream openOutputStream
(): Opens and returns an output stream for
a connection. This method is also inherited
from the OutputConnection interface.
ContentConnection: Manages a network
connection, such as HTTP, for transferring Web
content. This interface provides three methods to
determine the character encoding of an HTTP
stream. The methods in the
ContentConnection interface include:
public String getEncoding():
Returns the string describing the content
encoding of the resource that a URL
references.
public long getLength(): Returns
the content length of the resource that a
URL references.
public String getType(): Returns
the string describing the content type of the
resource that a URL references.

A datagram is a self-contained entity of data.


It contains information that helps to route the
datagram from a source to a destination.

Just a minute:
State whether the following statement is true
or false.
The StreamConnectionNotifier
interface of GCF manages attributes, such as
speed of a stream. This interface forms the
root of the InputConnection and
OutputConnection interfaces.

Answer:
False

Wireless Network Considerations in


GCF
While establishing a connection by using GCF, you need
to keep various network considerations in mind. These
considerations in GCF are based on the limited resources
of mobile devices. GCF provides networking and file I/O
capabilities to the mobile devices with hardware and
bandwidth limitations.
You need to keep the following considerations in mind
while creating network connections through GCF:
GCF provides networking and I/O capabilities by
defining a set of interfaces. The vendors and
developers need to implement these interfaces
according to their networking requirements. For
example, vendors providing MIDP API will have
to implement the HttpConnection interface
to support networking in MIDlets by using HTTP
connections.
GCF does not support object serialization that
defines a transmission and storage mechanism for
Java objects. As a result, you need to design
specific persistence mechanisms, such as RMS,
for storing Java objects persistently.

Object serialization extends the core Java I/O


classes with support for objects. It is used to
encode objects into a stream of bytes and
reconstruct an object graph from the encoded
stream.

Setting up a Connection by Using


GCF

The GCF Connector class enables you to set up


network connections among different mobile devices. The
Connector class provides several static methods to
setup a network connection. The static methods include
the following types of open() methods:
open(String url): Creates a network
connection with the specified connection type.
The argument, url describes the URL of the
connection type.
open(String url, int mode): Creates a
network connection with the specified connection
type and mode. The argument, url describes the
URL of the connection type and the argument,
mode, specifies the connection modes, such as
READ, WRITE, or READ_WRITE.
open(String url, int mode,
boolean timeouts): Creates a network
connection with the specified connection type,
mode, and timeout exception flag. The
timeouts argument is a Boolean flag that
specifies whether the network connection should
throw a timeout exception, such as the
InterrruptedIOException, when a
timeout occurs.
The various types of network connections that you can
create by using the open() method of the Connector
class are:
HTTP connection: Enables you to use the HTTP
protocol to access Web pages. The code snippet
to create an HTTP connection is:
Connection hc = (HttpConnection)
Connector.open
("www.wirelessdevnet.com");
Stream-based socket connection: Enables you
to create a stream-based socket connection. The
code snippet to create a stream-based socket
connection is:
Connection sc =
(StreamConnection)Connector.open
("socket://localhost:9000");
Datagram-based socket connection: Enables
you to create a datagram-based socket
connection. The code snippet to create a
datagram-based socket connection is:
Connection dc =
(DatagramConnection)
Connector.open
("datagram://:9000");
Serial port connection: Enables you to create a
serial port connection. The code snippet to create
a serial port connection is:
Connection cc = Connector.open
("comm:0;baudrate=9000");
The url parameter passed to the Connector.open()

method consists of the following three parts:


Protocol: Specifies the protocol used for creating
the connection. The protocol can be a socket, an
http, or a datagram.
Address: Specifies the destination address.
Parameters: Specifies the attributes of the
network connection, such as speed.
The Connector.open() method can throw the
ConnectionNotFoundException exception if the
target connection cannot be found, or if the requested
protocol type is not supported.
The tasks that you need to perform for establishing a
network connection by using GCF are:
1. Create the URL to which the network connection
is to be made.
2. Create the network connection by using the
Connector class.
3. Cast the return value to the appropriate
subinterface of the Connection class.
4. Get streams for the network connection by using
the methods, such as
Connection.getInputStream().
5. Close the stream by using the
Connection.close() method.

Implementing Network Connectivity


by Using MIDP
The javax.microedition.io package provides
support for networking in mobile wireless devices. It
contains the methods and interfaces that allow you to
implement network connectivity between a mobile client
and a server.
To implement the network connectivity by using MIDP,
you need to decide a protocol that you want to use and
then establish the network communication between
devices.

Using Network Protocols Supported


by MIDP
The types of networking in Java ME can be classified
based on the communication protocols. The following
types of networking are supported by Java ME:
Low-level networking: Involves socket-based
and datagram-based connections.
Secure networking: Involves secure network
connection, such as Hyper Text Transfer Protocol
Secure (HTTPS), that provide secure Web-based
services.
HTTP networking: Involves HTTP-based
network connection.

The following network protocols are supported by MIDP


2.x:
Transmission Control Protocol/Internet Protocol
(TCP/IP) and User Datagram Protocol (UDP)
HTTP and HTTPS
Socket and ServerSocket

MIDP1.0 does not provide low-level


networking support for the TCP/IP sockets
and UDP datagram, but the MIDP2.0
specification responded to the needs of 2.5G
and 3G networks by adding support for
sockets and datagram.

TCP/IP and UDP


The TCP/IP protocol is used to establish socket-based
connection. A socket represents end-points for
communication between a server and a client. A socketbased connection is used to connect between a wireless
device and a remote server or between two wireless
devices.

TCP/IP is the standard Internet protocol that


allows you to send and receive data over wired
or wireless networks.
In the MIDP 2.x specification, the support for TCP/IP and
UDP is optional, which means that device manufacturers
may or may not provide support for TCP/IP and UDP.
You can use UDP to transmit data in datagram-based
communication, in which the sender builds a datagram
packet that contains information about the destination of
the packet. The sender then sends the packet to the
destination. The datagram packets are used to send and
receive the information asynchronously.
You can use UDP to transmit the following types of data:
Real-time audio/video data
Data in a packet-switched wireless network,
which does not support socket-based
communications
You can implement a UDP connection by using the
UDPDatagramConnection interface. A UDP
connection can be implemented by using the
Connector.open() method. The application should
provide a URL starting with the string, datagram://. The
host name and port number should be specified after the
datagram:// string. For example, the following code
snippet implements a UDP connection:

UDPDatagramConnection udpc = null;


// Open the UDP Datagram Connection
udpc = (UDPDatagramConnection)
Connector.open("datagram://:1111");
In the preceding code snippet, the port number of the host
machine is specified as 1111.
Datagram communication does not implement
mechanisms for error checking and acknowledgement. As
a result, UDP does not guarantee the delivery of a packet
to its destination.

HTTP and HTTPS


MIDP uses the HTTP protocol for enabling
communication with Web servers. The advantages of using
an HTTP-based communication over a socket or a
datagram-based communication are:
All MIDP devices support HTTP communication,
but not socket-based communication.
A Socket-based or a datagram-based
communication is network dependent, but an
HTTP-based communication does not depend on
the type of network.
Different types of data, such as multimedia data,
can be encapsulated into an HTTP request.
The MIDP 2.x specification requires you to implement
both HTTP and HTTPS by using GCF. HTTPS uses
Secure Socket Layer (SSL), a protocol that allows mobile
devices and HTTP servers to communicate over a secure
network connection. SSL provides data security by
encrypting the data sent over the network and
authenticating the socket end-points.

The ServerSocket protocol enables a MIDlet to receive


incoming service requests for socket connections. When a
MIDlet receives a service request from a client, it creates a
socket for communication with the client and continues to
wait for other requests.
The ServerSocket is implemented by using the
ServerSocketConnection interface. The
ServerSocketConnection interface extends the
javax.microedition.io.StreamConnectionN
otifier interface.
The following code snippet implements the
ServerSocketConnection interface:
ServerSocketConnection sconnection =
(ServerSocketConnection) Connector.open
("socket://:23");
// wait for incoming connections
SocketConnection sc =
(SocketConnection)
sconnection.acceptAndOpen();
/*Set the socket opetions and perform
the operations to be performed after
the connection is made */
The preceding code snippet creates a
ServerSocketConnection object and listens for the
incoming connection at the port 23. The
acceptAndOpen() method returns a
SocketConnection object that represents a serverside socket connection.

Socket and ServerSocket


The Socket protocol allows a MIDlet to establish two-way
communication with a server over a network. The
ServerSocket protocol allows a MIDlet to act as a server
and enable other clients to connect to the server MIDlet by
using the Socket protocol.
The SocketConnection interface is used to send and
receive data to and from a remote host. You can open a
connection on the target machine by using the
Connector.open() method. For example, the
following code snippet opens a socket connection on the
host named host.com:
SocketConnection sconnect=
(SocketConnection) Connector.open
("socket://host.com");
In the above code snippet, the Connector.open()
method returns a SocketConnection object, which is
used to retrieve the local and remote port addresses and
control the socket options.

Just a minute:
Which protocol allows a MIDlet to act as a
server and enable other clients to connect to
the server MIDlet?

Answer:
ServerSocket protocol

Establishing Network Connection by


Using MIDP 2.x Classes

After the protocol to be used for network connectivity is


decided, you can establish a network communication
between two devices. The MIDP specification provides
two methods, open() and close(), to open and close a
network connection, respectively.

Opening a Network Connection


The open() method of the Connector class is used to
open an HTTP connection.
The following code snippet shows how to open an HTTPbased network connection:

InputStream mIn =
mHttpConnection.openInputStream();
int len = (int)
mHttpConnection.getLength();

Closing a Network Connection


You can use the close() method of the Connection
interface to close an existing connection.
The following code snippet shows how to close an
existing HTTP connection:

// Code for connection making......


try {
HttpConnection mHttpConnection =
(HttpConnection)Connector.open
("www.msweap.com",

mHttpConnection.close (); // Close any


open stream

Connector.READ_WRITE,true);

// Setting the request method and


headers

catch (IOException ioe) {


// Handle the exception

mHttpConnection.setRequestMethod
(HttpConnection.POST);
mHttpConnection.setRequestProperty
("Content-Type", "text/plain");
mHttpConnection.setRequestProperty
("Accept", "*/*");
mHttpConnection.setRequestProperty
("Connection", "close");
OutputStream os =
mHttpConnection.openOutputStream();

String requestString =
makeRequestString();
System.out.println("\n
\nOut<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<");

Creating Enterprise Applications by


Using Java ME
An enterprise application is a combination of client-side
applications, such as MIDP applications, and server-side
applications, such as servlets. Enterprise applications
enable you to use mobile devices to access enterprise
databases that are stored on servers. The servlets running
on different servers, such as Web servers, perform
database-related operations.
MIDP applications created by using Java ME platform
interact with these servlets to retrieve information, such as
news and forecasts, from the Web servers. You need to
configure the Web server to support servlets before
creating enterprise applications by using Java ME.
The following code snippet shows how to develop a
server-side application by using Java ME:
import java.io.*;

os.write((requestString+"\r
\n").getBytes());

import javax.servlet.*;

os.flush();

import javax.servlet.http.*;

if (os != null)
os.close();

public class News_Servlet extends


HttpServlet {

public void init() {

*/

}
public void doPost(HttpServletRequest
request,
/**
HttpServletResponse response)
* @param request Wrapper around
client data

throws IOException,
ServletException {

* @param response Wrapper around


Server response to client
*
* @throws IOException If any
problem occured in I/O operations

InputStream in;
OutputStream out;
DataInputStream din;
DataOutputStream dout;

* @throws ServletException If any


problem servlet specific

String news = "Elections in IRAQ held


under dark

problem occured
*/

shadow"+","+"India has done well in


second test";

public void doGet(HttpServletRequest


request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out =
response.getWriter();

try{
in = (InputStream)
request.getInputStream();

out.println("No GETs allowed.");


}

out = (OutputStream)
response.getOutputStream();

/**
* @param request Wrapper around
client data

din = new DataInputStream


(in);

* @param response Wrapper around


Server response to client
*

dout = new
DataOutputStream(out);

* @throws IOException if any


problem occured in I/O operations
* @throws ServletException if any
servlet specific problem
occured

byte[] requestRead =new


byte[200];

int byteRead= din.read


(requestRead);

String requestString =
requestRead.toString();

System.out.println ("**********\n
\nRequest Got From
client\n\n**********");

byte[] byteArr =
news.getBytes();

dout.write(byteArr);
System.out.println ("\n\n **********\n
\nnews is
sent..\n\n***************");

} catch (Throwable e) {
}
finally{
in = null;
out = null;
din = null;
dout = null;
}
}
}
In the preceding code, the News_Servlet class is a
subclass of the HttpServlet class. HTTP requests and
responses are handled by using the doGet() and
doPost() methods. The code also includes exception

handlers that handle the exceptions generated by the


doGet() and doPost() methods.

The steps required to compile, deploy, and run


a servlet are discussed in the section
Developing a News Application.

Developing a News Application


Problem Statement
Global Systems Inc. provides mobile and Web services to
its customers by using Java-based technologies, including
Java ME. You are working as a mobile application
developer with Global Systems Inc. and have been
assigned the task to develop a news application for mobile
phones. You need to ensure that the news application is
able to collect the news stored on a Web server. You also
need to ensure that the news is displayed on the mobile
device in the form of tickers. Therefore, you need to
develop an application that can interact with a servlet
running on the Web server and collect information from
the Web server.

Solution
To develop the required application, you need to perform
the following tasks:
1. Create and compile a server-side program.
2. Run and test the server-side program.
3. Create a NetBeans project
4. Add files to the project
5. Build and run the project.

Task 1: Creating and Compiling a ServerSide Program


To create the server-side program of the news application,
you need to perform the following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project from the NetBeans
IDE 6.0.1 window. The New Project dialog box
appears, as shown in the following figure.

created under the Projects tab of the NewsServer


- NetBeans IDE 6.0.1 window, as shown in the
following figure.

The New Project Dialog Box


3. Select the Web option from the Categories
section.
4. Ensure that the Web Application option is
selected in the Projects section.
5. Click the Next button. The Name and Location
page is displayed, as shown in the following
figure.

The NewsServer - NetBeans IDE 6.0.1


Window
11. Right-click index.jsp under the Projects tab, and
then select Delete. The Confirm Object
Deletion message box appears.
12. Click the Yes button to confirm deletion of the
index.jsp file.
13. Select FileNew File. The New File dialog box
is displayed, as shown in the following figure.

The Name and Location Page


6. Type NewsServer in the Project Name text box.
7. Ensure that <Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.
8. Ensure that GlassFish V2 is selected in the
Server drop-down list.
9. Click the Next button. The Frameworks page is
displayed, as shown in the following figure.

The Frameworks Page


10. Click the Finish button. The NewsServer node is

The New File Dialog Box


14. Ensure that the Web option is selected in the
Categories section.
15. Select the Servlet option from the File Types
section.
16. Click the Next button. The Name and Location
page is displayed, as shown in the following
figure.

public void doGet


(HttpServletRequest request,
HttpServletResponse response)
throws IOException,
ServletException {

The Name and Location Page


17. Type News_Servlet in the Class Name text box.
18. Type News in the Package combo box.
19. Click the Next button. The Configure Servlet
Deployment page is displayed, as shown in the
following figure.

PrintWriter out =
response.getWriter();
out.println("No GETs
allowed.");

public void doPost


(HttpServletRequest request,
HttpServletResponse response)

The Configure Servlet Deployment Page


20. Click the Finish button to create the
News_Servlet.java file.
21. Replace the existing code for the
News_Servlet.java file in the Editor with the
following code:
package News;
import java.io.*;

throws IOException,
ServletException {
InputStream in;
OutputStream out;
DataInputStream din;
DataOutputStream dout;
String news = "Elections
in IRAQ held under dark

import javax.servlet.*;
import javax.servlet.http.*;

public class News_Servlet extends


HttpServlet {

shadow"+","+"India has
done well in second test";

try{
in =(InputStream)
request.getInputStream();

public void init() {


}

out =(OutputStream)
response.getOutputStre

} catch (Throwable e) {

am();
}
finally{
din = new
DataInputStream(in);

in = null;
out = null;

dout = new
DataOutputStream(out);

din = null;
dout = null;
}

byte[] requestRead
=new byte[200];

}
}
int byteRead= din.read

(requestRead);

String requestString =
requestRead.toString
();

Task 2: Running and Testing the ServerSide Program


To run and test the server-side program, you need to
perform the following steps:
1. Select RunRun FileRun
News_Servlet.java. The Set Servlet
Execution URI dialog box appears, as shown in
the following figure.

System.out.println
("**********\n\nRequest
Got From client\n
\n**********");

The Set Servlet Execution URI Dialog Box


byte[] byteArr =
news.getBytes();

dout.write(byteArr);
System.out.println
("\n\n **********\n\nnews
is sent..\n
\n***************");

2. Click the OK button. A browser window appears


with a Web page displaying the text, No GETs
allowed, as shown in the following figure.

The Web Page

Task 3: Creating a NetBeans Project


To create a NetBeans Project, you need to perform the
following steps:
1. Switch to the NetBeans window.
2. Select FileNew Project to open the New
Project dialog box.
3. Select the Mobility option from the Categories
section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name and Location
page is displayed.
6. Type NewsApplication in the Project Name text
box to assign a name to the new project.
7. Ensure that <Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.
8. Clear the Create Hello MIDlet check box.
9. Click the Next button. The Default Platform
Selection page is displayed.
10. Click the Next button. The More Configurations
Selection page is displayed.
11. Click the Finish button to create the
NewsApplication project.

Task 4: Adding Files to the Project


For adding files to the NewsApplication project, you need
to perform the following steps:
1. Select FileNew File to open the New File
dialog box.
2. Ensure that the MIDP option is selected in the
Categories section.
3. Ensure that the MIDlet option is selected in the
File Types section.
4. Click the Next button. The Name & Location
page is displayed.
5. Type NewsMidlet in theMIDlet Name text box
to assign a name to the new MIDlet.
6. Click the Finish button to create the
NewsMidlet.java MIDlet.
7. Replace the existing code for the
NewsMidlet.java MIDlet in the Editor with the
following code:
import
javax.microedition.midlet.*;
import
javax.microedition.lcdui.*;
public class NewsMidlet extends
MIDlet {
public static NewsMidlet
instance;
News displayable;
public static String
SERVER_URL = null;

/** Constructor */
public NewsMidlet() {
instance = this; //Read From
JAD File if there are any
parameters
SERVER_URL = getAppProperty
("URL");
}
/** Main method */
public void startApp() {
try{
displayable = new News();
}catch(Exception e){
e.printStackTrace();
}
}
/** Handle pausing the MIDlet
*/
public void pauseApp() {
}
/** Handle destroying the
MIDlet */
public void destroyApp(boolean
unconditional) {
}
/** Quit the MIDlet */
public static void quitApp() {
instance.destroyApp(true);
instance.notifyDestroyed();
instance = null;
}
}
8. Select FileNew File to open the New File
dialog box.
9. Select the Java option from the Categories
section.
10. Ensure that the Java Class is selected in the File
Types section.
11. Click the Next button. The Name and Location
page is displayed.
12. Type News in theClass Name text box to assign a
name to the new Java class file.
13. Click the Finish button to create the News.java
class file.
14. Replace the existing code for the News.java class
file in the Editor with the following code:
import java. io.*;
import
javax.microedition.lcdui.*;
import javax.microedition.io.*;
import

javax.microedition.lcdui.Command;
import
javax.microedition.lcdui.CommandL
istener;

class News implements


CommandListener {
Command CMDEXIT;
int i = 0;
private Form newsForm;
public boolean inRequest =
false;
public static long timeout =
0L;
private HttpConnection
mHttpConnection;
private InputStream is = null;
private OutputStream os =
null;
private String CommandType =
null;
private
null;
private
private
private
= null;

StringBuffer sb =
int count = 0;
int requestType = 0;
String serverResponse

public News() throws Exception

CMDEXIT = new Command


("Exit",1,Command.EXIT);
newsForm.addCommand
(CMDEXIT);
newsForm.setCommandListener
(this);
}catch(Exception e){
System.out.println
("Exception is "+e.getMessage());
}
}
private void showWaitScreen(){
Form waitForm = new Form
("Wait Form");
waitForm.append("Please
Wait...");
Display.getDisplay
(NewsMidlet.instance).setCurrent
(waitForm);
}
/**Handle command events*/
public void commandAction
(Command c, Displayable disp) {
int cmdType =
c.getCommandType();
try{
if(c == CMDEXIT){
NewsMidlet.quitApp();
}

{
try{
run();
Display.getDisplay
(NewsMidlet.instance).setCurrent
(newsForm);
}catch(Exception e)
{
}
}
private void
showServicesScreen(String scrlst)
{
try{
newsForm = new Form("News
Application");
// creating and initializing
a ticker
Ticker tick = new Ticker
(scrlst);
newsForm.setTicker(tick);
newsForm.setCommandListener
(this);

}catch(Exception e){
System.out.println
("Exception is thrown");
e.printStackTrace();
}
}
public synchronized String
MakeConnection(StringBuffer
values, int cnt, int requestType)
{
StringBuffer sbuffer = null;

try{
//making an HTTP connection
mHttpConnection =
(HttpConnection) Connector.open
(NewsMidlet.SERVER_URL,Connector.
READ_WRITE, true);
// Set the request
method and headers

mHttpConnection.setReque
stMethod(HttpConnection.POST);
mHttpConnection.setReque
stProperty("Content-Type", "text/
plain");
mHttpConnection.setReque
stProperty("Accept", "*/*");
mHttpConnection.setReque
stProperty("Connection",
"close");
//Making Request
Here....
String xml =
makeRequestXML(values, cnt,
requestType);
os =
mHttpConnection.openOutputStream
();
os.write( (xml + "\r
\n").getBytes());
os.flush();
if (os != null)
os.close();
is =
mHttpConnection.openInputStream
();
int len = (int)
mHttpConnection.getLength();
byte data[] = new byte
[len + 1];
sbuffer = new
StringBuffer();
int ch = 0;
while ( (ch = is.read
()) != -1) {
sbuffer.append
( (char) ch);
}
System.out.println
("Value Read is >> " +
sbuffer.toString());

try {
System.gc();
is = null;
mHttpConnection = null;
} catch (Exception exp) {}
return sbuffer.toString();
}
public void run(){
try {
serverResponse =
this.MakeConnection(sb, count,
requestType);
}catch (Exception e) {
System.out.println("Here is
Exception in run () method " +
e.getMessage());
}
showServicesScreen
(serverResponse);
}
//making request string
private String makeRequestXML
(StringBuffer value,int count,
int reqType){
String Request_XML = null;
if(reqType==1){
Request_XML = reqType
+"#"+value;
}
return Request_XML;
}
}
15. Right-click the NewsApplication node under the
Projects tab and then select the Properties
option from the pop-up menu. The
NewsApplication dialog box is displayed, as
shown in the following figure.

}catch(IOException ioe){
System.out.println("Here is
exception while making
connection....");
}
mHttpConnection = null;
is = null;
os = null;

The NewsApplication Dialog Box

16. Select Application Descriptor from the


Category section.
17. Ensure that the Attributes tab is selected.
18. Click the Add button. The Add Attribute dialog
box is displayed, as shown in the following
figure.

The Add Attribute Dialog Box


19. Type URL in the Name text box.
20. Type http://localhost:8080/NewsServer/
News_Servlet in the Value text box.
21. Select the JAD option from the Placement dropdown list.
22. Click the OK button to add the attribute, as
shown in the following figure.

The NewsApplication Dialog Box with Added


Attributes
23. Click theOK button to close
theNewsApplication dialog box.

Task 5: Building and Running the Project


1. Select BuildBuild Main Project to build the
NewsApplication project.
2. Select RunRun Main Project to execute the
NewsApplication project. The
DefaultColorPhone emulator window appears, as
shown in the following figure.

The DefaultColorPhone Emulator Window


3. Click the soft key below Launch to launch the
NewsMidlet MIDlet. The Is it OK to Use
Airtime ? screen is displayed, as shown in the
following figure.

The DefaultColorPhone Emulator Displaying


the Is it OK to Use Airtime ? Screen
4. Click the soft key below Yes. The News
Application screen is displayed with the news
collected from the Web server in the form of a
ticker, as shown in the following figure.

The DefaultColorPhone Emulator Displaying


News
5. Select MIDletExit to close the
DefaultColorPhone emulator window.
6. Select FileExit to close the NetBeans IDE.

Summary
In this chapter, you learned that:
In J2ME, CLDC and MIDP are used to develop
applications for mobile devices.
GCF is a set of classes included in CLDC that
enables you to establish network
communications.
The components of GCF are:

The Connector class


The
ConnectionNotFoundException
exception
Seven interfaces
Both the CDC and CLDC support GCF.
GCF itself does not provide any protocol
implementation, but it allows the vendors
implementing MIDP to implement the required
protocol by implementing the corresponding
interface.
The limitations of GCF are:
Does not provide FTP and Telnet services
Does not support object serialization
Does not allow you to access files
TheConnector class of GCF enables you to
establish network connections between mobile
devices.
MIDP provides networking services by using the
javax.microedition.io package.
The three types of networking in J2ME are:
Low-level networking
Secure networking
HTTP networking
The network protocols supported by MIDP 2.x
are:
HTTP and HTTPS
TCP/IP and UDP
Server and ServerSocket
MIDP 2.x makes it necessary for the vendors
providing MIDP to implement HTTP and
HTTPS.
Enterprise applications are used to retrieve
information from servers by using mobile
devices.

Exercises
Exercise 1
You are working as a mobile application developer with
PerryB Inc. and have been assigned the task to develop a
cricket updates application for mobile phones. You need to
ensure that the cricket updates application is able to collect
the updates of cricket stored on a Web server. You also
need to ensure that the updates are displayed on the mobile
device in the form of tickers. Therefore, you need to
develop an application that can interact with a servlet
running on Web server and collect information from the
Web server.

Reference Reading
Creating Network Connections Using

Generic Connection Framework


Reference Reading: Books Reference Reading: URLs
Enterprise J2ME:
http://developers.sun.com/
Developing Mobile Java
techtopics/mobility/midp/
Applications By John W.
articles/genericframework/
Muchow Publisher: Prentice
Hall PTR.
Java 2 Micro Edition
Application Development By
Michael Kroll Stefan
Haustein Publisher: Sams
Publishing

Implementing Networking
Connectivity by Using MIDP
Reference Reading: Books Reference Reading: URLs
Enterprise J2ME:
http://www.cssathya.com/
Developing Mobile Java
software/tutorials/
Applications By John W.
development/java/
Muchow Publisher: Prentice certification/scmad/docs/
Hall PTR.
pdf/04_SCMAD.pdf
Java 2 Micro Edition
http://developers.sun.com/
Application Development By techtopics/mobility/midp/
Michael Kroll Stefan
articles/genericframework/
Haustein Publisher: Sams
Publishing

Chapter 9
Implementing Security Features in
CLDC and MIDP
These days, mobile devices are used for storing personal
information. It is also very common for users to download
applications onto their mobile devices. Users want to be
sure that downloading data on to their mobile devices do
not corrupt the information and disturb the stability of
their devices. The harmful application can corrupt the
mobile phone and its data by virus attacks. Also, while
connecting to the website for downloading the application
or accessing some information, there is a threat to the
information sent through the device. Therefore, it is
necessary to provide security to mobile applications in
order to ensure the safety of mobile devices and the
information sent through it.
This chapter discusses various aspects of MIDlet security.
It also discusses implementing security features in CLDC
and MIDP.

Objectives
In this chapter, you will learn to:
Implement MIDlet security
Sign the city guide application

Implementing MIDlet Security


Mobile applications allow users to connect to Web servers
and other mobile devices through Bluetooth or Infra-Red
(IR) for downloading applications on a mobile device.
However, these downloaded applications can carry viruses
that might be a potential threat to the security of the
mobile device and its functioning. Therefore, you need to
provide security to mobile applications to avoid various
threats. These threats can lead to the crashing of the
application and therefore, losing the saved information on
mobile devices.
Similarly, while accessing the Web server through a
mobile device, it is possible for unauthorized users to
access personal information stored in a mobile device.
Therefore, you need to restrict such users from accessing
confidential information and data stored in your mobile
device.
The security framework of Java SE platform cannot be
made available for Java ME due to its memory
restrictions. In fact, Java ME has a security model that is
simpler as compared to the security model of Java SE.
This security model of Java ME is defined at the following

levels:
Low-level security: Ensures that the MIDlet
applications do not harm the mobile device in
which it is executed. It relates to the verification
of the MIDlet suite's class files. The verification
is partially done by the developer in the
preverification step and partially on the mobile
device in which the application is executed.
Application-level security: Ensures that the
MIDlet applications are secure by limiting the
access to libraries that are accessible in the JRE.
This requirement is ensured by running the
application in a testing environment called
sandbox. In addition, the application-level
security does not allow the user to override the
profile-specific or manufacturer-specific
packages, such as javax.microedition.*
and java.*. Furthermore, it ensures that the
applications can only load classes that are
included in their own JAR file.

Implementing Application-level
Security
MIDP 2.0 introduces a new security model. It allows
MIDlet developers to use certain APIs that are considered
as sensitive or restricted.
Consider an example where you need to connect to an
online banking application by using the HTTP connection.
In such a case, a person might get access to your username
and password that are being sent over the network to the
server. Consequently, the APIs for network connections
are considered as restricted.
Therefore, you need to provide application-level security
to network-based applications in order to secure them.
Application-level security involves implementing security
mechanisms in the MIDlet application itself. As a result,
you can create highly secure network-based applications
that enable you to access and share online information and
resources. Application-level security ensures security of an
application by providing restricted access to those
resources and components that are installed on to a mobile
device.
MIDP 2.x provides several new mechanisms to implement
application-level security. MIDP 2.0 introduces the
concept of trusted and untrusted MIDlets. If the device is
able to verify the authenticity and integrity of a MIDlet
suite and assign it to a protection domain, then the MIDlet
suite is said to be trusted, else the MIDlet suite is treated
as untrusted by the mobile device.

Permissions
In MIDP version 2.0, the security model was enhanced to
allow MIDlets to access APIs that are considered

sensitive. To make any type of network connection, such


as an HTTP connection, is considered as a sensitive
operation that may involve monetary costs for the user. A
MIDlet that uses an HTTP connection must have
permission to open an HTTP connection.
The permissions defined in MIDP 2.0 correspond to
network connection APIs. However, the security
architecture of MIDP 2.0 allows optional APIs to define
their own permissions.

Protection Domains
In MIDP 2.x, security is based on the concept of
protection domains. A protection domain is a set of
allowed permissions and user interaction modes. When a
MIDlet suite is installed, it is assigned to a given
protection domain and acquires its permissions and
interaction modes.
A protection domain consists of the following parts:
Permissions that are allowed and permissions for
which the user must be consulted
Criteria for entry into the protection domain
The Java ME Wireless Toolkit 2.5.2 includes the following
protection domains for the JTWI specification:
Untrusted
Trusted
Minimum
Maximum
MIDlets in the Trusted and Maximum domains are
granted all permissions. MIDlets in the Untrusted
domain prompt the user for every permission. MIDlets in
the Minimum domain are denied all permissions.

Permission Types
The following types of permissions are granted to a
MIDlet to enable it to run on a mobile device:
Allowed permissions: These types of
permissions are granted to a MIDlet when it is
developed or deployed. The MIDP 2.x
implementation automatically checks these
permissions before running a MIDlet on a mobile
device. Allowed permissions allow MIDlet suites
to access protected methods and APIs in the
protection domain.
User permissions: These types of permissions
require user interaction. The user can either deny
the permission or allow it. When a MIDlet that
requires user permissions is run, the mobile
device prompts the users whether to run the
MIDlet or not.
The protection domain contains the permissions that will
be granted to MIDlets (allowed permissions) as well as the
permissions for which the user must be consulted (user
permissions). Allowed permissions allow MIDlet suites to
access protected methods and APIs in the protection
domain without any user interaction. However, user
permissions prompt a user for an interaction mode.

Interaction Modes for User Permissions


After the user authorizes for an interaction mode, the
MIDlet suite is granted access to the protected methods
and APIs in the protection domain. However, a user can
deny or grant permission for any of the following
interaction modes:
blanket: Allows permission to all the methods
or APIs requested by the MIDlet suite until the
user modifies the permission.
session: Allows permission for all the methods
or APIs requested by the MIDlet suite until the
MIDlet terminates. A session interaction mode
prompts the user only at the beginning of a
session when the MIDlet suite is launched. The
user prompt is repeated when the user relaunches the MIDlet suite.
oneshot: Allows permission for the current
request for a method or an API. This mode
prompts the user on each invocation of the
protected method or API.

Trusted MIDlet Suite


The MIDP 2.0 specification introduces the concept of
trusted MIDlet suites. A trusted MIDlet suite is a MIDlet
suite for which a mobile device can determine the source,
authenticity, and integrity of the JAR file.
A trusted MIDlet suite can be assigned to any protection
domain and its permissions are granted according to its
protection domain. For example, if the
javax.microedition.io.Connector.http
permission was requested and the MIDlet application has
Allowed permission, no user confirmation will be
needed to open an HTTP connection.
MIDP 2.0 and above specification implements the concept
of trusted MIDlet suites that can access restricted APIs and
resources on mobile devices. The MIDP 2.x
implementation checks against a root certificate associated
with the protection domain of that suite to verify whether a
MIDlet suite is trusted or not.

A certificate is an electronic document that


checks the authenticity of the document.
A trusted MIDlet suite is digitally signed and verified by
using the X.509 certificate Public Key Infrastructure
(PKI). A certificate conforms to the ISO X.509
authentication protocol that defines the structure of X.509
PKI. A Certificate Authority (CA) authorizes the
certificate by using a private key to sign a certificate.
Authorization allows only authenticated mobile
applications to access the resources of a mobile device.
Authorization determines whether a MIDlet suite is
granted a requested permission or not.

A MIDlet suite that requires mandatory access to protected


methods and APIs need to mention the corresponding
permissions in the MIDlet-Permissions attribute of
the JAR or JAD file. Alternatively, a MIDlet suite that
requires optional access to protected methods and APIs
need to mention the corresponding permissions in the
MIDlet-Permissions-Opt attribute of the JAR file.
For example, a mobile device user is able to play a game
as a single-player instead of multiple-player if the
requested permissions are not granted.
In order to authorize itself, a trusted MIDlet suite uses the
following information:
A set of permissions for the protected APIs and
functions on the device. This is a union of all
permissions defined by every API on the device
for protected functions.
A protection domain consisting of a set of
Allowed and User permissions.
A set of permissions requested by the MIDlet
suite in the MIDlet-Permissions and
MIDlet-Permissions-Opt attributes of its
JAR manifest or application descriptor.
The user who may be asked to grant permissions.
The following conditions needs to be true for granting and
invoking permissions for a trusted MIDlet suite:
The MIDlet suite needs to be associated with a
protection domain.
The requested crucial permissions need to be
retrieved from the MIDlet-Permissions
attribute and non-crucial permissions need to be
retrieved from the MIDlet-PermissionsOpt attribute of the JAR or JAD file. These
attributes need to be identical to the
corresponding attributes in the JAR file, if they
are listed in the JAD file. Otherwise, the MIDlet
suite should not to be installed or invoked.
The requested permissions need to be removed if
they are not crucial and are unidentified for a
mobile device.
The MIDlet suite need not be installed or invoked
if the requested permissions are indicated as
crucial but are unidentified for a mobile device.
The MIDlet suite need not be installed or invoked
if the requested permissions do not exist in a
protection domain. However, these permissions
are indicated as crucial, as the MIDlet suite does
not have sufficient authorization.
The MIDlet suite needs to be installed or invoked
even if the requested permissions are not
indicated as crucial. However, these permissions
do not exist in the protection domain.
The user needs to provide authorization to grant
permissions to a MIDlet suite, if the requested
permissions correspond to the User permissions

of the protection domain.


The permissions that are granted to a MIDlet
suite is an intersection of requested permissions
with the combination of User and Allowed
permissions.
The restricted APIs need to be verified for
required permissions during the execution of a
MIDlet suite. An exception called as the
SecurityException exception is thrown if
the permission is not granted.

Untrusted MIDlet Suite


A MIDlet suite is defined as untrusted by the MIDP 2.0
specification if the origin and integrity of the JAR file
cannot be verified by the mobile device. For example,
MIDlets downloaded from unknown resources are treated
as untrusted MIDlets.
Untrusted MIDlets require explicit user permission to
access restricted APIs. Untrusted MIDlet suites can also be
run in a restricted environment, known as untrusted
domain, to prevent access to restricted APIs and mobile
device resources.
MIDP 1.0 MIDlet suites are by default untrusted.
Untrusted MIDlets can call any APIs without permission,
if they are not protected.
The following table lists the APIs and their protocols that
an untrusted domain needs to provide with explicit
confirmation by the user for untrusted MIDlet suites.
APIs
Protocols
javax.microedition. HTTP
io.HttpConnection
javax.microedition. HTTPS
io.HttpsConnection

Table Listing the APIs provided by an Untrusted


Domain with Explicit Confirmation
The following table describes the APIs that an untrusted
domain needs to provide without explicit confirmation by
the user for untrusted MIDlet suites.
APIs
Description
javax.microedition. RMS APIs
rms
javax.microedition. MIDlet Lifecycle APIs
midlet
javax.microedition. User Interface APIs
lcdui
javax.microedition. Game APIs
lcdui.game
javax.microedition. Multi-media APIs for
media
playback of sound. Directly
compatible building block of
the Mobile Media (JSR-135)

specification
javax.microedition. Multi-media APIs for
media.control
playback of sound. Defines
the specific Control types
that can be used with a
Player.

Table Describing the APIs provided by an Untrusted


Domain without Explicit Confirmation
In case an untrusted MIDlet suite tries to invoke a
protected API and doesn't have the permission to invoke it,
then the exception named the SecurityException
exception will be thrown. The MIDlet needs to catch this
exception and handle it. For example, when an untrusted
MIDlet tries to open an HTTP connection, the user is
prompted for the permission. If the user does not grant this
permission, a SecurityException exception is
thrown.

Just a minute:
State weather the following exception is true
or false.
The blanket interaction mode allows
permission to all the methods or APIs
requested by the MIDlet suite until the user
modifies the permission.

Analyzing the Sandbox Model


The sandbox security model of CLDC/MIDP addresses the
application-level security of MIDP 1.0. The sandbox
security model, which is also referred as a MIDP 1.0
security model, secures the device resources from
malicious codes.

Understanding the Sandbox Model


The sandbox model is used in Java SE to ensure the
security of the machine on which a downloaded applet is
run. Although the sandbox model of MIDP is based on the
Java SE sandbox model, it restricts certain features of Java
SE from providing security to mobile devices with low
resources. Some of these features include reflection
features, JNI, user defined class loaders, security related
packages, and the security manager that is present in Java
SE.
In the sandbox model, according to the CLDC
specification, the local and trusted MIDlets are allowed to
access the resources of a mobile device. However, the
untrusted MIDlets are restricted from accessing the system
resources and APIs. As a result, the sandbox model of Java
ME ensures the security of device resources and Java code
when a MIDlet is run.
Some of the basic components of the sandbox security
model include the verification tool, applet class loader,
and security manager. In addition, the security features
built into JVM and Java APIs are the components of the
sandbox security model.
The following figure shows the sandbox model.

Answer:
True

The Sandbox Model

Just a minute:
Which exception is thrown when a required
permission is not granted to a MIDlet suite?

Answer:
The SecurityException exception

The characteristics of the sandbox model are:


Ensures that the CLDC preverifier and runtime
verification tools authenticate the Java class files
and MIDlet. This prevents execution of any
untrusted code before being verified. When a
Java source program is compiled it is translated
to a platform-independent Java byte code, which
is then verified by the verifier before being run
on a JVM.
Ensures that only a restricted and predefined set
of APIs is available to application developers.

Ensures that an application developer downloads


MIDlets in the virtual machine at the native code
level. This prevents application developers from
overriding the standard class loading mechanisms
of virtual machine.
Ensures that an application developer cannot use
native code, such as the Runtime.exec()
method that is not included in the predefined
packages of Java.
Ensures that user-defined classes are not
provided to application developers. As a result,
application developers cannot override the
standard class loading mechanisms of the KVM.
Ensures that an application developer is not able
to access native functions that are not supported
by CLDC and MIDP.
Ensures that an application developer is not able
to download new libraries that are not supported
by CLDC and MIDP.
Ensures that only the applet class loader
determines when and how an applet can add
classes to a JRE. This ensures that the code that
an applet tries to install do not accidentally
replace the important elements of the JRE.
Ensures that only pre-defined packages, such as
MIDP and WMA are available to application
developers.
Ensures that thread groups and daemon threads
are not allowed to run on mobile devices.
Ensures that the security manager verifies the
operation performed by untrusted applets or
codes. This prevents the untrusted applets or
codes from performing any critical operation on
the mobile device that may damage the device.

Security provided by MIDP 1.0 is not sufficient


to secure the MIDlets from network attacks
and packet sniffing. The sandbox security
model of MIDP 1.0 only secures the device
resources from malicious codes and MIDlets.
This is because:
MIDP 1.0 support only HTTP and does not
support HTTPS.
A MIDlet in MIDP 1.0 is not able to access a
record store that belongs to another MIDlet.
MIDP 1.0 does not allow sharing of record store
between MIDlets.

Analyzing MIDlet Signing Process


Consider a situation where a user frequently downloads

information from a Web server. Every time the user


downloads an application, the mobile device prompts the
user for allowing the application to run. The application is
executed if the user grants the permission, otherwise it is
not executed. Such frequent prompts can be avoided by
ensuring that the MIDlet application comes from a trusted
source.
An application code signing process ensures that MIDlet
applications come from a trusted source, so that they can
get access to restricted APIs. Although an application need
not be signed to be executed on a mobile device, it just
eliminates the messages for granting permissions.
Signing a MIDlet ensures that:
The MIDlet application gets access to securitysensitive operations, such as opening an HTTP
connection, on the mobile device.
Some malicious programs do not corrupt the
mobile device.
Signing a MIDlet suite involves adding a digital signature
and signer certificate of a JAR file to a JAD file. You need
to build and package the MIDlet suite before signing it.
Digital signing makes use of the public-key cryptography
and digital certificate concepts.
Java Wireless Client checks the validity of a signed
MIDlet suite by using the public keys from a CA. Signed
MIDlet suites contain a certificate that is signed by a CA,
who assures the authenticity of the MIDlet suite.
The signing process of a MIDlet suite involves using a
keytool utility known as the Java Application Descriptor
Tool (JADTool), and Mobile Equipment Key Tool
(MEKeytool). The keytool utility is a GUI utility that
requests the JADTool and MEKeyTool to sign a MIDlet
suite. JADTool is a command-line tool, which uses public
key cryptography for signing MIDlet suites. MEKeyTool
is a command-line tool used to manage public keys of
CAs.
A certificate is stored in the ME keystore file of
MEKeyTool when a key pair is created in Java ME
Wireless Toolkit. You can use the security keytool utilities
to:
Create a new key pair and mention its alias name.
Copy the certificate from the Java SE Keystore to
the Java ME Keystore.
Add the certificate to the JAD file of the MIDlet
suite.
Digitally sign the JAR file of the MIDlet suite to
the JAD file.
Delete an obsolete certificate.
Assigning a security domain to a certificate determines the
level of trust that a certificate owner has in order to access
the restricted APIs.
To specify a trusted domain MIDlet suite, you need to sign
the MIDlet suite. To sign a MIDlet suite, you need to
perform the following tasks:

1. Obtain an appropriate cryptographic key/


certificate pair to do the signing.
2. Insert the certificate in the JAD.
3. Create the signature and apply it to JAD.
4. Authenticate a MIDlet suite.
5. Verify the signer certificate.
6. Verify the MIDlet suite JAR.
7. Include the list of permissions the MIDlet suite is
requesting in the JAD file and manifest file.

Obtaining a Certificate
A mobile device validates the certificate associated with a
MIDlet suite by using zero or multiple root certificates. A
device needs to support the X.509 certificate to validate
these certificates. The signer of the certificate needs to be
aware of the authorization policy for the device and
contact the appropriate certificate authority.
To obtain a certificate, you need to perform the following
steps:
1. Generate a new public/private key pair by using
an appropriate tool.
2. Generate a Certificate Signing Request (CSR) by
performing the following steps:
1. Click Generate CSR in the signing
window.
2. Enter a new path or click Browse and
select a new file location to save the
CSR file.
3. Click Create to write the CSR file.
3. Send the CSR to a CA. The CA verifies your
identity, takes payments for the certificate that
needs to be generated, and then wraps the public
key in a certificate, and sends it back to you.
You need to import the certificate that you have obtained
from the CA back into your keystore so the certificate is
available with you when you need to sign any MIDlet
suite.

Inserting the Certificate in the JAD


File
The certificate path contains the signer certificate and
other required certificates. However, it does not contain
the root certificate because it exists on the mobile device.
To insert the certificate in the JAD file, encode the
certificate in the path by using the base64 encoding
standard. The encoding is performed without line breaks.
The following code snippet inserts the certificate in the
JAD file:
MIDlet-Certificate-<n>-<m>: <base64
encoding of a certificate>
where:

<n>: Represents the sequence in which you test


the certificates to determine if the corresponding
root certificate is on the mobile device. The <n>
parameter is equivalent to 1 for first certification
path in the descriptor or 1 more than the previous
number for additional certification paths.
<m>: Is equivalent to 1 for the signer's certificate
in a certification path or 1 more than the previous
number for successive intermediate certificates.

Creating the RSA SHA-1 JAR


Signature and Applying it to JAD
To create a JAR signature and apply it to JAD, you need to
perform the following steps:
1. Create the JAR signature by using the signer's
private key in accordance with the EMSAPKCS1-v1_5 encoding method of PKCS #1
version 2.0 standard.
2. Insert the JAR signature in the application
descriptor, which is base64 encoded, and format
it as a single MIDlet-Jar-RSA-SHA1 attribute
without line breaks. The following code shows
the base64 encoding of a JAR signature:
MIDlet-Jar-RSA-SHA1
The signer of a MIDlet suite protects the assets and
capabilities of a protection domain owner and verifies the
MIDlet suite before signing it. A protection domain root
certificate owner delegates signing of MIDlet suites to an
intermediary, such as an author of the MIDlet, in case
there is a trusted relationship between the MIDlet suites.

Authenticating a MIDlet Suite


A mobile device needs to verify whether authentication is
required when a MIDlet suite is downloaded. To
authenticate a MIDlet suite, the mobile device needs to
authenticate the JAR by verifying the signer certificates
and JAR signature, if the MIDlet-Jar-RSA-SHA1
attribute is present in the JAD.
There is no need to authenticate the JAD files that do not
contain the MIDlet-Jar-RSA-SHA1 attribute, because
these JAR files are installed and invoked as untrusted
MIDlet suites.

Verifying the Signer Certificate


The signer certificate needs to be authenticated to confirm
that the MIDlet suite is from a trusted source. To verify the
signer certificate, you need to perform the following steps:
1. Retrieve the certification path for the signer
certificate from the attribute of the JAD file. For
example, MIDlet-Certificate-1-<m> is
the certification path where <m> starts at 1 and
increases by 1 until there is no other attribute
with the given name. The certification path is also
known as certification chain. The value of each
attribute in the certificate path needs to be
decoded and parsed because the values are

written in base64-encoded standard.


2. Authenticate the certification path by using the
protection domains that is a trustworthy source of
protection domain root certificates.
3. Combine the MIDlet suite with the protection
domain to authenticate the first certificate path
from the signer of certificate with root certificate
and continue with the installation. The root
certificate is the certificate that is integrated in
the SIM (Subscriber Identity Module) card of the
mobile device or in the device itself.
4. Repeat steps 1, 2, and 3 if the MIDletCertificate-<n>-<m> attribute with <n>
greater than 1 is present. In addition, if the full
certification path is not able to establish even
after verifying the MIDlet-Certificate<1>-<m> for the value <n> greater by 1 than the
previous value.

Verifying the MIDlet Suite JAR


After verifying the signer certificate, the MIDlet suite JAR
file also needs to be validated to confirm the integrity and
confidentiality of the MIDlet suite. To verify the JAR file
of a MIDlet suite:
1. Retrieve the public key from the authenticated
signer certificate.
2. Retrieve the MIDlet-Jar-RSA-SHA1
attribute from the JAD file.
3. Decode the value of the attribute from base64 by
generating a PKCS #1 signature.
4. Verify the signature by using the signer's public
key, signature, and SHA-1 digest of the JAR. The
application descriptor and MIDlet suite is
rejected, if the signature verification fails. The
JAR should not be installed or allow MIDlets
from the MIDlet suite to be invoked in case of
failure.
When the verification of the certificate, signature, and
JAR is complete, the content of the MIDlet suite is
integrated and the identity of the signer is made available.
This process needs to be executed at the time of installing
the MIDlet suite.

The process of verifying whether a MIDlet


suite is trusted is done during installation or
before launching the MIDlet suite. When a
MIDlet suite is verified, the device will
perform the basic security checks, such as
attribute checks and class verification.
The following table lists the various conditions and
corresponding verification results of a MIDlet suite.

Initial State
If JAD is unavailable and
JAR is downloaded.

Verificataion Result
Authentication cannot be
accomplished. You may need
to install JAR. Therefore, the
MIDlet suite is considered
as untrusted.
If JAD is available but JAR Authentication cannot be
is unsigned.
accomplished. You may need
to install JAR. Therefore, the
MIDlet suite is considered
as untrusted.
If JAR is signed but there is Authentication cannot be
no root certificate available accomplished and the JAR
in the keystore to validate installation is not allowed.
the certificate chain.
If JAR is signed but a
Authentication cannot be
certificate on the path has accomplished and JAR
expired.
installation is not allowed.
If JAR is signed but a
JAD is rejected and JAR
certificate is rejected for
installation is not allowed.
reasons other than
expiration.
If JAR is signed and the
JAD is rejected and JAR
certificate path is validated installation is not allowed.
but signature verification
fails.
If JAR is signed, certificate JAR installation is allowed.
path is validated and the
signature is verified.

Table Listing Conditions and Their corresponding


Verification Results of a MIDlet Suite

Including List of Permissions in the


JAD and Manifest File
Once you have verified the MIDlet suite JAR, you need to
include the list of permissions that your MIDlet suite is
requesting in the JAD file and manifest file of the MIDlet
suite.
A MIDlet suite that requires mandatory access to protected
methods and APIs need to mention the corresponding
permissions in the MIDlet-Permissions attribute of
the JAD file and the manifest file. Alternatively, a MIDlet
suite that requires optional access to protected methods
and APIs need to mention the corresponding permissions
in the MIDlet-Permissions-Opt attribute of the
JAR file.
For example, the following code snippet shows the list of
permissions added in a JAD file and a manifest file of a
MIDlet suite:
MIDlet-Permissions:
javax.microedition.io.Connector.http,
javax.microedition.io.Connector.https23

MIDlet-Permissions-Opt:
javax.wireless.messaging.sms.receive,
javax.wireless.messaging.sms.send

Just a minute:
Christine Turner is a mobile application
developer with Super Graphics. She is
developing a mobile application. While
developing the application Christine needs to
verify the JAR file of a MIDlet suite she has
developed for the application. She executes the
JAR at the time of installing the MIDlet suite.
However, the verification process is not
accomplished. What could be the possible
reason of error?

Answer:
JAD is unavailable and JAR is downloaded

Analyzing Certificates/X.509
Certificate Profile
MIDP X.509 Certificate Profile helps to implement trusted
MIDlet suites. This profile supports WAP-211WAPCert-20010522-a WAP Certification Profile, which
supports the Internet X.509 Public Key Infrastructure
Certificate. A Certificate Profile includes processing,
expiring, and revoking of a certificate.

Processing Certificate for OTA


MIDP 2.x specification includes Over-The-Air (OTA)
protocol to download the MIDlets from a server to a
mobile device. A mobile device needs to identify the
extension of the private or public keys and verify whether
the digital signature bit is set for the extension. A mobile
device also needs to verify whether the extension includes
the id kp codeSigning object identifier.
A JAD file should not contain a self-issued root certificate
in a certificate chain. However, an MIDP device should
not explicitly reject X.509v3 self-issued CA certificate in
its chain.

Expiring and Revoking a Certificate


Expiration and revocation of a certificate in a JAD file is
verified during the authorization process of the certificate.

The verification of expiry of a certificate is a process that


is required to validate a certificate. The information about
expiry of a certificate is present on the certificate itself.
Revocation of a certificate involves sending a request to a
server and taking decisions based on the response received
by the server. Certificate revocation requires
implementation of a certificate revocation mechanism on
the mobile device. This mechanism is not a part of the
MIDP security framework and needs to be implemented
separately.
A mobile device should support Online Certificate Status
Protocol (OCSP) if certificate revocation needs to be
implemented on the mobile device. If a mobile device
supports other certificate revocation protocols, the
certificate is considered as revoked, regardless of the
result received by the OCSP protocol.

City Guide Application


Problem Statement
You are working as a mobile application developer at
Global Systems Inc, which specializes in developing
mobile applications by using Java ME platform. Your
organization has developed a city guide application that
shows the map of a city with restaurants, museums, shops,
and theatres marked on it. However, the application is
untrusted and therefore prompts the user each time
whenever an access is made to any service. You have been
assigned the task of signing the application such that it
does not prompt the user each time when it accesses a
service. How will you achieve the required task?

Solution
To solve the preceding problem, you need to perform the
following tasks:
1. Open the sample project, City Guide.
2. Analyze the run-time behavior of the project.
3. Sign the project.
4. Build, run, and test the project.

Task 1: Opening the Sample Project, City


Guide
To open the City Guide project, you need to perform the
following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project. The New Project
dialog box appears, as shown in the following
figure.

The New Project Dialog Box


3. Expand the Samples node in the Categories
section, and then expand the Mobility node.
4. Select MIDP under the Mobility node, and then
select City Guide in the Projects section.
5. Click the Next button. The Name and Location
page is displayed, as shown in the following
figure.

The Name and Location Page


6. Ensure that <Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.
7. Click the Next button. The Default Platform
Selection page is displayed, as shown in the
following figure.

The Default Platform Selection Page


8. Click the Finish button. The CityGuide1 NetBeans IDE 6.0.1 window is displayed, as
shown in the following figure.

The CityGuide1 - NetBeans IDE 6.0.1


Window

Task 2: Analyzing the Run-Time Behavior


of the Project
To analyze the run-time behavior of the CityGuide1
project, you need to perform the following steps:
1. Select BuildBuild Main Project to build the
CityGuide1 project.
2. Select RunRun Main Project to execute the
CityGuide1 project. The DefaultColorPhone
emulator window is displayed, as shown in the
following figure.

The DefaultColorPhone Emulator Window


3. Click the soft key below Launch to launch the
CityGuide MIDlet. The City Guide screen is
displayed, as shown in the following figure.

The City Guide Screen


4. Click the soft key below Next. The Landmark
services screen is displayed, as shown in the
following figure.

The Landmark Services Screen


5. Click the soft key below Yes. The Location
services screen is displayed, as shown in the
following figure.

The Location Services Screen


6. Click the soft key below Yes. The map of a city is
displayed, as shown in the following figure.

To sign the CityGuide1 project, you need to perform the


following steps:
1. Right-click the CityGuide1 node in the Projects
tab and then select Properties from the pop-up
menu. The CityGuide1 dialog box appears, as
shown in the following figure.

The CityGuide1 Dialog Box


2. Select Signing under the Build node in the
Category section.
3. Select the Sign Distribution check box.
4. Select trusted from the Alias drop-down list.
5. Select Running in the Category section.
6. Select the Specify the Security Domain check
box.
7. Select maximum from the Specify the Security
Domain drop-down list.
8. Click the Ok button to return to the NetBeans
IDE.

Task 4: Building, Running, and Testing


the Project

The Map of a City

If the RAM in the mobile device is low,


pressing the soft key below Yes in the
preceding stepwill not launch the
application. In such a case, you need
to stop the application that is
currently running, close the emulator,
and restart the application.
7. Select MIDletExit to close the
DefaultColorPhone emulator window.

Task 3: Signing the project

To build, execute, and test the CityGuide1 project, you


need to perform the following steps:
1. Select BuildBuild Main Project to build the
CityGuide1 project.
2. Select RunRun Main Project to execute the
CityGuide1 project. The DefaultColorPhone
emulator window is displayed, as shown in the
following figure.

The DefaultColorPhone Emulator Window


3. Click the soft key below Launch to launch the
CityGuide MIDlet. The City Guide screen is
displayed, as shown in the following figure.

The City Guide Screen


4. Click the soft key below Next. The map of a city
is displayed, as shown in the following figure.

Summary

The Map of a City

The Application did not show the


Landmark Services and Location
Services screens. This implies that
now the application is signed and
trusted.
5. Select MIDletExit to close the
DefaultColorPhone emulator window.
6. Select FileExit to close the NetBeansIDE.

In this chapter, you learned that:


The security model of Java ME is defined at the
following levels:
Low-level security
Application-level security
Application-level security involves implementing
security mechanisms in the MIDlet application
itself.
MIDP 2.0 introduces the concept of trusted and
untrusted MIDlets.
If the device is able to verify the authenticity and
integrity of the MIDlet suite and assign it to a
protection domain, then the MIDlet suite is said
to be trusted, else the MIDlet suite is treated as
untrusted by the mobile device.
If a MIDlet needs to establish an HTTP
connection, it must have permission to open an
HTTP connection.
MIDP 1.0 specification uses the sandbox concept
that restricts the untrusted MIDlet suites for
developing applications. The Java ME Wireless
Toolkit 2.5.2 includes the following protection
domains for the JTWI specification:
Untrusted
Trusted
Minimum
Maximum
MIDlets in the Trusted and Maximum
domains are granted all permissions.
A user can deny or grant permission for any of
the following interaction modes:
blanket
session
oneshot
A trusted MIDlet suite is signed and verified by
using the X.509 PKI.
The sandbox security model of CLDC/MIDP
addresses the application-level security of MIDP
1.0.
Java Wireless Client checks the validity of a
signed MIDlet suite by using the public keys
from a CA.
The signing process of a MIDlet suite involves
using a keytool utility known as the JADTool and
MEKeytool.
The steps involved in signing a MIDlet suite are:
1. Verify a certificate.
2. Insert the certificate in the JAD.
3. Create the signature and apply it to JAD.
4. Authenticate a MIDlet suite.
5. Verify the signer certificate.
6. Verify the MIDlet suite JAR.

7. Include the list of permissions your


MIDlet suite is requesting in the JAD
file and manifest.
A certificate profile includes processing,
expiring, and revoking of a certificate.
MIDP X.509 Certificate Profile is the profile
used for implementing trusted MIDlet suites.
This profile supports WAP-211WAPCert-20010522-a WAP Certification Profile,
which supports Internet X.509 Public Key
Infrastructure Certificate.

Exercises
Exercise 1
You are working as a mobile application developer at
Global Systems Inc, which specializes in developing
mobile applications by using Java ME platform. Your
organization has developed a news application for mobile
phones. The news application collects the news stored on a
Web server and displays it in the form of a ticker.
However, every time the application prompts the user to
get the permission for establishing a connection with the
server. You have been assigned the task to modify the
application such that it connects to the server without
asking the user for permissions.
Prerequisites: The following applications are needed to
run the application.
NEWSAPPLICATION
NEWSSERVER

Reference Reading
Implementing MIDlet Security
Reference Reading: Books Reference Reading: URLs
Enterprise J2ME:
http://developers.sun.com/
Developing Mobile Java
techtopics/mobility/learn/
Applications By John W.
midp/security/
Muchow Publisher: Prentice
Hall PTR.
http://developers.sun.com/
techtopics/mobility/midp/
Java 2 Micro Edition
articles/permissions/
Application Development By
Michael Kroll Stefan
http://www-128.ibm.com/
Haustein Publisher: Sams developerworks/wireless/
Publishing
library/wi-secj2me.html

Chapter 10
Implementing Mobile Media API
Mobile devices are used for several purposes including
entertainment. These devices have multimedia
capabilities, such as audio and video that provide
entertainment to the users. Applications can be developed
for such devices to utilize their multimedia capabilities.
For example, you can create a multimedia player that
plays sound and videos for a mobile device user.
Java ME provides Mobile Media API (MMAPI) to
develop multimedia applications. You can use the classes
and interfaces provided by MMAPI to develop various
multimedia applications.
This chapter discusses various packages of MMAPI. It
also explains various components of MMAPI architecture.
Further, it discusses the use of MMAPI for playing sound
and videos, and implementing the camera feature that
allows you to record videos and click photographs.

javax.microedition.media.control:
Provides various types of control interfaces that
can be used with a Player object, a
VolumeControl object, and a
VideoControl object.
javax.microedition.media.protocol
: Provides support for defining protocols that are
used for handling user-defined custom controls.

Identifying Classes and Interfaces in


MMAPI Package
The three packages defined in MMAPI provide a set of
classes and interfaces for playing and controlling
multimedia content on mobile devices.
The following table describes the classes defined in the
MMAPI packages.
Class
Manager

Objectives
In this chapter, you will learn to:
Identify Mobile Media API
Implement MMAPI package

Introducing Mobile Media API

ContentDescriptor

DataSource

MMAPI is an optional package that can be used with Java


ME to develop multimedia applications. MMAPI belongs
to JSR 135 and its latest specification is MMAPI 1.1 that
includes security framework, which was not available in
MMAPI 1.0. MMAPI provides a set of classes and
interfaces that can be used to create and play multimedia
content on a mobile device. For example, you can use
MMAPI for playing sounds, and for capturing audio and
video data.

Describing MMAPI Packages and its


Architecture
MMAPI defines a set of three packages for playing and
controlling the multimedia content on a mobile device.
The three packages defined in MMAPI are:
javax.microedition.media: Provides the
Manager class that is used to create and manage
the Player objects. A Player object
represents a multimedia player of a mobile
device.

MediaException

Description
Creates a Player object
based on the type of the
specified multimedia
content. This class is defined
in the
javax.microedition.
media package.
Creates a container to store
a specific media-type. This
class is defined in the
javax.microedition.
media.protocol
package.
Represents an abstraction
for media protocol-handlers.
It hides the details of how
the data is read from
various sources, such as a
file or a streaming server.
This class is used by the
Player object to access
the input data. This class is
defined in the
javax.microedition.
media.protocol
package.
Indicates an unexpected
error condition in a method.

Table Describing Classes in the MMAPI Packages


The three MMAPI packages further define several
interfaces for performing a variety of tasks, such as
creating players, events, and control types for multimedia
content.
The following table describes the various interfaces
defined in the packages of MMAPI.

Interface
Control

Description
Is used to control the media
playback capabilities of a
Player object. This
interface is defined in the
javax.microedition.
media package.
Controllable
Is used to retrieve controls
from Player objects. This
interface provides methods
to query the Player object
and retrieve the required
information. This interface
is defined in the
javax.microedition.
media package.
Player
Is used to play the
multimedia content. This
interface is defined in the
javax.microedition.
media package.
PlayerListener
Is used to receive
asynchronous events
generated by the Player
objects. This interface is
defined in
javax.microedition.
media.
TimeBase
Is used for a source that
provides time measurement.
This interface can be used to
measure the progress of time
to synchronize multiple
Player objects. This
interface is defined in
javax.microedition.
media.protocol.
SourceStream
Is used with aDataSource
object to provide input
interface to the Player
object. This interface is
defined in the
javax.microedition.
media.protocol
package.
FramePositioningCon Specifies and controls the
trol
positioning of the video
frame in a video player. This
interface is defined in the
javax.microedition.
media.protocol
package.
GUIControl
Is used to control

MetaDataControl

MIDIControl

PitchControl

RateControl

RecordControl

StopTimeControl

TempoControl

thePlayer objects, which


use GUI features of a mobile
device. This interface is
defined in the
javax.microedition.
media.control
package.
Is used to retrieve and
control metadata
information stored in a
multimedia stream. This
interface is defined in the
javax.microedition.
media.control
package.
Enables you to access and
control MIDI-playing
devices. This interface is
defined in the
javax.microedition.
media.control
package.
Increases or decreases the
pitch of sound without
affecting the playback
speed. This interface is
defined in the
javax.microedition.
media.control
package.
Controls the rate at which
multimedia content is being
played on aPlayer object.
This interface is defined in
the
javax.microedition.
media.control
package.
Controls the recording of
multimedia content from a
Player object. This
interface is defined in the
javax.microedition.
media.control
package.
Enables you to preset the
timer for stopping a player.
This interface is defined in
the
javax.microedition.
media.control
package.
Enables you to control the
tempo of sound. Tempo is

ToneControl

VideoControl

VolumeControl

defined as the number of


beats per minute. This
interface is defined in the
javax.microedition.
media.control
package.
Enables you to play and
control a sequence of userdefined tones. This interface
is defined in the
javax.microedition.
media.control
package.
Controls the display of video
data on a Player object.
This interface is defined in
the
javax.microedition.
media.control
package.
Controls the volume of a
Player object. This
interface is defined in the
javax.microedition.
media.control
package.

Table Describing Interfaces in the MMAPI Packages

MMAPI Architecture
The MMAPI architecture consists of the following
components:
TheManager class
The Player interface
The Control interface
The DataSource class
The following figure shows the interaction between the
components of MMAPI architecture.

Player object based on the media type being requested.


For example, if the type of media to be played is in the
WAV format, the Manager class creates a Player
object with WAV-playing capabilities.
The Player interface is used to generate and play timebased multimedia content. You can also create Control
objects for the multimedia players to control the flow of
multimedia content. The Control objects are
implemented according to the type of data being provided
to the Player object. For example, a video player will
implement two type of Control objects,
VideoControl and RecordControl. A player can
also accept data from user-specified custom
DataSource objects.

Just a minute:
Debbie Howe is working as a mobile
application developer in the SSPT
Corporation. Debbie wants to controls the
display of video data on a Player object in
the media application. Identify the interface
that Debbie will use to achieve the task.

Answer:
VideoControl

Just a minute:
State whether the following statement is true
or false.
The ToneControl interface enables you to
play and control a sequence of user-defined
tones.

Answer:
The MMAPI Architecture
The Manager class is used to create Player objects by
using the createPlayer() method. It creates a

True

Just a minute:
State whether the following statement is true
or false.
The Manager class creates a Player
objects-based on the type of the specified
multimedia content.

Answer:
True

Implementing MMAPI
You can create and control multimedia content by using
the classes and interfaces defined in MMAPI. In order to
create and control multimedia content, you need to
implement the various classes and interfaces of MMAPI in
a mobile device. In addition, these classes and interfaces
can be used to:
Handle the events generated by a player.
Play ringtones.
Play different sound file formats.
Play and record videos on mobile devices.

Implementing MMAPI Components


In order to play multimedia content, you need to use
various components of the MMAPI architecture.
A Player object is used to create a player and specify
the data to be played. The object of the DataSource
class provides the data to the Player object. The
Manager class generates the appropriate implementation
of the Player interface according to the specified
multimedia content. For example, if you specify a video
file in the createPlayer() method of the Manager
class, aPlayer object capable of playing the specified
video file is generated.
The control interfaces, such as VideoControl and
VolumeControl, are added to the Player objects to
enable mobile users to control the features of multimedia
content, such as video and volume, on mobile devices.

Implementing the Manager Class


The Manager class is a static factory class that is used to

createPlayer objects. The Manager class defines the


following versions of the createPlayer() methods to
create the Player objects:
static Player createPlayer(String
LOCATION): Creates a Player object that is
used to play a multimedia file. The network
location of the multimedia file is specified by
using the Uniform Resource Identifier (URI)
locator string, LOCATION. For example, the
following code snippet shows the use of this
method:
Player player =
Manager.createPlayer("http://
server/music.mp3");
static Player createPlayer
(InputStream is, String type):
Creates a Player object to play a multimedia
file. The data of the multimedia file is specified
by using theInputStream object, is, and the
Multipurpose Internet Mail Extensions (MIME)
type of the multimedia file is specified as the
String object type. This version of the method
allows you to play locally stored multimedia
content. For example, the following code snippet
shows the use of this method:
InputStream in = getClass
().getResourceAsStream
("airhorn.wav");
try
{
Player player =
Manager.createPlayer(in, "audio/
X-wav");
}catch( Exception e ){
}
static Player createPlayer
(DataSource DS): Creates a Player object
to play a multimedia file. This Player object
plays the multimedia data specified by a
DataSource object. The DataSource
object provides the methods to connect to and
play the multimedia data from a custom data
source. For example, the following code snippet
shows the use of this method:
DataSource ds= (DataSource) new
CleverStreamingDataSource
("proto://songs.com/sound.mp3");
Player player =
Manager.createPlayer(ds);

The Factory class is a class that provides an


interface for creating families of related
objects. Factory classes are useful when the
decision of which class to use must be done at
run time. The Manager class is a factory
class because its createPlayer() method
creates a player according to the type of data
that needs to be played.
The following table describes some of the methods, in
addition to the createPlayer() method, defined in
the Manager class.
Method
Description
getSupportedContent Returns the list of
Types(String
multimedia content types
Protocol)
supported by the specified
protocol. The content type
identifies the type of media
data, such as MP3 audio
files, MIDI files, and MPEG
video files.
getSupportedProtcol Returns the list of supported
s(String
multimedia protocols for the
content_type)
specified content type.
Examples of protocols are,
disk I/O and streaming
media I/O.
getSystemTimeBase() Returns an object of
theTimeBase interface.
playTone(int note, Renders the tone as
int time, int
specified by its note and
volume)
duration.

Life Cycle of a Player Object


You can switch between the different states of a Player
object according to your requirements. As a result,
different states in the life cycle of the Player object help
you in managing the memory and resources of a mobile
device effectively. For example, you can keep a Player
object in the UNREALIZED state before playing the
multimedia content, and save the memory overheads
required to keep the player in the REALIZED and
STARTED states.
The following table describes the five states in the life
cycle of aPlayer object.
State
UNREALIZED

Table Describing the Manager Class Methods

Implementing the Player Interface

REALIZED

The Player interface extends the Controllable


interface. It represents the generic behavior of the
Player classes, which are implemented by various
vendors implementing MMAPI.
A Player object is created by using the
createPlayer() method of a Manager class object.
A player goes through five different states in its life cycle.
The following figure shows the various states and their
interactions in the life cycle of a Player object.
PREFETCHED

STARTED

Description
Is the initial state, in which
a Player object is created.
In this state, the Player
object does not possess the
necessary information to
acquire the resources to play
multimedia content.
Represents the state when
the Player object obtains
the necessary information to
acquire the resources
required to play the
multimedia content.
However, it does not have
the system dependent
resources for playing the
content.
Represents a state when the
player acquires all system
dependent resources that are
needed for playing the
multimedia content.
Represents a state when the
Player is started. In this

CLOSED

state it processes the


multimedia content.
Represents a state when
thePlayer object has
reached the end of its life
cycle. After a Player
object reaches the CLOSED
state, it is no longer usable.

Table Describing the States in the Life Cycle of a


Player Object
When a Player is first constructed, it is in the
UNREALIZED state. You can use the realize()
method to transform the Player object from the
UNREALIZED state to the REALIZED state. During this
transformation, the Player object acquires the
information about the multimedia content that needs to be
played.

A Player object cannot return to the


UNREALIZED state from the REALIZED
state. After invoking the realize() method,
a Player can only return to the
UNREALIZED state by calling the
deallocate() method before the
completion of the realize() method.
After acquiring the content to be played, you can use the
prefetch() method to move the Player object from
the REALIZED state to the PREFETCHED state. The
prefetch() method acquires the system resources and
processes as much data as necessary to reduce the start
time of the player. You can use the start() method to
play the content. When the start() method is called,
the Player object moves to the STARTED state. A
Player object stops playing the multimedia content
either when the stop() method is called, or when the
Player object encounters the end of the multimedia
content. In both these cases, the Player object moves to
the PREFETCHED state from the STARTED state. You
can also invoke the close() method to end the life cycle
of a Player object and send it to the CLOSED state.
The following code snippet creates a Player object and
provides controls to handle the tone of the player:
try{
Player tonePlayer =
Manager.createPlayer
(Manager.TONE_DEVICE_LOCATOR);

tonePlayer.realize();
ToneControl tc = (ToneControl)
tonePlayer.getControl("ToneControl");
tc.setSequence(mySequence);
tc.start();
}
catch (IOException ioe) {}
catch (MediaException me) {}

Implementing the Control and


Controllable Interfaces
The Control interface provides a set of methods, which
can be used for processing multimedia content. A Player
object extends theControllable interface. You can use
the getControl() and getControls() methods
ofControllable interface to retrieve the Control
objects from a Player object, which implements the
Controllable interface.
MMAPI defines several other control interfaces, which are
derived from the Control interface, to represent
different types of controls. These controls are used to
manage the multimedia content.

Implementing the DataSource Class


The DataSource class is used to create and retrieve the
sources of multimedia data. The DataSource class
hides the details of how to read data from various types of
sources, such as file, network server, or RMS storage.
TheDataSource class is an abstract class. This class is
used to derive classes that implement streaming
multimedia data from various resources, such as network,
RMS storage, and data files. By using the objects of the
classes derived from the DataSource class, you can
access the multimedia data randomly. As a result, the
DataSource objects offer easier access to the
multimedia content as compared to accessing multimedia
content by usingInputStream objects.
You can use the Manager.createPlayer() method
to create a player for the data provided by a custom
DataSource object.
Some of the commonly used methods of the
DataSource class are:
connect(): Connects to the specified
DataSource object.
start(): Starts the transfer of data from the
DataSource object.
stop(): Stops the transfer of data from the

DataSource object.
getStream(): Returns one or more data
streams associated with a DataSource object.
disconnect(): Closes the connection to the
source described by the locator.
getContentType(): Gets a string that
describes the content-type of the media that the
source is providing.
getLocator(): Gets the locator that describes
this source.

started.
The following code snippet checks for the generated
event:
if (eventType ==
PlayerListener.STARTED)
{
...
}

A DataSource object contains a set of


SourceStream objects. Each
SourceStream object represents an
elementary data stream from a multimedia
source that is to be played.

else if(eventType == PlayerListener.


RECORD_STARTED){
...
The preceding code snippet checks the event type that is
generated in the player by using theSTARTED and
RECORD_STARTED fields.

Generating Tones with MMAPI


Support
Just a minute:
Which method of the Player interface is
used to move the Player object from the
REALIZED state to the PREFETCHED state?

Answer:
Prefetch()

You can use the playTone() method of the Manager


class to generate tones on a mobile device. The
playTone() method enables you to generate the tones
without creating the Player objects. As a result, this
method saves memory in resource-constrained mobile
devices.
The following code snippet shows the prototype of the
playTone() method:
playTone(int note, int duration, int
volume)

Handling Events by Using the


PlayerListerner Interface
ThePlayerListener interface listens for the
asynchronous events generated by the Player objects.
You can implement this interface in a multimedia
application and register the implementation by using the
addPlayerListener() method of the Player
interface.
The PlayerListener interface defines several static
fields of the String type to represent the events that can
occur while playing multimedia content. For example, the
RECORD_STARTED string represents the event that
occurs when a Player object starts recording the
multimedia content. Similarly, the STARTED string
represents the event that occurs when a Player object is

In the preceding syntax, the parameter:


note: specifies the musical note value to be
played by the playTone() method. The value
of the note parameter should be between 0 and
127.
duration: specifies the time duration for
which the tone should be played. The time
duration is specified as an integer value, duration.
This value is specified in terms of milliseconds.
volume: specifies the volume of the tone to be
played. The value of the volume parameter
ranges from 0 to 100.
The playTone() method can throw the following two
exceptions:
IllegalArgumentException: This
exception is thrown if the note or duration

parameter is out of range.


MediaException: This exception is thrown if
a mobile device is not able to play the specified
tone due to some hardware error.
The playTone() method generates a single tone for a
specified duration. You can also use the playTone()
method to create music by playing a sequence of tones.
You can generate a sequence of tones by putting the
playTone() method inside a loop.
For example, the following code snippet plays a series of
tones by calling the playTone() method in a loop:
for(int counter=0; counter< 100;
counter++){
int NOTE= (int)
(System.currentTimeMillis() % 127);

Player WAVplayer = Manager.createPlayer


(istream, "audio/X-wav");
WAVplayer.start();
}
catch (IOException ioe) {
}
catch (MediaException me) {
}
...

Manager.playTone(NOTE, 100, 100);

The following code snippet implements a WAV file player


by using the Player class:

//Move the clock forward

int id;

Thread.currentThread().sleep(10);

// play back from a record store

The preceding code invokes the playTone() method


100 times to play a sequence of tones. The different values
of the NOTE parameter are calculated based on the current
system time, which is measured in milliseconds and
dividing it by 127 to get a remainder value between 0 to
127. The values of the volume and time duration
parameters are specified as 100.

try {
InputStream is= getClass
().getResourceAsStream("audio.midi");
Player midiplayer =
Manager.createPlayer(is, "audio/midi");
midiplayer.start();

Playing Different Sound File


Formats
You can play various formats of sound files by using the
MMAPIPlayer interface. The commonly used file
formats that can be played by using the MMAPIPlayer
interface are:
WAV
MP3
MIDI
The following code snippet shows how to play a sound file
with a .WAV extension:
int id;
// play back from a record store
try {
InputStream istream = getClass
().getResourceAsStream("audio.wav");

}
catch (IOException ioe) {
}
catch (MediaException me) {
}
...
The preceding code snippet creates a midiPlayer
object, which is an instance of the Player interface. The
MIDI file to be played is stored locally in the RMS and is
retrieved by using the InputStream object, istream.
You can also play MP3 files by using the Player
interface. The following code snippet shows how to play
an MP3 file by using the Player interface:
...

Player mp3player;

code snippet shows how to capture and record live audio:

VolumeControl vcontrol;

try {

try {

// Create a DataSource to capture


live audio.

mp3player = Manager.createPlayer
("http://server/music.mp3");
mp3player.realize();

Player player =
Manager.createPlayer("capture://
audio");
player.realize();

// get volume control for player


and set volume to half max value

// Get the RecordControl.


RecordControl rc = (RecordControl)
player.getControl("RecordControl");

vcontrol = (VolumeControl)
mp3player.getControl("VolumeControl");
if(vcontrol != null) {

//Set the location of the source


for recording.
rc.setRecordLocation("file:///
tmp/audio.wav");

vcontrol.setLevel(50);
rc.startRecord();
}
player.start();
// start the player
mp3player.start();

Thread.currentThread().sleep
(5000);

player.stop();

catch(IOException IOex) {

rc.stopRecord();

rc.commit();

catch(MediaException ex) {

} catch (IOException ioe) {

} catch (MediaException me) {

...

} catch (InterruptedException e) { }

The preceding code snippet creates a Player object,


mp3player, which plays an MP3 file. The location of
the MP3 file is provided by specifying the path of the MP3
file, by using the string, http://server/music.mp3. The
volume of the sound is set to the value, 50 that specifies
half of the maximum volume allowed on a mobile device.

The preceding code snippet captures the audio file from


the file:///tmp/audio.wav location and records the audio for
5 seconds.

Capturing and Recording Live Audio


You can capture and record live audio by using the
MMAPI interfaces and classes. The RecordControl
class helps in recording of the live audio. The following

Playing and Controlling Videos


You can play, capture, and record videos by using the
MMAPI interfaces and classes. For example, the
VideoControl interface is used to control the display
of video on a mobile device.
A Player object, which is intended to play videos on a

mobile device, should provide the VideoControl


object for controlling the video playback. The
VideoControl object is returned by using the
getControl() and getControls() methods of the
Player object.
You can create a video player, and play video files by
extending the Canvas class and by using the objects of
various MMAPI classes and interfaces. You also need to
provide the control in a video player by using the
VideoControl interface.
The following code snippet implements a video player:

v.initDisplayMode
(VideoControl.USE_DIRECT_VIDEO, this);
v.setDisplayLocation(2, 2);
v.setDisplaySize(width - 4, height
- 4);
vplayer.start ();
} catch (Exception ex) {
ex.printStackTrace();

import javax.microedition.lcdui.*;
}

import javax.microedition.media.*;
}

import
javax.microedition.media.control.*;

public class CanvasVideo extends Canvas


implements CommandListener {

public void paint(Graphics G) {


// Draw a border around the
VideoControl.
G.setColor(0x00ffff);

private Player vplayer;


private int width, height;
private Command done;

G.drawRect(0, 0, width - 3, height


- 2);
G.drawRect(1, 1, width - 5, height
- 4);

public CanvasVideo () {
width = getWidth();
height = getHeight();

}
public void commandAction(Command c,
Displayable s) {
if (c == done) {

done = new Command("Done",


Command.OK, 1);
addCommand (done);
setCommandListener (this);

//Code to stop the player when the done


key is pressed
}

}
}

public void startPlayer (Player p) {


vplayer = p;
try {
VideoControl v=
(VideoControl) vplayer.getControl
("VideoControl");

}
The preceding code snippet creates a video player named
vPlayer that is defined in the CanvasVideo class,
which extends the Canvas class.

Implementing Camera

MMAPI provides support for implementing a camera. To


implement camera, a special locator, capture://
video is used to create the Player object. An
application uses the VideoControl object to display
the view finder on the screen and take pictures.
The VideoControl.getSnapshot(String
imageType) method is used to capture an image from
camera. The following code snippet shows how to capture
images by implementing camera:

...

} catch (IOException ioe) {


} catch (MediaException me) { }
The preceding code snippet implements the camera and
uses the getSnapshot() method to take the pictures.

Player player;
VideoControl vc;

Creating a JukeBox Application


Problem Statement

// initialize the camera


try {
player = Manager.createPlayer
("capture://video");

You are working as a mobile application developer with


Technology Systems Inc. The organization uses Java ME
platform for developing mobile applications. The
organization also manufactures mobile phones.

player.realize();

You are asked by your Team Leader to develop a jukebox


application for mobile devices, which enables the users to
play various types of audio file formats.

// Grab the video control.

Prerequisite: The airhorn.wav andintro.midi input files


are required for performing this activity. Ask your faculty
to provide the required input files.

vc = (VideoControl)
player.getControl("VideoControl");
if (vc != null) {
Form form = new Form("video");
form.append((Item)
vc.initDisplayMode
(vc.USE_GUI_PRIMITIVE, null));
Display.getDisplay
(midlet).setCurrent(form);
}

player.start();

byte[] image = vc.getSnapshot


(null);

Solution
To develop the JukeBox application, you need to perform
the following tasks:
1. Create a NetBeans project.
2. Add class files to the project.
3. Build and execute the project.

Task 1: Creating a NetBeans Project


To create a JukeBox project, you need to perform the
following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project. TheNew Project
dialog box appears.
3. Select the Mobility option from the Categories
section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name and Location
page is displayed.
6. Type JukeBox in the Project Name text box to
assign a name to the new project.
7. Ensure that Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.

8. Clear the Create Hello MIDlet check box.


9. Click the Next button. The Default Platform
Selection page is displayed.
10. Click the Next button. The More Configurations
Selection page is displayed.
11. Click the Finish button to create the JukeBox
project.

Task 2: Adding Class Files to the Project


For adding files to the JukeBox project, you need to
perform the following steps:
1. Select FileNew File. TheNew File dialog box
appears.
2. Ensure that the MIDP option is selected from the
Categories section.
3. Ensure that the MIDlet option is selected in the
File Types section.
4. Click the Next button. The Name & Location
page is displayed.
5. Type PlayerMIDlet in theMIDlet Name text box
to assign a name to the new MIDlet.
6. Click the Finish button to create the
PlayerMIDlet.java MIDlet.
7. Replace the existing code in the
PlayerMIDlet.java MIDlet in the Editor with the
following code:
import
javax.microedition.lcdui.*;
import
javax.microedition.media.*;
import
javax.microedition.media.control.
*;
import
javax.microedition.midlet.*;
import java.io.*;
import javax.microedition.io.*;
public class PlayerMIDlet extends
MIDlet implements CommandListener
{
private Display display;
private List lst;
private Command start = new
Command("Play",Command.SCREEN,
1);
int currentPlaying = -1;

(this);
}
protected void startApp() {
String[] elements = {"Play
>> Audio","Play >>
TuneSequence"};
lst = new List("Menu",
List.IMPLICIT, elements, null);
lst.setCommandListener
(this);
lst.addCommand(start);
display.setCurrent(lst);
}
protected void pauseApp() {
}
protected void destroyApp
(boolean unconditional) {
}
public void commandAction
(Command c , Displayable d){
int index =
lst.getSelectedIndex();
if(c == start){
if (index == 0){
sound_play();
}
if(index == 1){
playTones();
}
}
}
public void sound_init()
{
InputStream in = getClass
().getResourceAsStream
("airhorn.wav");
try
{
audioPlayer =
Manager.createPlayer(in, "audio/
X-wav");
}catch( Exception e ){

//Sound Player object.


static Player audioPlayer;
private Player tonePlayer;

}
in = null;
}

public PlayerMIDlet(){
display = Display.getDisplay

public void sound_play()

{
sound_init();
try
{
audioPlayer.realize();
System.out.println("Playing
Sound...");
audioPlayer.start();
}catch(Exception e){
}
}

}
public void playTones() {
createTonePlayer();
if (tonePlayer != null){
try {
System.out.println
("Playing Sound...");
tonePlayer.start();
} catch (MediaException
me) {
}
}

private void createTonePlayer


() {
byte tempo = 30;
byte d = 8;
byte C4 = ToneControl.C4;
byte D4 = (byte)(C4 + 2);
byte E4 = (byte)(C4 + 4);
byte G4 = (byte)(C4 + 7);
byte rest = ToneControl.SILENCE;
byte[] mySequence = {
ToneControl.VERSION, 1,
ToneControl.TEMPO, tempo,
ToneControl.BLOCK_START, 0,
E4,d, D4,d, C4,d, E4,d,
E4,d, E4,d, E4,d, rest,d,
ToneControl.BLOCK_END, 0,
ToneControl.PLAY_BLOCK, 0,
D4,d, D4,d, D4,d, rest,d,
E4,d, G4,d, G4,d, rest,d,
ToneControl.PLAY_BLOCK, 0,
D4,d, D4,d, E4,d, D4,d, C4,d
};
try{
tonePlayer =
Manager.createPlayer
(Manager.TONE_DEVICE_LOCATOR);
tonePlayer.realize();
ToneControl c =
(ToneControl)
tonePlayer.getControl
("ToneControl");
c.setSequence(mySequence);
} catch (IOException ioe)
{System.err.println("Initializing
Tone");}
catch (MediaException me)
{ }

}
}
8. Copy the given sound files, airhorn.wav and
intro.midi and paste them in the <Drive
Letter>:\JavaMEProjects\src folder.

Task 3: Building and Executing the


Project
To build and execute the project, you need to perform the
following steps:
1. Switch to the JukeBox - NetBeans IDE 6.0.1
window.
2. Select BuildBuild Main Project to build the
project.
3. Select RunRun Main Project to execute the
project. The DefaultColorPhone emulator
window is displayed, as shown in the following
figure.

The DefaultColorPhone Emulator


4. Click the soft key below Launch to launch the
PlayerMidlet MIDlet, as shown in the following
figure.

The DefaultColorPhone Emulator Displaying


the PlayerMidlet MIDlet
5. Click the soft key below Play to play the selected
sound format. You can select one of the two
sound file formats by using the up and down
arrow keys.
6. Select MIDletExit to close the
DefaultColorPhone emulator window.
7. Select FileExit to close the NetBeans IDE.

Summary
In this chapter, you learned that:
MMAPI is an optional package that can be used
with Java ME to develop multimedia

applications.
MMAPI consists of the following packages:
javax.microedition.media
javax.microedition.media.cont
rol
javax.microedition.media.prot
ocol
The Manager class is used to createPlayer
objects on the basis of the type of multimedia
content specified in the createPlayer()
method.
The Player interface is used to play the
multimedia content.
The MMAPI architecture consists of the
following components:
TheManager class
The Player interface
The Control interface
The DataSource class
The Manager class defines the following
versions of the createPlayer() methods to
create the Player objects:
static Player createPlayer
(String LOCATION)
static Player createPlayer
(InputStream is, String type)
static Player createPlayer
(DataSource DS)
A Player object goes through the following
states during its life cycle:
UNREALIZED
REALIZED
PREFETCHED
STARTED
CLOSED
The Control interface provides a set of
methods, which can be used for processing
multimedia content.
Some of the commonly used methods of the
DataSource class are:
connect()
start()
stop()
getStream()
disconnect()
getContentType()
getLocator()
ThePlayerListener interface listens for the
asynchronous events generated by the Player
objects.
You can use the playTone() method of the
Manager class to generate tones on a mobile
device.
The commonly used file formats that can be

played by using the MMAPIPlayer interface


are:
WAV
MP3
MIDI
A Player object, which is intended to play
videos on a mobile device, should provide the
VideoControl object for controlling the
video playback.

Exercises
Exercise 1
Kiwi Sound Systems is an organization that develops
music player applications for various devices, such as
computers, car stereos, and mobiles. Jim Peter is working
with the organization as a mobile application developer.
He is asked to develop a media player that plays midi
sound format. For developing the application he needs to
use the Java ME platform.
Prerequisite: The intro.midi file is required to run the
application.

Reference Reading
Introducing Mobile Media API
Reference Reading: Books Reference Reading: URLs
J2ME in a Nutshell: By Kim http://www.devx.com/
Topley Publisher: OReilly wireless/Article/20911/0
Enterprise J2ME:
http://developers.sun.com/
Developing Mobile Java
techtopics/mobility/midp/
Applications By John W.
articles/mmapioverview/
Muchow Publisher: Prentice
Hall PTR.

Implementing MMAPI
Reference Reading: Books Reference Reading: URLs
Enterprise J2ME:
http://www.devx.com/
Developing Mobile Java
wireless/Article/20911/0
Applications By Michael
Juntao Yuan Publisher:
Prentice Hall PTR

Chapter 11
Implementing Wireless Messaging
API
Sending and receiving messages can be considered as a
low-cost alternative for communicating through voice
calls. However, to enable a mobile device to send and
receive messages, you need to develop an interface for the
messaging application. In addition, a network connection
is required that will enable the users to send and receive
messages from one mobile device to another.
Java ME facilitates the development of messaging
application by using an additional package called Wireless
Messaging API (WMA).
This chapter discusses the interfaces, address formats, and
exceptions in WMA. It also discusses various security
issues that need to be considered while developing
messaging applications. Further, it discusses the process of
creating, sending, and receiving text messages.

Objectives
In this chapter, you will learn to:
Identify wireless messaging
Implement SMS

Introducing Wireless Messaging


Java ME allows you to create messaging applications for
sending and receiving messages. These messaging
applications use wireless networks, such as GSM, to send
and receive messages from one mobile device to another.
Messaging is possible on both the GSM and CDMA
networks.
WMA is a package of classes and interfaces that enables
you to create messaging applications. In addition, it allows
you to send and receive short text and binary messages
and multimedia messages. It belongs to JSR 120 and JSR
205.

Introducing WMA
Due to memory limitations, MIDP does not define any
classes and interfaces to create messaging applications.
WMA is an optional package in Java ME that can be used
in MIDP-based applications to send and receive messages
from mobile devices. However, the presence of WMA is
mandatory on mobile devices that comply with JSR 185,
which is a JTWI specification for CLDC.

WMA is based on GCF, which is compatible with both


CDC and CLDC. As a result, you can use WMA to create
applications for both CDC and CLDC-based mobile
devices.

An optional package is a set of APIs that does


not define a complete application
environment, like profiles. It is always used
with a configuration or a profile. It extends the
runtime environment to support device
capabilities that cannot be universally defined
as part of a profile and needs to be shared by
different profiles.

Types of Messaging Protocols


WMA enables you to create messaging applications that
are independent of the messaging protocols used to deliver
the messages. In fact, how messages are delivered depend
on the underlying transport, such as GSM Short Message
Service (SMS), GSM Cell Broadcast Service (CBS), or
CDMA SMS.
WMA supports the following types of messaging
protocols:
SMS: Is a bi-directional protocol that allows you
to send and receive short text messages from
mobile devices. The main advantage of SMS is
the guarantee that the message will reach the
destination mobile device even if the device is
out of radio coverage or switched off.
CBS: Is a uni-directional protocol that is used to
receive messages that are broadcast by the base
station to all mobile users or subscribers in a
specific geographic region. CBS provides one-tomany service within a specific geographical area.

The IOException exception is raised if you


try to use the CBS protocol for sending
messages.
To use a specific type of messaging protocol in a
messaging application, you need to specify the protocol
type in the
javax.microedition.io.Connector.open()
method. This method is a part of GCF and is used to create
connections for messaging applications. For example, in
order to use the SMS protocol to send and receive
messages on 1234 port of a mobile device, you need to
write the following code snippet:

(MessageConnection)Connector.open
("sms://:1234);

Interfaces of WMA
The javax.wireless.messaging package provides
all the interfaces that enable you to handle and manage
both text and binary messages.
The javax.wireless.messaging defines the
following top-level interfaces:
Message: Represents a message and its content
in a messaging application.
MessageConnection: Implements a
connection that can be used to send and receive
messages.
MessageListener: Notifies messaging
applications about incoming messages.

The Message Interface


The Message interface is the base interface for all the
messages that are sent and received by using WMA. It
defines the following subinterfaces that are used to create
two different types of messages, namely text and binary:
TextMessage: Represents a text message. This
interface contains methods to create and send text
messages from one mobile device to another. The
TextMessage interface defines the following
two methods:
getPayLoadText(): Returns a text
string stored in the Message object.
setPayLoadText(String data):
Sets the text of the specified String
object as the content of the Message
object.
BinaryMessage: Represents a message that
contains binary data. The TextMessage
interface defines the following two methods:
getPayLoadData(): Returns the data
stored in a Message object as an array of
bytes.
setPayLoadData(String data):
Sets the specified byte array data as the
content of a Message object.
The TextMessage and BinaryMessage interfaces
are derived from the the Message interface.

You can create a connection by using the following


modes:
Client mode: Represents a mode in which you
can send, but cannot receive messages. You can
establish a client mode connection by passing the
destination address of the message as a string to
the Connector.open() method. For
example, the following code snippet shows how
to establish a connection in a client mode:
MessageConnection)Connector.open
("sms://+15121234567:5000");
Server mode: Represents a mode in which you
can send as well as receive messages. You can
establish a server mode connection by passing an
end point identifier, such as a port number, of the
server in the Connector.open() method. For
example, the following code snippet shows how
to establish a connection in a server mode:
(MessageConnection)Connector.open
("sms://:5000");

If the end point identifier is already assigned


to some other application, an IOException
is thrown. For example, if you have assigned a
port number, 1234, to some application and
you pass this port number to the
Connector.open() method, an
IOException is thrown.
The following table describes the methods defined in the
MessageConnection interface.
Method
newMessage(String
type)

The MessageConnection Interface


The MessageConnection interface is derived from the
javax.microedition.io.Connection package.
It defines the methods that provide the basic functionality
for sending and receiving messages. The methods of the
MessageConnection interface can also be used to
create Message objects.
The MessageConnection interface represents a
connection between two mobile devices.

newMessage(String
type, String
address)

numberOfSegments

Description
Creates a new message of
the specified type, which is
passed as a String
argument. If you pass the
string, TEXT_MESSAGE, a
TextMessage object is
returned. If you pass the
string, BINARY_MESSAGE,
a BinaryMessage object
is returned.
Creates a new message of
the specified type, which is
passed as a String
argument. This method also
accepts the destination
address of the message.
Returns the number of

(Message msg)

segments in which a
message is divided, before
sending it to the destination.
The number of segments
depends on the protocol that
is used for sending the
message. For example, the
number of segments will be
different for the SMS and
CBS protocols.
receive()
Receives a message. This
method waits for a new
message, until either the
message arrives or the
connection is closed.
setMessageListener Registers a
(MessageListener
MessageListener
mlist)
object, which is notified
when an incoming message
is received.
send()
Sends a message. A
SecurityException is
thrown if the application has
no permission to send
messages on the specified
port.

Table Describing the MessageConnection


Interface Methods

The MessageListener Interface


TheMessageListener interface enables you to
receiveMessage objects and notifies the messaging
application about the receipt of a message.
TheMessageListener interface contains the
notifyIncomingMessage() method that is invoked
on receiving a message.
A messaging application needs to extend the
MessageListener interface to receive incoming
messages. The MIDlet class of the messaging application
should also define a notifyIncomingMessage()
method, which handles the incoming messages.

Address Formats in WMA


You need to specify the address of the destination mobile
device, which receives a message, in the
Connector.open() method. The address is specified
as a string, which is called an address format. You can
define the type of protocol to be used for messaging by
using different address formats in the Connector.open
() method.
The types of address formats that can be used with the
Connector.open() method are:
sms://PHONENO:PORT: Is used to create a

connection for a client mobile device, to enable


the client device to send messages. This address
format creates a MessageConnection object,
which can be used to send the message to the
destination mobile device with the specified
phone number by using the PHONENO parameter
and the port. For example, the sms://
+1234567890:9999 address is used to create a
connection for sending a message to the mobile
device with the phone number, 1234567890, at
the 9999 port.
sms://:PORT: Is used to create a connection for
a server to receive incoming messages from the
specified port number, PORT, of a mobile device.
For example, the sms://:9090 address can be used
to create a connection for the incoming messages
at the port number, 9090.
cbs://:PORT: Is used to create a connection for a
mobile device to receive broadcast messages on
the specified port number, PORT. This address
format also specifies that the CBS protocol
should be used for receiving messages. For
example, the cbs://:2020 address can be used to
create a connection for receiving broadcast
messages from the 2020 port of a mobile device.

Types of Exceptions in WMA


The messaging process involves sending messages from
one mobile device to another over a network. Several
types of exceptions can be encountered in this process.
The following table describes the exceptions that can
occur while using WMA.
Exception
Description
ConnectionNotFoundE Is thrown by the
xception
Connector.open()
method. This exception is
raised when a connection
cannot be established with
the specified mobile device,
or the specified connection
type does not exist.
IllegalArgumentExce
Is thrown by the
ption
Connector.ope
n() method when
the argument to
this method is
invalid.
Is thrown by the
newMessage()
method. The
exception is raised
when this method is
not able to identify
the message type

InterruptedIOExcept
ion

IOException

specified in the
argument.
Is thrown by the
send() method
when the message
is incomplete or the
message type is
invalid.
Is thrown by the
receive()
method when the
MessageConnec
tion object is
closed while
receiving a
message.
Is thrown by the
receive()
method when either
a timeout occurs or
the
MessageConnec
tion object is
closed while
sending a message.
Is thrown by the
Connector.ope
n() method when
an I/O error, such
as non-availability
of connection end
point, is
encountered.
Is thrown by the
receive()
method when one
of the following
conditions arise:
An error
occurs while
retrieving a
message.
A connection
is closed.
A method is
invoked for a client
instead of a server.
Is thrown by the
send() method
when the network
or connection is
not available.
Is thrown by the
setMessageLis

tener() method
when a connection
is closed.
NullPointerExceptio Is thrown by the send()
n
method when the Message
parameter is null.
SecurityException
Is thrown by the
Connector.ope
n() method when
the specified
protocol is not
allowed to be used
for messaging.
Is thrown by
thereceive()
method when the
messaging
application
containing the
receive() method is
not allowed to
receive messages at
the specified port.
Is thrown by the
send() method
when the message
application
containing the
send() method is
not allowed to send
messages at the
specified port.
Is thrown by the
setMessageLis
tener() method
when the
messaging
application
containing the
receive()
method is not
allowed to receive
messages at the
specified port.

Table Describing the Exceptions Types in WMA

Identifying WMA Security Issues


Messages being sent through a wireless network are prone
to attacks by hackers. Therefore, it is necessary for WMA
to implement a security mechanism. Although WMA does
not define a security mechanism by itself, it ensures the
security of messaging applications by using the security

mechanisms implemented in the security framework of the


platform on which the messaging application is
implemented.
On certain platforms such as MIDP 2.x, networking
operations require permissions that are requested by the
application to be granted by the platform. For example, if
the application wants to send or receive sms, it should
specify the following attribute in the JAD and the manifest
file:
MIDlet-Permissions:
javax.microedition.io.Connector.sms,
javax.wireless.messaging.sms.receive,
javax.wireless.messaging.sms.send
The security mechanism authenticates and checks the
certificate before enabling a MIDlet to access the wireless
network. This security feature is device-dependent.
While creating messaging applications, you need to
consider certain issues. The issues related to the security
of the WMA-based applications are:
Applications can be restricted from sending and
receiving messages to specific ports and
destination addresses. For example, if you want
to secure one port of the machine for a Webbased application, you can block that port. Any
attempt to access that port for receiving and
sending messages will throw an exceptionnamed
SecurityException.
In case a messaging application attempts to
access the wireless network without proper
authorization, the exception named
SecurityException is thrown.
If a mobile device is MIDP 1.0 compliant, the
security mechanisms are absent because they
were introduced in MIDP 2.0.

Introducing SMS
SMS is a one-to-one and one-to-few messaging service.
By using this messaging service, a sender can send
messages to either one or a small number of receivers.
SMS supports both the client and server connections. You
can create two-way messaging applications based on the
SMS protocol.
The process of sending a message by using SMS involves
the following steps:
1. A mobile user creates a message on the client
mobile device.
2. The client mobile device sends the message to an
SMS server, known as Short Message Service
Centre (SMSC), of the required mobile service
provider.
3. SMSC receives the message and saves a copy of

this message.
4. SMSC identifies the address of the destination
mobile device and sends a copy of the message to
the destination mobile device. If the destination
mobile device is not reachable, SMSC waits until
the destination mobile device is reachable.
5. The destination mobile device sends an
acknowledgment after receiving the message.
6. SMSC deletes its own copy of the message after
receiving the acknowledgment from the
destination mobile device.
The following figure illustrates the process involved in
sending a message.

Sending an SMS
The delivery of messages depends on the underlying
transport. Certain transports impose a limit on the size of a
message being sent to a mobile device. The size of a
message refers to the amount of data that a message can
carry.
The Segmentation And Reassembly (SAR) feature of lowlevel transports ensures the breaking of a large message
into a number of smaller segments. For example, a
message sent on SMSC is typically limited to 160 GSM 7bit encoded characters or 140 binary 8-bit bytes.
The following table describes the message header and the
corresponding message size per segment.
Message Header
7-bit encoded character
8-bit binary data
UCS-2 text

Maximum Size (in bytes)


per segment
160
140
70

Table Describing the Message Size Limitations

Creating and Sending a Text


Message
Before sending a message, you need to create a connection
between the client and the server. The connection is
created by using the Connector.open() method. This
method returns a MessageConnection object. After
creating the MessageConnection object, you can use
the newMessage() method to obtain a message object.

To send the created message, you can use the send()


method of the MessageConnection interface.
For example, the following code snippet shows how to
create and send a new text message:
The following code snippet shows how to send a message:
public void sendTextMessage
(MessageConnection cn, String
message, String URL) {
//message parameter is the text message
to be passed
//URL is the address of the destination
where message is to be sent
try {
TextMessage tms =
(TextMessage)cn.newMessage
(MessageConnection.TEXT_ME
SSAGE);
if (URL!= null)
tms.setAddress(URL);

You can receive messages as:


Synchronous messaging: In this case, a thread
waits for the incoming messages. You can receive
a message by using the receive() method of
the MessageConnection interface. This
method performs synchronous messaging. This
means that the application invoking the
receive() method must halt processing until
it receives the message.
Asynchronous messaging: In this case, the
system notifies the application when new
messages arrive. You can use the
notifyIncomingMessage() method to
enable the application to proceed with its
processing while waiting for the incoming
messages.
For synchronous messaging, you need to create a
MessageConnection object with the specified port
number on a mobile device to receive a message. After
receiving the message, you should check the message type
before further processing the received message. You can
use the instance of an operator to check whether the
message is of the TextMessage or BinaryMessage
type.
For example, you can use the following code snippet for
receiving a message in synchronous messaging:
public class SynchronousMsg implements
Runnable {

tms.setPayloadText(message);
cn.send(tmsg);
}
catch(Exception e) {
// Handle the exception...
System.out.println
("sendTextMessage " + e);
}

MessageConnection
messageConnection;
boolean done;
...
public SynchronousMsg (
MessageConnection
messageConnection) {
this.messageConnection =
messageConnection;

Thread th = new Thread(this);

Receiving a Message
There are two modes using which you can create
connections between mobile devices, namely client and
server. However, messages can be received only by a
server mode and not by a client mode.

th.start();
}
...

public void setDone() {


done = true;
}
public void run() {
while (!done) {
try {
Message message;
message =
messageConnection.receive();
if (message != null) {
processMessage
(message);
}
} catch (IOException ioe)

Java ME. Steve, a mobile application developer at Global


Systems Inc., has been asked to develop a chatting
application by using the WMA API in Sun Java ME SDK
3.0. Before creating the code for the chatting application,
Steve needs to check how to run a messaging application
in Java ME SDK 3.0. Therefore, Steve decides to run a
sample messaging application, which is provided with the
Sun Java ME SDK 3.0. How will Steve accomplish his
task?

Solution
To run the sample messaging application, Steve needs to
perform the following tasks:
1. Start the WMADemo application in the Sun Java
ME SDK 3.0.
2. Prepare the receiver for receiving Messages.
3. Send the message.

Task 1: Starting the WMADemo


Application in Sun Java ME SDK 3.0
To start the WMADemo application, Steve needs to
perform the following steps:
1. Select startAll ProgramsJava(TM) ME
Platform SDK 3.0Java() ME Platform
SDK 3.0. The Java() Platform, Micro
Edition Software Development Kit 3.0 window
appears.

{
// Handle or ignore the
exception
}
}
}
public void processMessage
(message) {

If the Authentication dialog box


appears, press the Cancel button to
proceed with the activity.
2. Select FileOpen Sample
ProjectWMADemo. The Java() Platform,
Micro Edition Software Development Kit 3.0
window with the current status of the
WMADemo project is displayed, as shown in the
following figure.

// Process the message here


}
...

Running a Messaging Application in


Java ME SDK 3.0
Problem Statement
Global Systems Inc. provides mobile and Web services to
its customers by using Java-based technologies, including

The Java() Platform, Micro Edition


Software Development Kit 3.0 Window

3. Select RunBuild Main Project to build the


WMADemo project.
4. Select RunRun Main Project to start running
the MIDlet application. The
DefaultCldcMsaPhone1 emulator window
appears, as shown in the following figure.

1. Select the SMS Receive option from the list by


using the down arrow key of the
DefaultCldcMsaPhone1 emulator.
2. Click the Ok
button on the keypad of the
DefaultCldcMsaPhone1 emulator to launch the
message receiving MIDlet. The SMS Receive
screen is displayed on the emulator, as shown in
the following figure.

The DefaultCldcMsaPhone1 Emulator


Window

Task 2: Preparing the Receiver for


Receiving Messages

Task 3: Sending the Message

To prepare the receiving mobile device for receiving the


messages, Steve needs to perform the following steps:

To send a message, Steve needs to perform the following


steps:

The SMS Receive Screen

1. Switch to the WMADemo window.


2. Right-click the WMADemo node under the
Projects tab of the Java() Platform, Micro
Edition Software Development Kit 3.0 window,
and then select Properties from the pop-up
menu. The WMADemo dialog box appears, as
shown in the following figure.

The WMADemo Dialog Box


3. Ensure that the Platform option is selected in the
Category section.
4. Select DefaultCldcMsaPhone2 from the Device
drop-down list.
5. Click the Ok button to save the changes made to
the properties of the WMADemo project.
6. Select RunBuild Main Project to build the
WMADemo project.
7. Select RunRun Main Project to start running
the MIDlet application. The
DefaultCldcMsaPhone2 emulator window
appears, as shown in the following figure.

The DefaultCldcMsaPhone2 emulator


Window
8. Ensure that the SMS Send option is selected
from the list on the DefaultCldcMsaPhone2
emulator screen.
9. Click the Ok
button on the keypad of the
DefaultCldcMsaPhone2 emulator to launch the
message sending MIDlet. The Destination
Address? screen is displayed in the emulator
window, as shown in the following figure.

following figure.

The Destination Address? Screen


10. Type the phone number, which is displayed on
the title bar of the DefaultCldcMsaPhone1
emulatorwindow,in the text box of the
Destination Address? screen of the
DefaultCldcMsaPhone2 emulator window.
11. Press the soft key below Menu to display the list
of commands.
12. Select the OK option from the command list by
using the down arrow key on the keypad of the
emulator.
13. Press the Ok
button to display the Enter
Message screen in the emulator, as shown in the

The Enter Message Screen


14. Press the soft key below Menu to display the list
of commands.
15. Ensure that the Qwerty option is selected in the
command list.
16. Press the Ok
button to display a list of input
types, as shown in the following figure.

The List of Input Types


17. Select the Abc option in the input types list by
using the down arrow key on the keypad of the
emulator.
18. Press the Ok button to select the input type as
Abc. The Enter Message screen appears with the
Abc label, as shown in the following figure.

The Enter Message Screen


19. Type the message,Hi, in the text area of the
Enter Message screen of the emulator by using
the keypad of the emulator.
20. Press the soft key below Menu to display the list
of commands.
21. Select the Send option from the command list by
using the down arrow key on the keypad of the
emulator.
22. Press the Ok button to send the message. The
SMS alertscreen is displayed for a short duration.
After the alert elapses, the message, Hi will be
displayed on theDefaultCldcMsaPhone1

emulator, as shown in the following figure.

23. Select ApplicationExit in the


DefaultCldcMsaPhone1 emulator window to
close the DefaultCldcMsaPhone1 emulator.
24. Select ApplicationExit in the
DefaultCldcMsaPhone2 emulator window to
close the DefaultCldcMsaPhone2 emulator.
25. Select FileExit to close the WMADemo Java() ME Platform SDK 3.0 window.

If you want to perform the preceding


activity by using a different login id,
then you need to delete the private
folder in the <Drive letter>:
\Java_ME_platform_SDK_3.0\apps
\WMADemo\nbproject directory.

Summary

The Received Message Displayed on the


Emulator

You can reply to a message by clicking


the Reply button after receiving a
message. In this case, the emulator
window, which is replying to the
message, becomes the sender and the
other window becomes the message
receiver.

In this chapter, you learned that:


Java ME allows you to create messaging
applications for sending and receiving messages.
WMA is a set of interfaces that enables you to
create messaging applications.
WMA supports the following types of messaging
protocols:
SMS
CBS
SMS is a bi-directional protocol that allows you
to send and receive short text messages from
mobile devices.
CBS is a uni-directional protocol that is used to
receive messages that are broadcast by the base
station to all mobile users or subscribers in a
specific geographic region.
The javax.wireless.messaging defines
the following top-level interfaces:
Message
MessageConnection
MessageListener
The Message interface is the base interface for
all the messages that are sent and received by
using WMA.
The MessageConnection interface defines
the methods that provide the basic functionality
for sending and receiving messages.
TheMessageListener interface enables you
to receiveMessage objects and notifies the
messaging application about the receipt of a
message.
You need to specify the address of the destination
mobile device, which receives a message, in the

Connector.open() method.
SMS is a one-to-one and one-to-few messaging
service.
SMS supports both the client and server
connections.
Messages can be received only by a server mode
and not by a client mode.

Reference Reading
Introducing Wireless Messaging
Reference Reading: Books
Enterprise J2ME:
Developing Mobile Java
Applications By Michael
Juntao Yuan Publisher:
Prentice Hall PTR

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/midp/
articles/wma/
http://www-128.ibm.com/
developerworks/wireless/
library/wi-extendj2me/
index.html

Chapter 12
Developing Gaming Applications
Mobile games are nothing but video games on a mobile
device. They have become popular as they provide
entertainment. Java ME is a popular platform for
developing gaming applications for mobile devices. It has
a set of Game APIs that provide enhanced capabilities to
develop rich gaming applications.
This chapter introduces MIDP Game APIs. It explains the
limitations of MIDP 1.0 Game APIs and further introduces
the enhancements provided in the new Game API of MIDP
2.0. It also explains the various classes provided in MIDP
2.0 Game APIs for creating and managing graphic objects.
In addition, it discusses the characteristics and
implementation of MIDP 2.0 Game APIs.

Objectives
In this chapter, you will learn to:
Analyze and implement classes in the MIDP Game
API
Develop a Tic-Tac-Toe game by using the Game API

Introducing MIDP Game API


MIDP Game API is a set of APIs that is used to develop
gaming applications for mobile devices. It belongs to JSR
178.
The MIDP Game API is available in the
javax.microedition.lcdui.game package. The
javax.microedition.lcdui.game package of the
MIDP 1.0 provides limited support for game
programming.
Some of the reasons due to which it is difficult to develop
game applications by using MIDP 1.0 are:
It does not provide advanced graphical features
such as support for audio.
It is difficult to render three-dimensional images
due to unavailability of support for floating-point
representation.
It supports only the HTTP network protocol.
It does not allow applications to read or write to
individual pixels. Therefore, it cannot perform
basic image manipulations, such as fading an
image to black.
It does not support any form of transparency for
using an image mask or for defining a transparent
color.
As a result, new MIDP Game APIs were defined in MIDP

2.0 that provide several gaming features for developing


gaming applications that did not require you to manually
create complex graphics. Further, the Game API of MIDP
2.0 helps you to develop UIs that use minimum device
resources, such as memory, for gaming applications.
MIDP 2.0 includes basic Game APIs for developing TwoDimensional (2D) games. 2D games use simple images
that can be animated. 2D games can be created by drawing
pixels on the screen of a mobile device.
Java ME can also be used to develop Three-Dimensional
(3D) games. 3D games are visually better than 2D games.
The javax.microedition.m3g package defines
APIs for developing 3D game applications. This package
supports a variety of mobile devices, including the devices
that supported CLDC 1.0 configuration.

Characteristics of MIDP 2.0 Game


API
MIDP 2.0 Game API provides several enhancements over
the characteristics and classes provided by MIDP 1.0
Game APIs. The new Game API package provides game
specific classes, such as the GameCanvas class, to easily
create rich gaming applications.
Some characteristics of the MIDP 2.0 Game API package
are:
It helps to create gaming applications for mobile
devices by using fewer resources as compared to
MIDP 1.0. As a result, the cost of creating games
is significantly reduced.
It helps to implement the concept of layers in
graphic-based applications. All graphic objects of
a gaming application, which appear on the screen
of a mobile device, are placed on a separate layer.
For example, consider a game that uses four
graphic objects: a background image object, a
road object, a vehicle object, and a tree object.
Each of these graphic objects needs to be placed
on different layers of the gaming application. You
can draw these graphic objects by using the
MIDP 2.0 Game API. You can then combine
these objects to create the required animation
effect for the gaming application. The Game API
package helps you to manage graphic objects
separately, independent of each other. For
example, you can create an animation effect by
controlling the movements of the vehicle object,
without affecting any other graphical object used
in the gaming application.

Layers are tiers of content that are

placed on top of each other.


It helps to view the game area without writing the
code for scrolling from one view area to another.
The game area of a gaming application may be
larger than the screen of a mobile device. For
example, in a racing game, the game area can
include several hurdle points, which can be
represented by separate view areas on the screen
of a mobile device. All these view areas cannot
be displayed on the mobile device
simultaneously. You need to scroll from one view
area to another to view the complete game area.
In MIDP 1.0, you need to write code to scroll
from one view area to another for viewing the
complete game area, which is a difficult task.
However, MIDP 2.0 Game API contains a view
window, using which you can view the complete
game area.
It reduces the flickering of images on the screen
of a mobile device. In MIDP 1.0, rendering
images on the screen is difficult, because you
need to control the refresh rates of the screen
when a graphic image is updated. MIDP 2.0
automatically refreshes the screen of a mobile
device when a graphic image is updated. As a
result, the MIDP 2.0 Game API helps to develop
flicker-free animation effects in a gaming
application.
It consumes less memory space. The size of the
JAR file for a gaming application created by
using the MIDP 2.0 Game API consumes less
space than the size of the JAR file created by
using MIDP 1.0 Game API. As a result, gaming
applications created by using MIDP 2.0 Game
API consume less memory in a mobile device.

Implementing MIDP 2.0 Game API


A gaming application built by using Java ME contains a
screen that displays various graphic objects. For example,
a gaming application can contain graphical images of
streets, buildings, and vehicles moving on a street. You
need to control the movement of these graphic objects to
create an animation effect for a game. You can implement
the MIDP 2.0 Game API to create the required animation
effect. MIDP 2.0 Game API provides the following classes
to create and manage these graphic objects:
GameCanvas: Contains methods to create a
game UI.
Layer: Contains methods to create a graphical
object for a game.
LayerManager: Contains methods to manage
different layers in a gaming application.

Sprite: Contains methods to give animation


effects to a graphical object.
TiledLayer: Contains methods that are mainly
used to create a background image of a gaming
application.
The following figure shows the class hierarchy in the
MIDP 2.0 game API.

Class Hierarchy in Game API

Implementing the GameCanvas Class


The
javax.microedition.lcdui.game.GameCanva
s class extends the MIDP Canvas class and provides
several additional benefits over the Canvas class. In
addition to the capabilities derived from the Canvas
class, the GameCanvas class also provides the following
game-specific capabilities:
Querying key states
Using the off-screen buffer

Querying Key States


In a gaming application, the user input is provided in the
form of a key press. You need to press keys to control the
animation effects of a game. A gaming application needs
to have instant access to the current state of a key for
responding to any key press changes.
The state of the key of a mobile device determines which
key is pressed on the keypad of a mobile device. For
example, you are playing a bike racing game. In this
game, you need to press the right and left arrow keys of
the mobile device to control the movement of the bike
object. The gaming application needs to access the state of
the right or left arrow keys to control the animation effect.
When you press the right arrow key, the gaming
application moves the bike object to the right of the game
area. Similarly, when you press the left arrow key, the
gaming application moves the bike object to the left of the
game area.
The GameCanvas class contains the getKeyStates
() method that enables a gaming application to access the
state of a key.
The following table describes different key states that can
be used in a gaming application.

State of a key
LEFT_PRESSED
RIGHT_PRESSED
UP_PRESSED
DOWN_PRESSED
FIRE_PRESSED

GAME_A_PRESSED

GAME_B_PRESSED

GAME_C_PRESSED

GAME_D_PRESSED

Description
The bit representing the
LEFT key.
The bit representing the
RIGHT key.
The bit representing the UP
key.
The bit representing the
DOWN key.
The bit representing the
FIRE key. FIRE key is the
OK key.
The bit representing the
GAME_A key. This may not
be supported on all devices.
The bit representing the
GAME_B key. This may not
be supported on all devices.
The bit representing the
GAME_C key. This may not
be supported on all devices.
The bit representing the
GAME_D key. This may not
be supported on all devices.

Table Describing the Different Key States Used in a


Gaming Application

}
if ((keyState & RIGHT_PRESSED) != 0) {
System.out.println("You have pressed
Right Key");
}
if ((keyState & UP_PRESSED) != 0) {
System.out.println("You have pressed Up
Key");
}
if ((keyState & DOWN_PRESSED) != 0) {
System.out.println("You have pressed
Down Key");
}
if ((keyState & FIRE_PRESSED) != 0) {
System.out.println("You have pressed
Fire Key");
}

Using the Off-Screen Buffer

Just a minute:
Identify the state of the key that describes the
bit representing the FIRE key.

Answer:
FIRE_PRESSED
The following code snippet shows how to access the state
of a key:
int keyState = getKeyStates();

if ((keyState & LEFT_PRESSED) != 0) {


System.out.println("You have pressed
Left Key");

The off-screen buffer is used by theGameCanvas class to


create a flicker-free animation effect. The off-screen buffer
provides a Graphics object that is used to draw on the
canvas.
The off-screen memory buffer is a memory space where
you can perform all the drawing operations. You can then
copy the entire contents of the off-screen buffer to the
display of a mobile device. As a result, the display is
updated instantly. Whereas, if you directly draw on the
display of a mobile device flickering occurs as individual
parts are updated.
By using the offline memory buffer, you can combine
multiple drawing operations into a single operation to
copy the graphics to the display of the mobile device. You
can use the off-screen buffer to draw different graphical
objects of a gaming application and then combine the
graphical objects and display them on the screen, one at a
time. This results in a flicker-free animation effect.
Every instance of the GameCanvas class has a separate
off-screen buffer. The contents of these off-screen buffers
can be accessed only by calls to the graphic object from
the GameCanvas instance. The flushGraphics()
method of the GameCanvas class calls the off-screen
buffer to display the animation effect on the screen.

The following code snippet shows the use of


flushGraphics() method in a gaming application:
public void run() {
Graphics g = getGraphics();
while(true) {
// update the game state
// ...
int k = getKeyStates();
// respond to key events
flushGraphics();
}
}

Implementing the Layer Class


All graphic objects in a game are represented by the
objects of the subclasses of the Layer class. The Layer
class defines attributes, such as location, size, and
visibility of a graphic object.
The Layer class contains methods that are used to set or
retrieve the attributes of a graphic object. Each subclass of
the Layer class needs to define a paint() method to
render the layer on the canvas.
The following table describes the methods of the Layer
class.
Method
int getHeight()

Description
Retrieves the current height
of a layer, in pixels.
int getWidth()
Retrieves the current width
of a layer, in pixels.
int getX()
Retrieves the horizontal
position of the upper-left
corner of a layer, in
coordinate system of the
canvas.
int getY()
Retrieves the vertical
position of the upper-left
corner of a layer, in
coordinate system of the
canvas.
boolean isVisible() Retrieves the visibility of a
layer.

void move(int dx,


int dy)

Moves a layer by the


specified horizontal and
vertical distances on the
canvas.
abstract void paint Paints a layer, if the layer is
(Graphics g)
visible.
void setPosition
Sets the position of a layer,
(int x, int y)
such that the upper-left
corner of the layer is
located at the position
defined by the x and y
parameters. The x and y
parameters represent the
coordinate points of the
layer in the coordinate
system of the canvas.
void setVisible
Sets the visibility of a layer.
(boolean visible)
void remove(int
Removes a layer at the
Index)
specified index.
void addImpl(Layer Inserts the specified layer at
layer, int index) the specified index.
void removeImpl
Removes the specified layer
(Layer l)
from the
LayerManagerclass.

Table Describing the Layer Class Methods

Implementing the LayerManager


Class
The LayerManager class manages the layers in a
gaming application. To manage the layers, you need to add
or remove layers from an object of the LayerManager
class.
The methods to add a layer to the LayerManager class
are:
append(Layer l): Places a new layer behind
the existing layers in a gaming application.
insert(Layer l, int index): Places a
new layer at a specified location of your choice.
The location is indicated with the help of an
index that is passed as an argument to the
insert() method.
The LayerManager class keeps track of all the layers
that are appended, inserted, or removed from the
LayerManager class through index numbers assigned
to the layers. The layer that is added to the
LayerManager class is assigned an index. The index of
the topmost layer is 0 and it is closest to the user. The
layer with the highest index represents the bottommost
layer and it is closest to the hardware of the mobile device.
When a layer is removed, the index numbers attached to
the various layers are readjusted to maintain the sequence.

The LayerManager class also enables you to choose the


section of the graphic object that should appear on the
screen. For example, consider a 3D motor racing game for
mobile devices. Because the screen of a mobile device is
small, you can display only a part of the screen at a time.
In this scenario, the motor racing game area represents a
graphic object that is larger than the size of the screen. If
the graphic object is larger than the size of the screen, the
LayerManager class helps you to view specific sections
of a graphic object on the screen of a mobile device.
To view the sections of a large graphic object, you need to
set a view window that represents a certain section of the
graphic object. The view window moves from one section
of the graphic object to another and displays the respective
sections on the screen of a mobile device. You can use the
setViewWindow() method of the LayerManager
class to set a view window.
The following table describes different methods defined in
the LayerManager class.

public class ExampleGameCanvas extends


GameCanvas implements Runnable {
private boolean isPlay; // Game Loop
runs when isPlay is true
private long delay; // To give thread
consistency
private int currentX, currentY; // To
hold current position of 'X'
private int width; // To hold screen
width
private int height; // To hold screen
height

// Sprites to be used
Method
void append(Layer
l)
Layer getLayerAt
(int index)
int getSize()

Description
Appends a layer to the
LayerManager class.
Retrieves the layer with the
specified index.
Retrieves the number of
layers in the
LayerManager class.
void insert(Layer Inserts a new layer in the
l, int index)
LayerManager class, at
the specified index.
void paint(Graphics Renders the current view
g, int x, int y)
window of the
LayerManager class at
the specified location.
void remove(Layer Removes the specified layer
l)
from the LayerManager
class.
void setViewWindow Sets the view window of the
(int x, int y, int LayerManager class.
width, int height)

private Sprite playerSprite;


private Sprite backgroundSprite;
// Layer Manager
private LayerManager layerManager;
// Constructor and initialization
public ExampleGameCanvas() throws
Exception {
super(true);
width = getWidth();
height = getHeight();
currentX = width / 2;
currentY = height / 2;

Table Describing the LayerManager Class


Methods

delay = 20;

The following code snippet shows the use of the


LayerManager class:
import javax.microedition.lcdui.*;

// Load Images to Sprites

import javax.microedition.lcdui.game.*;

Image playerImage = Image.createImage


("/transparent.png");
playerSprite = new Sprite

(playerImage,32,32);
Image backgroundImage =
Image.createImage("/background.png");

// Method to Handle User Inputs


private void input() {

backgroundSprite = new Sprite


(backgroundImage);

int keyStates = getKeyStates();

layerManager = new LayerManager();

playerSprite.setFrame(0);

layerManager.append(playerSprite);
layerManager.append(backgroundSprite);

// Left

if ((keyStates & LEFT_PRESSED) != 0) {


currentX = Math.max(0, currentX - 1);

// Automatically start thread for game


loop

playerSprite.setFrame(1);
}

public void start() {


isPlay = true;
// Right
Thread t = new Thread(this);
if ((keyStates & RIGHT_PRESSED) !=0 )
t.start();
if ( currentX + 5 < width) {
}
public void stop() { isPlay = false; }

currentX = Math.min(width, currentX +


1);
playerSprite.setFrame(3);

// Main Game Loop

public void run() {


Graphics g = getGraphics();

// Up

while (isPlay == true) {

if ((keyStates & UP_PRESSED) != 0) {

input();

currentY = Math.max(0, currentY - 1);

drawScreen(g);

playerSprite.setFrame(2);

try { Thread.sleep(delay); }

catch (InterruptedException ie) {}


}

// Down

if ((keyStates & DOWN_PRESSED) !=0)

if ( currentY + 10 < height) {


currentY = Math.min(height, currentY +
1);
playerSprite.setFrame(4);
}

An Image with Eight Frames in a Row


The following figure shows the image displayed in the
preceding figure, divided into two equal rows.

}
// Method to Display Graphics
private void drawScreen(Graphics g) {
//g.setColor(0x00C000);

An Image with Eight Frames Displayed in Two Rows


g.fillRect(0, 0, getWidth(), getHeight
());
g.setColor(0x0000ff);
// updating player sprite position
playerSprite.setPosition
(currentX,currentY);

The frame sequence of a Sprite object defines the


sequence in which the frames are displayed on a mobile
device. The length of the default frame sequence is equal
to the number of frames. For example, if a Sprite object
contains two frames, the default frame sequence is (0, 1).
You need to retrieve the number of frames in a graphic
object to manage the sequence of frames. You can use the
following method to retrieve the total number of frames in
a graphic object:
public int getRawFrameCount()

// display all layers


layerManager.paint(g,0,0);
flushGraphics();
}}

Implementing the Sprites Class


A sprite is a small graphic object that can be moved
independently around the screen to create animation
effects. You can create a sprite by using the Sprite class.
The Sprite class contains constructors that are used for
managing sprites in a mobile game application. There are
two kinds of sprites used in a gaming application, namely
animated and non-animated. A sprite can contain one or
several images, called frames. These frames create an
animation effect when displayed in a sequence.
When more than one frame is used in a Sprite object,
the image is divided into frames of equal height and width.
These frames can be arranged in various ways, depending
on your requirements.
The following figure shows an image with eight frames,
all in a row.

You can specify the position of a frame as the current


frame in the frame sequence by using the void setFrame
(int) method. You can specify the previous and next
frames in the frame sequence by using the void
prevFrame() and the void nextFrame() methods,
respectively.
The following figure shows the sequence of frames that
will be displayed on a mobile device.

The Frame Sequence


You can define an arbitrary (having any value or form, of
any degree or extent) frame sequence for a Sprite
object. The frame sequence must contain a graphic object.
Each graphic object must refer a valid frame index. You
can use the frame index to display the frames in the
required sequence.
You can use the following code snippet to set the required
frame sequence:
public void setFrameSequence(int[]

sequence)
The preceding code snippet shows the creation of an
arbitrary sequence by using the available frames. All
Sprites have a default sequence that displays the Sprites
frames in a particular order.
The methods of the Sprite class help to manage the
frame sequence, manipulate sprite rotations, and detect
sprite collisions.
The following table describes the methods of the Sprite
class.
Method
boolean
collidesWith(Image
image, int x, int
y, boolean
pixelLevel)

Description
Verifies whether or not a
Sprite object collides
with the specified graphic
object at the specified point
on the upper left corner of
the screen.
boolean
Verifies whether or not a
collidesWith(Sprite Spriteobject collides with
s, boolean
another Sprite object,
pixelLevel)
specified by the Sprite s
parameter in the
collidesWith()
method.
boolean
Verifies whether or not a
collidesWith
Sprite object has collided
(TiledLayer t,
with a TiledLayer object.
boolean pixelLevel) The TiledLayer object is
specified as a parameter of
the collidesWith()
method.
void
Defines a section on the
defineCollisionRect game area, where the
angle (int x, int collision of graphic objects
y, int width, int can be detected.
height)
void
Defines the pixel, which is
defineReferencePixe used as a reference point for
l (int x, int y)
a Sprite object in the
frame sequence. The
reference point is called
reference pixel.
int getFrame()
Retrieves the current index
in the frame sequence.
int
Retrieves the number of
getFrameSequenceLen graphic objects in the frame
gth()
sequence.
int
Retrieves the number of raw
getRawFrameCount() frames for a Sprite
object.
int getRefPixelX() Retrieves the horizontal

position of the reference


pixel of a Sprite object in
the coordinate system of the
canvas.
int getRefPixelY() Retrieves the vertical
position of the reference
pixel of a Sprite object in
the coordinate system of the
canvas.
void nextFrame()
Selects the next frame in the
frame sequence.
void paint(Graphics Draws a Sprite object.
g)
void prevFrame()
Selects the previous frame in
the frame sequence.
void setFrame(int Selects the current frame in
sequenceIndex)
the frame sequence.
void
Sets the frame sequence for
SetFrameSequence
a Sprite object.
(int[] sequence)
void setImage(Image Modifies the graphic object
img, int
containing the frames of the
frameWidth, int
Sprite object.
frameHeight)
void
Sets the position of the
setRefPixelPosition Sprite object, such that
(int x, int y)
its reference pixel is located
at (x, y) in the coordinate
system of the canvas.
void setTransform Sets the transform for the
(int transform)
Sprite object. The
transform specifies the
angular position of a
graphic object in the
canvas.
collidesWith
Detects sprite collisions.
(Sprite sprite,
boolean pixelLevel)

Table Describing the Sprite Class Methods


You can also flip and rotate a Sprite object about a
specified reference point. This reference point is defined
by calling the Sprite.defineReferencePixel()
method. You can rotate a Sprite object about a point by
calling the Sprite.setTransform() method. You
can pass several values to the Sprite.setTransform
() method to flip and rotate the Sprite object.
The following table describes the values that you can pass
to the Sprite.setTransform() method.
Values
TRANS_MIRROR

Description
Displays the mirror image
of a Sprite object, about

its vertical center.


TRANS_MIRROR_ROT180 Displays the mirror image
of a Sprite object, about
its vertical center, and
rotates it by 180 degrees.
TRANS_MIRROR_ROT270 Displays the mirror image
of a Sprite object, about
its vertical center, and
rotates it by 270 degrees.
TRANS_MIRROR_ROT90 Displays the mirror image
of a Sprite object, about
its vertical center, and
rotates it by 90 degrees.
TRANS_NONE
Removes the transform
applied to a Sprite
object. The Sprite object
returns to its original
position in the canvas.
TRANS_ROT180
Rotates the Sprite object
by 180 degrees.
TRANS_ROT270
Rotates the Sprite object
by 270 degrees.
TRANS_ROT90
Rotates the Sprite object
by 90 degrees.

Table Describing Values of the setTransform()


Method

Just a minute:
Which method will you use to retrieve the total
number of frames in a graphic object?

Answer:
public int getRawFrameCount()

Implementing the TiledLayer Class


The TiledLayer class represents a graphic object in the
form of a grid of cells. These grid cells are filled with a set
of images called tiles and form the complete graphic
object. A TiledLayer may include animated elements, but
has no transformations, frame sequence, or reference
pixel.
You need to load the graphic object in the TiledLayer
class to display the graphic object as the background of the
mobile device screen. A grid represented by the

TiledLayer class is made up of several grid cells of


equal size.
The graphic object, when loaded in the TiledLayer
class, is divided into tiles. This division is based on the
parameters passed to the constructor of the TiledLayer
class. The constructor of the TiledLayer class specifies
the number of columns and rows of a grid cell, which form
a part of the graphic object. You can use these tiles in
games to create large scrolling backgrounds, without using
a large image for the background. The use of animated
tiles allows numerous cells of a Tiledlayer to be
animated quickly.
The following figure shows a set of tiles.

using the preceding set of tiles.

Various Arrangements of a Set of Tiles


The following code snippet shows how to load an image
into TiledLayer:
Image bkgrndImage = Image.createImage
("/bkgnd.png");
int rows = getHeight() / 16;
int cols = getWidth() / 16;
TiledLayer bkgnd =
new TiledLayer(cols, rows, bkgrndImage,
16, 16);

Set of Tiles
The preceding set of tiles can be used in various
arrangements to create an image. The following figure
shows some of the arrangements that can be created by

In the preceding code snippet, the number of columns and


rows are calculated based on the screen height, screen
width, and the desired size of each tile.
The tiles used to fill the grid cells are provided in a single
graphic object. The graphic object is divided into a series
of tiles with equal size. The dimensions of these tiles are
specified along with the graphic object. Each tile is
assigned a unique index number. The tile located in the
upper left corner of the graphic object is assigned an index
of 1. All the other tiles are numbered consequently in the
row column order. These tiles are called static tiles
because there is a fixed link between the tile and the
graphic object associated with the tile.
A set of static tiles is created when the TiledLayer
class is instantiated. You can also update the set of static
tiles by using the setStaticTileSet() method.

The row column order specifies the sequence


of all the tiles in a graphic object, from left to
right and from top to bottom.
A series of static tiles can be linked to each other to create
an animated tile. Animated tiles are created by using the
int createAnimatedTile(int
staticTileIndex) method. This method also assigns
an index to each animated tile specified by the
staticTileIndex argument. The animated tile indices
are always represented as negative integers, starting from
-1.
The contents of a grid cell are specified by the tile index.
A tile index can either be positive or negative. A positive
tile index refers to a static tile and a negative tile index
refers to an animated tile. When the tile index is 0, it
indicates that the grid cell is empty. An empty grid cell is
transparent, and nothing is drawn in that grid cell when the
TiledLayer class is rendered. All grid cells have tile
index set to 0 by default.
The methods of the TiledLayer class help you to
define the position and content of the grid cells.
The following table describes the methods of the
TiledLayer class.
Method
Description
int
Creates a new animated tile
createAnimatedTile and returns the index that
(int
refers to the new animated
staticTileIndex)
tile.
void fillCells(int Fills a region, specified by a
col, int row, int series of grid cells, with the
numCols, int
specific tiles.
numRows, int
tileIndex)
int getAnimatedTile Retrieves a tile referenced
(int
by an animated tile.
animatedTileIndex)
int getCell(int
Retrieves the contents of a
col, int row)
grid cell.
int getCellHeight() Retrieves the height of a
grid cell, in pixels.
int getCellWidth() Retrieves the width of a grid
cell, in pixels.
int getColumns()
Retrieves the number of
columns in a grid cell.
int getRows()
Retrieves the number of
rows in a grid cell.
void paint(Graphics Draws a TiledLayer
g)
object.

void
Associates an animated tile
setAnimatedTile(int with the specified static tile.
animatedTileIndex,
int
staticTileIndex)
void setCell(int
Sets the contents of a grid
col, int row, int cell.
tileIndex)
void
Modifies the static tile set.
setStaticTileSet
(Image image, int
tileWidth, int
tileHeight)

Table Describing TiledLayer Class Methods


The following code snippet shows how to set the contents
of the grid cells:
tiles.fillCells(0,0,8,1,1);
tiles.fillCells(0,0,1,6,1);
tiles.setCell(2,2,-1);
tiles.setCell(7,3,-1);
tiles.setCell(3,5,-1);
The following figure shows the grid cells filled with the
desired tile index numbers, according to the preceding
code snippet.

Grid Cells Filled with the Desired Tile Index Numbers

Developing a Tic-Tac-Toe
Application
Problem Statement

You are working as a game application developer at


SkyBlue Inc. You have been assigned the task to create a
TicTacToe game for mobile device users. While
developing the application, you need to consider that the
game is to be played by two players on the same mobile
device.

Solution
To develop the TicTacToe game, you need to perform the
following tasks:
1. Create a NetBeans project.
2. Add class files to the project.
3. Build, execute, and play the game.

8. Replace the existing name in the text box beside


the MIDlet Name label with TicTacToe_Midlet
to assign a name to the new MIDlet.
9. Click the Finish button to create the
TicTacToe_Midlet MIDlet.
10. Replace the existing code in the
TicTacToe_Midlet.java MIDlet in the Editor
with the following code:
package TicTacToe;
import
javax.microedition.lcdui.*;
import
javax.microedition.midlet.*;

Task 1: Creating a NetBeans Project


To create a NetBeans project, you need to perform the
following steps:
1. Select startAll
ProgramsNetBeansNetBeans IDE 6.0.1 to
open the NetBeans IDE 6.0.1 window.
2. Select FileNew Project.The New Project
dialog box appears.
3. Ensure that the Mobility option is selected in the
Categories section.
4. Ensure that the MIDP Application option is
selected in the Projects section.
5. Click the Next button. The Name and Location
page is displayed.
6. Type TicTacToeGame in the Project Name text
box to assign a name to the new project.
7. Ensure that <Drive Letter>:\JavaMEProjects is
displayed in the Project Location text box.
8. Clear the Create Hello MIDlet check box.
9. Click the Next button. The Default Platform
Selection page is displayed.
10. Click the Next button. The More Configurations
Selection page is displayed.
11. Click the Finish button to create the
TicTacToeGame project.

Task 2: Adding Class Files to the Project


For adding files to the TicTacToeGame project, you need
to perform the following steps:
1. Right-click the TicTacToeGame node under the
Projects tab, and then select NewJava
Package from the pop-up menu. The New Java
Package dialog box is displayed.
2. Type TicTacToe in the Package Name text box.
3. Click the Finish button.
4. Select FileNew File to open the New File
dialog box.
5. Ensure that the MIDP option is selected from the
Categories section.
6. Ensure that the MIDlet option is selected in the
File Types section.
7. Click the Next button. The Name & Location
page is displayed.

public class TicTacToe_Midlet


extends MIDlet implements
CommandListener{
/** The Main Display
Elements */
private Display theDisplay;
public TicTacToe_Canvas
canvas;
/** Command Button*/
Command exitCommand = new
Command("Exit", Command.EXIT, 0);
public TicTacToe_Midlet() {
canvas = new
TicTacToe_Canvas();
canvas.iniBoard();
//create the main
Display
theDisplay =
Display.getDisplay(this);
}
private void showGame(){
// Add the exit command
canvas.addCommand
(exitCommand);
canvas.setCommandListene
r(this);
theDisplay.setCurrent
(canvas);
}
protected void startApp()
throws MIDletStateChangeException
{
showGame();
}
protected void pauseApp() {
}
public void destroyApp

11.
12.
13.
14.
15.
16.
17.

(boolean unconditional) {
}
public void commandAction
(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
Select FileNew File.TheNew File dialog box
appears.
Select the Java option from the Categories
section.
Ensure that the Java Class option is selected in
the File Types section.
Click the Next button. The Name and Location
page is displayed.
Type TicTacToe_Canvas in theClass Name text
box to assign a name to the new Java class file.
Click the Finish button to create the
TicTacToe_Canvas Java class file.
Replace the existing code in the
TicTacToe_Canvas.java Java class file in the
Editor with the following code:
package TicTacToe;
import
javax.microedition.lcdui.Font;
import
javax.microedition.lcdui.Graphics
;
import
javax.microedition.lcdui.game.Gam
eCanvas;
public class TicTacToe_Canvas
extends GameCanvas{
public char board[][] = new
char[3][3];
/** Keep Track of Winner */
public String winner = "";
public boolean gameOver =
false;
/** The Game State */
public int whoseturn = 0;
public TicTacToe_Canvas() {
super(false);
}
public void iniBoard(){
board[0][0] = '1';
board[0][1] = '2';
board[0][2] = '3';
board[1][0] = '4';

board[1][1]
board[1][2]
board[2][0]
board[2][1]
board[2][2]

=
=
=
=
=

'5';
'6';
'7';
'8';
'9';

}
public void paint(Graphics
g){
int width = getWidth();
int height = getHeight
();
g.setColor( 1, 1, 1 );
g.fillRect( 0, 0, width,
height );
g.setColor( 0, 0, 0 );
g.fillRect( 0, 0, width,
height );
g.setColor( 255, 255,
255);
Font fnt = Font.getFont
(Font.FACE_SYSTem,Font.STYLE_BOLD
,Font.SIZE_LARGE);
g.setFont(fnt);
String r1 = board[0][0]
+"|"+board[0][1]+"|"+board[0][2]
+"\n";
String r2 = board[1][0]
+"|"+board[1][1]+"|"+board[1][2]
+"\n";
String r3 = board[2][0]
+"|"+board[2][1]+"|"+board[2][2];
g.drawString("TIC TAC
TOE",15+50,20, Graphics.LEFT|
Graphics.TOP);
g.drawString(r1,30+55,15
+60, Graphics.LEFT|Graphics.TOP);
g.drawString(r2,30+55,30
+60, Graphics.LEFT|Graphics.TOP);
g.drawString(r3,30+55,45
+60, Graphics.LEFT|Graphics.TOP);
if (winner != "")
{
g.drawString
("WINNER:"+winner,55,50,Graphics.
LEFT|Graphics.TOP);
}
else
{
g.drawString("TURN:
Player"+(whoseturn+1),0+55,60
+80,Graphics.LEFT|Graphics.TOP);
}
}
protected void keyPressed

(int keyCode) {
if (keyCode >= 49 &&
keyCode <= 57 && !gameOver)
{
int x = 0, y = 0;
keyCode -= 49;
if (keyCode < 3)
{
x = keyCode;
y = 0;
}
else if (keyCode <
6)
{
x = keyCode-3;
y = 1;
}
else
{
x = keyCode-6;
y = 2;
}
// If this slot is
open...
if (board[y][x] !=
'X' && board[y][x] != 'O')
{
if (whoseturn ==
0)
board[y][x] =
'X';
else
board[y][x] =
'O';
// Next player's
turn
whoseturn = 1whoseturn;
checkForWinner
();
repaint();
}
}
}
private void checkForWinner
()

// Check for a tie


for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
if (board[i]
[j] != 'X' || board[i][j] != 'O')
{
tie = false;
break;
}
}
if (tie)
{
GameOver(-1);
return;
}
// Check Horizontally
first
for (i=0; i<3; i++)
{
numXConsec =
numOConsec = 0;
for (j=0; j<3; j
++)
{
if (board[i][j]
== 'X')
numXConsec++;
else if (board
[i][j] == 'O')
numOConsec++;
else
break;
}
if (numXConsec >
2)
{
GameOver(0);
return;
}
else if
(numOConsec > 2)
{
GameOver(1);
return;
}
}

{
int i,j;
int numXConsec = 0; //
Number of consecutive Xs
int numOConsec = 0; //
Number of consecutive Os
boolean tie=true;

// Check Vertically
for (i=0; i<3; i++)
{
numXConsec =
numOConsec = 0;
for (j=0; j<3; j
++)

{
if (board[j][i]

winner = "Tie!";
else if (p == 0)
winner = "Player

== 'X')
{
numXConsec++;
}
else if (board

1!";
else
winner = "Player
2!";

[j][i] == 'O')

gameOver = true;
numOConsec++;
else
break;
}
if (numXConsec >

2)
{
GameOver(0);
return;
}
else if
(numOConsec > 2)
{
GameOver(1);
return;
}
}
// Finally Check both
diagonals
if ( ((board[0][0] ==
board[1][1]) && (board[1][1] ==
board[2][2]) &&
(board[2][2] == 'X')) ||
((board[0][2] == board[1]
[1]) && (board[1][1] == board[2]
[0]) &&
(board[2][0] == 'X')) )
{
GameOver(0);
return;
}
if ( ((board[0][0] ==
board[1][1]) && (board[1][1] ==
board[2][2]) &&
(board[2][2] == 'O')) ||
((board[0][2] == board[1]
[1]) && (board[1][1] == board[2]
[0]) &&
(board[2][0] == 'O')) )
{
GameOver(1);
return;
}
}
private void GameOver(int p)
{
if (p == -1)

}
}

Task 3: Building, Executing, and Playing


the Game
To build and execute the TicTacToeGame project, and
play the TicTacToe game, you need to perform the
following steps:
1. Select BuildBuild Main Project to build the
TicTacToeGame project.
2. Select RunRun Main Project to execute the
TicTacToeGame project. The
DefaultColorPhone emulator window is
displayed, as shown in the following figure.

The DefaultColorPhone emulator


3. Click the soft key below Launch on the
DefaultColorPhone emulator to launch the
TicTacToe_Midlet MIDlet, as shown in the
following figure.

The DefaultColorPhone emulator Displaying


the TicTacToe Game
4. Click the corresponding keys on the emulator
keypad to play the game.
5. Select MIDletExit to close the
DefaultColorPhone emulator window.
6. Select FileExit to close the NetBeansIDE.

Summary
In this chapter, you learned that:
MIDP Game API is a set of APIs that is used to
develop gaming applications for mobile devices.
The javax.microedition.lcdui.game
package of the MIDP 1.0 provides limited

support for game programming.


MIDP 2.0 Game API provides the following
classes to create and manage these graphic
objects:
GameCanvas
Layer
LayerManager
Sprite
TiledLayer
The GameCanvas class extends the MIDP
Canvas class and provides several additional
benefits over the Canvas class.
The GameCanvas class provides the following
two game specific capabilities:
Handling user input
Using off-screen buffer
All graphic objects in a game are represented by
the objects of the subclasses of the Layer class.
The Layer class defines the attributes, such as
location, size, and visibility of a graphic object.
The LayerManager class manages the layers
in a gaming application.
A sprite is a small graphic object that can be
moved independently around the screen to create
animation effects.
The Sprite class contains methods to create
animation effects in a graphical object.
The TiledLayer class contains methods that
are mainly used to create the background image
of a gaming application.

Exercises
Exercise 1
You are working as a mobile application developer with
Sonc Inc. Your organization develops mobile games by
using Java ME platform. You have been assigned a task of
creating a game that displays a space ship with a bullet
placed at its tip. The space ship is able to destroy its
enemies with the bullets. When the bullet collides with the
enemy, the enemy disappears. Perform the task.
Prerequisites: The following input files are required to
run the application:
BG.png
Bullet.png
Ship.png
Skull.png

Reference Reading
Introducing MIDP Game API

Reference Reading: Books


Wireless J2ME Platform
Programming By Vartan
Piroumian Publisher :
Prentice Hall PTR

Reference Reading: URLs


http://developers.sun.com/
techtopics/mobility/midp/
articles/game/

Chapter 13
Downloading MIDlet Applications
and Introducing Push Registry
Before MIDlet applications are executed on mobile
devices, they are created and tested on emulators that
provide a simulated environment. However, the emulators
that are used to test MIDlet applications do not perfectly
simulate all the features of the target mobile devices.
Therefore, after testing a MIDlet application on an
emulator, you will have to download it on the target device
and test its performance.
Besides many new features, MIDP 2.0 includes a feature
called push. This feature enables an inbound network
connection or a timer-based alarm to invoke a MIDlet
without user initiation. Consider a situation where you
need to automatically notify a mobile device user
regarding an important news update. This is possible by
using the push registry concept of MIDP 2.0 that pushes a
message to a MIDlet application and launches the
application on the mobile device.
This chapter explains the various ways of downloading a
MIDlet application on to a target mobile device. In
addition, this chapter discusses push registry. In addition,
it discusses the types of push registry and its benefits and
limitations.

Objectives
In this chapter, you will learn to:
Download MIDlets from a local machine and a Web
server
Explore the push registry

Downloading MIDlet Applications


MIDlet applications can be executed on a target mobile
device by downloading the application locally on it from a
computer. However, if you want an application to be
accessed by people all over the world, you need to deploy
it on a Web server so that it can be accessed remotely by a
mobile device.
The process of storing a MIDlet application on a Web
server is called deploying a MIDlet. After deploying a
MIDlet application, you can download it on a target
mobile device from the Web server over a wireless
network, such as GPRS.
MIDlet applications fall into the following categories:
Local applications: These MIDlet applications
do not need to access external data sources, such

as resource files, through a wireless network. For


example, a calculator application is a local
application, which does not need to access any
external data. Local applications are also known
as stand-alone applications.
Network applications: These MIDlet
applications contain some components that run
on a mobile device and other components that
run on a wireless network. As a result, these
applications need to access external resources.
For example, to run an e-mail application that is
residing on a wireless client device, the client
needs to interact with the Simple Mail Transfer
Protocol (SMTP) server to receive and send
messages.
Local applications and network applications are deployed
in a similar manner. However, local applications are easier
to execute than network applications. For example, a
calculator application can run on a mobile device even
when the device is not connected to a network. However,
an e-mail application will require the data to be
transmitted through a network to access the mails from the
SMTP server.
A MIDlet application can be downloaded in the following
ways:
By locally transferring the JAD and JAR files
from your computer to the target mobile device.
By remotely transferring the JAD and JAR files
from the Web server to the target mobile device.

Downloading MIDlets from a Local


Machine
You can download MIDlet applications on a target mobile
device from a local computer by using:
A USB cable connection.
An infrared connection.
A Bluetooth connection.

Downloading MIDlet Applications by


Using the USB Cable
You can attach a mobile device to a computer by using a
USB cable. The USB cable is attached to the USB port of
a computer. However, to create a connection by using a
USB cable, you need to install the appropriate driver for it.
To download a MIDlet application by using a USB cable,
you need to perform the following steps:
1. Install a driver for the USB cable on the computer
on which you want to deploy the MIDlet
application.
2. Attach the mobile device to the computer by
using the USB cable. A new disk drive will
appear in My Computer. On accessing this
drive, it will display the folders and sub folders

that represent the file system of the mobile device


attached to the computer.
3. Copy the JAR and the JAD file of the MIDlet
application to the appropriate folder in the new
storage device.

Downloading MIDlet Applications by


Using the IR Port
An IR port allows a computer and mobile device to
communicate without using wires. IR ports use infrared
waves to support wireless communication between a
mobile device and a computer.
To download a MIDlet application by using an IR port,
you need to perform the following steps:
1. Install an interface for the IR port on the
computer on which you want to deploy the
MIDlet application.
2. Activate the IR port on a mobile device.
3. Send the JAR and JAD files of the MIDlet
application to the mobile device through the IR
port.
4. Save the MIDlet application default executable
folder of the mobile device.

The default executable folder is set by the


device manager of the mobile device. This
folder has the executable files of all the
installed applications.

Downloading MIDlet Applications by


Using the Bluetooth Port
A Bluetooth port enables two devices to communicate in a
small area by using the Bluetooth technology that supports
short-range voice and data communication. The Bluetooth
technology states the way in which mobile phones,
computers, and PDAs interconnect with each other,
without wires.
To download a MIDlet application by using a Bluetooth
port, you need to perform the following steps:
1. Establish a network between the mobile device
and the computer on which you want to deploy
the MIDlet application.
2. Send the JAR and JAD files of the MIDlet
application to the mobile device through the
Bluetooth connection.
3. Save the MIDlet application in the appropriate
folder of the mobile device.

Downloading MIDlets from a Web


Server

A MIDlet application residing on a Web server can be


downloaded to a target mobile device. To download a
MIDlet application from the Web server to a target mobile
device, it first needs to be deployed on the Web server.

Deploying a MIDlet Application on a


Web Server
In order to allow your MIDlet applications to be accessed
by people all over the world, you need to deploy the
application on a Web server. This will enable the end users
to access your application remotely through a wireless
network.
To deploy a MIDlet application on a remote Web server,
you need to perform the following steps:
1. Upload the JAR and JAD files of the application
to the Web server. For example, if the project
name of the MIDlet application is Demo, you
need to upload the demo.jar and demo.jad files
from the dist directory of the project to the Web
server.
2. Reconfigure the Web server so that it recognizes
the JAD and JAR files. The procedure to
reconfigure the Web server depends on the Web
server that you are using.
For example, if you are using the Tomcat Web
server, you need to include the following code
snippet in the web.xml file to configure it:
<mime-mapping>
<extension>jad</extension>
<mime-type>text/
vnd.sun.j2me.app-descriptor</
mime-type>
</mime-mapping>
<mime-mapping>
<extension>jar</extension>
<mime-type>application/javaarchive</mime-type>
</mime-mapping>

If you are using Netbeans with Sun


java Application Server, you need not
add the MIME types for the JAD and
the JAR files. They are included in the
default MIME type mappings of the
Sun Java Application Server.
3. Change the MIDlet-Jar-URL property of the
JAD file to specify the URL of the JAR file to the
Web server. For example, if the Demo.jad file
contains the MIDlet-Jar-URL property as
Demo.jad, replace it with the following code
snippet:
MIDlet-Jar-URL: http://

<WebServerAddress>:<port>/<path>/
demo.jar

Downloading a MIDlet Application to


a Target Mobile Device
After deploying the MIDlet application on the Web server,
you can download it to the target mobile device by
connecting to the Web server and downloading the
MIDlets by using an Over-The-Air (OTA) provisioning
system. The OTA provisioning system allows you to
download any MIDlet application on demand. As a result,
you can access MIDlets from any place where wireless
coverage is available.

OTA Architecture and Components


The OTA provisioning system architecture defines various
components and their interactions. The following figure
shows the OTA architecture and its components.

Architecture of OTA Provisioning System


The various components of the OTA provisioning system
are:
Client mobile device: This component is used by
the client to access, download, and use the
mobile applications. The client mobile device is
the target device on which the downloaded
mobile application is executed. The client mobile
device should have the software that will allow
the users to locate and access the mobile
application deployed on the provisioning server.
This software is known as Discovery Application
(DA).
Wireless network: This component is used as a
communication medium between the client
mobile device and the provisioning server. For
example, the wireless network can be a WAP
gateway that allows mobile phone users to access
the data stored in the provisioning servers.
Provisioning server: This component is a Web
server, which interacts with the client device by
using the Wireless network. Provisioning server
is also known as a download server or a vending
machine. Provisioning server provides access to
the content repository in which the mobile
applications are stored for the client mobile
devices. In addition, this component provides a
UI that displays a list of applications to the client
mobile device. The UI is created by using a

markup language that is compatible with the


client mobile device. For example, you can create
the UI by using Wireless Markup Language
(WML) or HTML.
Content repository: This component is used to
store mobile applications and their descriptors.
The content repository should support features
such as version management and security for the
stored mobile applications.

Basic Features of OTA


The OTA provisioning system involves several activities,
such as content management, content indexing and search,
authentication, application retrieval and installation,
conformation and error display, and track mechanism.
The following figure shows a detailed view of an OTA
provisioning system.

Detailed View of an OTA Provisioning System


The descriptions of various labels provided in the
preceding figure are:
Content management: This feature is
implemented at the provisioning server and it
manages the content repository, which is a
database of mobile applications. This feature
performs version management of the applications
stored in the content repository. This feature also
enables third party developers to register and add
their mobile applications to the content
repository.
Content indexing and search: This feature
improves the speed of accessing mobile
applications by implementing appropriate
indexing and search techniques on the content
repository. This feature also enables the clients to
search for the applications in the content
repository based on the specified criteria.
Authentication: This feature confirms the
identity of the users requesting for information
before allowing them to gain access to the
content repository.
Application retrieval and installation: This
feature involves downloading and installing the
application. It is handled by AMS. If a JAD file
exists, the AMS downloads it from the
provisioning server's repository. If required, the
user is re-authenticated. Once the application is

downloaded successfully, the installation of the


application is done automatically.
Confirmation and error display: This feature
enables the clients to send a confirmation on
successfully downloading the application. This
feature also enables the provisioning server to
send appropriate error messages in case of
various errors, such as application nt available
and client device not supported.
Track mechanism: This feature enables the
application providers to track the usage of a
mobile application by the clients. For example,
you can implement a billing system to charge the
customers who have downloaded a gaming
application and are using it.
The OTA provisioning system also provides some optional
features. These are:
Personalization: This feature enables the
provisioning server to offer mobile applications
to the clients based on their preferences.
Selective content display: This feature enables
the provisioning server to display only those
applications to the clients that are supported by
their mobile devices. In case a provisioning
server does not have any application that is
supported by the client's mobile device, then it
does not show any application when the client
connects to the provisioning server.
Security: This feature allows the servers to
authenticate the users and enable them to use
secure connections, such as HTTPS, for
downloading applications.
Alerts: This feature enables the provisioning
server to send alerts to the users to notify them
regarding addition, removal, and updation of
applications in the content repository.

Processes in the OTA Provisioning


System
OTA provisioning system provides the following set of
processes to download mobile applications:
Discovery: This process searches for the
applications on the wireless network, downloads
a menu of applications that can be downloaded
through OTA, and allows the users to select an
application of their choice. This process is
performed by using DA that is installed on the
mobile device. Some devices might also provide
browser support for searching and viewing the
applications before downloading.
Installation: This process involves downloading
a JAR file and providing it to the users for
execution. In case the MIDlet application has a
JAD file associated with it, the AMS uses the
MIDlet-Jar-URL property of the JAD file to

download the application. The JAD and the


manifest file also contain the MIDletInstall-Notify attribute that specifies the
URL to which a post request is made in order to
confirm the successful installation of the MIDlet
suite.
Update: This process is similar to the installation
process except that it also involves an additional
process of comparing the mobile application
versions before downloading. For example, the
AMS compares the versions of the MIDlet
applications on the provisioning server and the
client machine. The AMS then notifies the user
whether it is installing a newer, older, or identical
version. Further, it asks them whether to replace
the existing MIDlet or not.
Execution: This process involves displaying a
list of MIDlets available in a client mobile device
to its user. The AMS allows the user to select a
MIDlet suite, and then select the required
MIDlet. Once the user selects the MIDlet, the
AMS instantiates it, which starts the life cycle of
the MIDlet.
Removal: This process enables the users to select
the application they wish to remove. On selecting
an application for removal, the AMS displays a
warning message to the user and waits for a
confirmation. For example, if a MIDlet suite
contains multiple MIDlets, the AMS displays a
warning message regarding the removal of all the
MIDlets and associated record stores. After
receiving the confirmation from the user, the
AMS removes the application. The warning
message that is provided to the user when
prompted to confirm deletion of the MIDlet suite
is specified by the MIDlet-DeleteConfirm attribute of the JAD file.
The following figure shows the various processes and their
interactions with AMS.

OTA Provisioning Processes


The following steps take place while downloading a
MIDlet application on a mobile device:
1. The mobile device searches for the MIDlet
application by using the DA software. The DA

contains a URL that references the JAR or JAD


file of the MIDlet application.
2. If the URL references a JAD file, the mobile
device downloads and examines the contents of
the MIDlet application. This helps to ensure that
the mobile device contains the required resources
to run the MIDlet application before attempting
to download the JAR file.
3. If the URL references a JAR file, or if the JAD
file check is successfully completed, the mobile
device downloads the JAR file and installs it.
4. The mobile device sends a notification to the Web
server. This notification indicates whether the
MIDlet application is installed successfully. The
following figure shows the OTA installation
process of a MIDlet application.

response to the status report, the Web server replies with


an HTTP response. If the mobile device cannot send the
status report during installation, the mobile device sends
the installation status report when a MIDlet in the MIDlet
application is executed, and the mobile device is
connected to the wireless network.
The following table describes the status codes received
from the Web server, to report the status of installation.

Table Describing the Status Codes Received from the


Web Server

Introducing the Push Registry


OTA Installation Process

Identifying the Installation Status


Reports
After downloading the MIDlet application, you can check
whether the application has been downloaded successfully
or not. If not, you can then identify and resolve the issues
related to unsuccessful installation of the MIDlet
application. To identify whether a MIDlet application has
been installed successfully or not, you can specify URLs
in the JAD file, which report the installation status of the
MIDlet application.
The mobile device, where the MIDlet application is
installed, generates and sends a status report of the
installation of the MIDlet application to the Web server. In

Push refers to the ability of an application to receive and


act on information asynchronously, as information
becomes available.
At times, you need to push information from a server and
launch the application automatically on a mobile device
without the user starting the device explicitly. The push
registry is a feature that enables MIDlet applications to
launch automatically, without user initiation. This feature
is provided in MIDP 2.0 of Java ME.
In MIDP 1.0, the AMS starts a MIDlet. However, with the
introduction of MIDP 2.x, you do not need the AMS to
start MIDlet applications. A MIDlet application can also
start based on a notification from a remote connection or a
timer-based alarm. This process of starting MIDlet
applications through external notifications is called push
registry.
Push registry uses the following ways to start a MIDlet
application:
Remote connection: Is used to start a MIDlet

application when it needs to connect to a remote


server. For example, a remote application can use
the remote connection feature of the push registry
to launch a news MIDlet application, which
needs to connect to a remote server to display
news on a mobile device.
Timer-based alarm: Is used to launch a MIDlet
application that needs to be invoked based on a
scheduled task. For example, you can use the
timer-based alarm feature to launch a MIDlet
application automatically for various scheduled
events, such as birthdays and anniversaries.

Introducing the Push Registry API


The push registry is a part of the GCF and it is handled by
the javax.Microedition.io.PushRegistry
class.
You need to register the push registry with a MIDlet
application to implement it on the MIDlet application. The
PushRegistry API helps you to register and implement the
push registry on MIDlet applications.
The PushRegistry API implements push registry in the
following three phases:
Registration: In this phase, the MIDlet
application is registered with all the network
connection types that need to be supported by the
push registry.
Listening: In this phase, the AMS listens for
registered connections and launches the
appropriate MIDlet.
Processing: In this phase, the AMS processes the
MIDlet application that is registered with the
push registry.
The following figure illustrates the phases of
implementing a push registry.

Phases of Push Registry Implementation


Push registry is a part of the GCF, and is implemented by
using the methods of the PushRegistry class.
The following table describes some of the methods of the
PushRegistry class.

Method
getFilter()

Description
Returns the filter <AllowedSender> for the connection
that is to be registered
getMidlet()
Returns the MIDlet
responsible for handling the
connection that is to be
registered
listConnections() Returns a list of registered
connections for a MIDlet
application
registerAlarm()
Registers an alarm based
push registry to launch the
MIDlet
registerConnection Registers a connection
()
unregisterConnectio Unregisters a connection
n()

Some Methods of the PushRegistry Class


Various exceptions are encountered when using the
methods of the PushRegistry class. These are:
ClassNotFoundException: Is thrown by
the registerConnection() method and the
registerAlarm()method when the specified
MIDlet class name cannot be found in the current
MIDlet suite.
ConnectionNotFoundException: Is
thrown by the following methods:
registerConnection(): Is thrown
when the platform does not support the
specified connection type for push inbound
connections.
registerAlarm(): Is thrown when the
platform does not support alarm-based
application launch.
Connector.open(): Is thrown when
the requested protocol does not exist, or the
connection could not be made.
IllegalArgumentException: Is thrown by
the following methods:
registerConnection(): Is thrown
when the connection string is not valid, or
the filter string is not valid.
Connector.open(): Is thrown when
one of the arguments is invalid.
IOException: Is thrown by the following
methods:
registerConnection(): Is thrown
when the connection is already registered,
or there are insufficient resources to handle
the registration.
Connector.open(): Is thrown when a

generic I/O error is encountered.


SecurityException: Is thrown by the
following methods:
registerConnection(): Is thrown
when the specified MIDlet does not have
permission to register a connection.
unregisterConnection(): Is
thrown when the specified connection was
registered by another MIDlet suite.
registerAlarm(): Is thrown when the
specified MIDlet does not have permission
to register an alarm.
Connector.open(): Is thrown when
the MIDlet has no permission to use the
requested protocol.

Identifying the Benefits and


Limitations of Push Registry
The primary benefit of using the push registry is that it
enables you to start a MIDlet application from a remote
connection without user intervention. In addition, push
registry supports network protocols, such as a socket and a
datagram, to help network-based push activation.

Besides its benefits, the push registry has certain


limitations. These limitations are:
Two MIDlet suites cannot share the same push
registry connection.
A MIDlet application is not installed if any
statically-declared connection fails to get
registered during the installation of the MIDlet
application.
Push registry does not support certain inbound
connection protocols. For example, a mobile
device may support a socket protocol connection,
but the push registry may not support it.

Identifying the Types of Push


Registry
A push registry supports network and timer initiated
MIDlet activation. This means that a MIDlet can be
activated by either using a network or by using a timerbased alarm.

Network-based MIDlet Registration


The MIDlet application is launched when a mobile device
receives a network connection request. You can use the
following two types of push registry when using a network
to activate the MIDlet:
Static

Dynamic

Static
A MIDlet registers a connection statically by specifying
and distributing the connection string in the application
descriptor of the MIDlet application.
You can declare a static push registration by using the
MIDlet-Push-n attribute. This attribute can be added
either in the JAD file or JAR manifest file of the MIDlet
application. While installing the MIDlet application, the
mobile device registers it to accept the connections.
The following code snippet shows the syntax to add the
MIDlet-Push-n attribute:
MIDlet-Push-n: ConnectionURL,
MIDletClassName, Filter
In the preceding code snippet:
MIDlet-Push-n specifies the name of the
attribute.
ConnectionURL specifies connection string
used in the Connector.open() method.
MIDletClassName specifies the name of the
MIDlet that creates and registers the connection
with the MIDlet application.
Filter specifies the senders that are authorized
to launch the requested MIDlet application.
Static push registrations can cause several errors while
installing a MIDlet application. The following points
specify some of these errors:
Having syntax errors in the push attributes
Declaring a connection that is already reserved
for another MIDlet application
Declaring a protocol, which a mobile device does
not support, for implementing push registry
Referencing a MIDlet class name that is not
listed in the attributes of the MIDlet application

Dynamic
A MIDlet registers a connection dynamically by using the
PushRegistry class at runtime. When the AMS detects
an incoming connection associated with a MIDlet, the
AMS starts the MIDlet and calls the startApp()
method. The MIDlet then processes the incoming
connection request.
Dynamic registration is performed by using the
PushRegistry.registerConnection() method.
In a dynamic registration, the arguments for PushMIDlet-n attribute are the same as those used in a static
registration. The MIDlet application needs to provide the
connection string, the MIDlet, and the filter string. The
dynamic registration can throw several exceptions if the
registration is not performed properly.
Various exceptions thrown by a dynamic registration are:
IllegalArgumentException: Is thrown if

the connection of filter arguments is null.


ClassNotFoundException: Is thrown if the
MIDlet argument is null or if the name of the
class is not found in the MIDlet suite.
ConnectionNotFoundException: Is
thrown if the Java ME platform does not support
push notification for the requested connection
protocol.
IOException: Is thrown if the connection is
already registered or if there are insufficient
resources to process the registration request.
SecurityException: Is thrown if the
MIDlet application does not have permission to
register a push connection.

Alarm-based MIDlet Registration


A timer-based alarm can be used to invoke a MIDlet
application. For example, a MIDlet application developed
to sell movie tickets on a mobile device can send an alarm
to the buyer just before the movie is about to begin.
The MIDlet calls the registerAlarm() method of the
PushRegistry class to invoke the MIDlet application.
The name of the MIDlet application that is to be invoked
and the time to invoke the MIDlet application are passed
as parameters to the registerAlarm() method.

The name of the MIDlet application, which is


passed to the registerAlarm() method,
must be specified in the JAD file or JAR
manifest file of the MIDlet application, with
theMIDlet-n attribute.
The push registry supports one alarm per MIDlet
application. If you make a new registration for an alarmbased push registry and the registry already exists, the
existing push registry is overwritten.
You can use the PushRegistry.registerAlarm()
method to retrieve the time of the old registration. If the
registration is not performed properly, the
registerAlarm() method can throw several
exceptions.
Various exceptions thrown by the registerAlarm()
method are:
ConnectionNotFoundException: Is
thrown if the Java ME platform does not support
alarm-based push registry.
ClassNotFoundException: Is thrown if the
MIDlet class name provided is null or the
specified MIDlet application is not present in the
MIDlet suite.
SecurityException: Is thrown if the
MIDlet application does not have permission to

register an alarm-based push registry.


When using a timer-based alarm, a mobile device may not
always launch a MIDlet application if the timer for the
alarm is set.
This situation may arise in the following conditions:
If the mobile device is off when the MIDlet
application is scheduled for launch.
If the MIDlet application is already running when
the MIDlet application is scheduled for launch.

Describing the Inbound Connection


Type of Network-Based Push
Activation
To support network-based push activation, the Java ME
platform should support general inbound connection types.
This is because MIDlet applications are activated by an
inbound connection. MIDP 1.0 supports only client type
network connection, called HttpConnection. MIDP
2.0 and above defines additional connection types, such as
TCP, UDP, and SMS.
Inbound connections can be message-based or packetbased. SMS or stream-based connections, such as TCP, are
examples of message-based inbound connections.
Datagrams are examples of packet-based inbound
connections. Some of these connections, such as SMS,
may buffer incoming data before a MIDlet application is
activated. Other types of inbound connections, such as
sockets or datagrams, do not support buffering.
An inbound network connection is identified with its static
or dynamic local address. A local address consists of two
parts, an IP address and a port identifier. A static local
address provides both the protocol and the inbound port
number. A dynamic local address provides the protocol of
a network connection.
The following code snippet shows examples of creating
inbound connections based on static local address:
Connector.open("socket://:5000")
Connector.open("datagram://:5000")
Connector.open("sms://:5000")
The following code snippet shows examples of creating
inbound connections based on dynamic local address:
Connector.open("socket://")
Connector.open("datagram://")
When using a system-assigned address, the address must
be published to avoid any connections to the application

by the external system. If you are using a


ServerSocketConnection or a
UDPDatagramConnection, you can get the
dynamically assigned address by using the
getLocalAddress() method and the
getLocalPort() method. Also, you can also retrieve
the hostname assigned to a device, by invoking the
System.getProperty
("microedition.hostname") method. You can use
HTTP to publish the dynamic address on an external
system.

Running a Sample Application via


OTA
Problem Statement
Chris Williams is working with the TechFreak Inc. as a
Wireless Application Developer. He has developed an
application by using Java ME. Now, he wants to upload
his application on a Web server and download it on the
mobile device by using OTA provisioning. However,
before doing this he needs to check how an application is
downloaded and installed on a mobile device by using
OTA provisioning. Therefore, he decided to run a sample
application via OTA in the Java(TM) ME Platform SDK
3.0 emulator.

Solution
To run a sample application via OTA, Chris needs to
perform the following tasks:
1. Open a project in Java(TM) ME Platform SDK
3.0.
2. Run the project via OTA.

Task 1: Opening a Project in Java() ME


Platform SDK 3.0
To open a project in Java() ME Platform SDK 3.0, Chris
needs to perform the following steps:
1. Select startAll ProgramsJava() ME
Platform SDK 3.0Java() ME Platform
SDK 3.0 to open the Java() Platform, Micro
Edition Software Development Kit 3.0 window.
2. Select FileOpen Sample
ProjectPhotoAlbum. The Java() Platform,
Micro Edition Software Development Kit 3.0
window with the current status of the
PhotoAlbum project is displayed, as shown in
the following figure.

The Java() Platform, Micro Edition


Software Development Kit 3.0 Window

Task 2: Running the Project via OTA


To run the project via OTA, Chris needs to perform the
following steps:
1. Select RunRun Main Project via OTA to
start running the MIDlet application via OTA.
The DefaultCldcMsaPhone1 emulator window
appears, as shown in the following figure.

The DefaultCldcMsaPhone1 Emulator


Window

The Emulator Window Displaying the


Downloading Message
3. Next, the Confirmation screen is displayed on
the emulator window, as shown in the following
figure.

The address of the Web site link may


differ each time you run the
application.
2. After the emulator connects to the website, the
Downloading the application description file...
screen is displayed on the emulator window as
shown in the following figure.

The Emulator Window Displaying the


Confirmation Screen
4. Press the soft key below Install to install the
PhotoAlbum application. The Installing
Application screen is displayed, as shown in the
following figure.

The Emulator Window Displaying the


Downloading Status
5. After the emulator downloads the
PhotoAlbum.jad file, it verifies the file and the
Verifying the application... screen is displayed,
as shown in the following figure.

The Emulator Window Displaying the


Verifying the application Screen
6. After verifying the PhotoAlbum.jad file, the
emulator finishes the installation and the
Finishing installation. screen is displayed, as
shown in the following figure.

The Emulator Window Displaying the


Finishing installation Screen
7. After finishing the installation, the Application
was successfully installed alert screen is
displayed. This alert screen is followed by the
Java MIDlets screen, as shown in the following
figure.

The Emulator Window Displaying the Java


MIDlets Screen

The Emulator Window Displaying the Images


Screen

8. The preceding screen is followed by the Images


screen, as shown in the following figure.

If you do not launch the PhotoAlbum


application manually, it will
automatically get launched after few
seconds.
9. Close the emulator window.
10. Select FileExit to close the PhotoAlbum Java() ME Platform SDK 3.0 window.

Summary
In this chapter, you learned that:
You can download MIDlet applications on a
target mobile device from a local computer by
using:
A USB cable connection.
An IR connection.
A Bluetooth connection.
MIDlet applications can be downloaded by using
OTA provisioning system. The steps to download
the MIDlet application are:
a. Upload the JAR and JAD files to the
Web server.
b. Reconfigure the Web server so that it
recognizes the JAR and JAD files.
c. Change the MIDlet-Jar-URL
property of the JAD file, to specify the
URL of the JAR file to the Web server.
The OTA provisioning system allows you to
download any MIDlet application present on
Java-based server on demand.
The various components of the OTA provisioning
system are:
Client device
Wireless network
Provisioning server
Content repository
OTA provisioning system provides the following
set of processes to download mobile applications:
Discovery
Installation
Update
Execution
Removal
Push registry is a feature that enables the MIDlets
to launch automatically, without user initiation.
Push registry is a part of the GCF and is
implemented by using the methods of the class,
javax.microedition.io.PushRegistr
y. The push registry is a part of the GCF and it is
handled by the
javax.Microedition.io.PushRegistr
y class.
Push registry is implemented in the following
phases:
Registration
Listening
Processing
Push registry invokes a MIDlet application by:
Using a network
Using a timer-based alarm
When using a network to activate the MIDlet,

you can use the following two types of push


registry:
Static
Dynamic
Alarm-based push registry helps to invoke a
MIDlet application at a preset time.
To support network-based push registry, the Java
ME platform should support general inbound
connection types.

Reference Reading
Downloading MIDlet Applications
Reference Reading: Books Reference Reading: URLs
Core J2ME Technology & http://developers.sun.com/
MIDP By John W. Muchow. techtopics/mobility/midp/
articles/ota/
Wireless J2ME Platform
Programming By Vartan
Piroumian Publisher:
Prentice Hall PTR

Glossary
C
CBS
Cell Broadcast Service is a protocol which enables the
network carriers to broadcast messages to all mobile
devices reachable from a certain cell station.
CLDC
Connected Limited Device Configuration (CLDC) is a
configuration supported by Java ME for wireless mobile
devices with very limited hardware capabilities.
Clip
It is a rectangular region consisting of a set of pixels.
These set of pixels are painted by a Graphics object.
Configuration
It defines class libraries for a range of devices that have
similar requirements for memory, processing power, and
network connectivity.
D
Double buffering
It is a technique in which you draw graphical objects on
the off screen buffer of a mobile device, and display the
content of the off screen buffer as and when required. This
technique reduces the flickering effect and enables you to
create high quality graphics and animations.
E
EDGE
It is a 3G wireless technology that provides broad
bandwidth and faster data transfer as compared to the 2G
wireless technology in mobile devices.
Emulator
It is a testing environment for testing the MIDlets.
Event Handling
It is the process of handling the user interactions by using
the user interface an application.
G
GCF
GCF provides a common API that is used for wireless
network communication. GCF itself does not provide any
protocol implementation, but it allows the vendors
implementing the MIDP profiles, to implement the
required protocol by implementing the corresponding
interface.
GPRS
Is a data service that sends and receives information across
a wireless mobile telephone network.
GSM
It is the global standard for digital mobile communication.
Game API

It is a set of APIs used specifically to develop gaming


applications for mobile devices.
H
High level UI API
It defines a set of classes and interfaces, which help in
creating portable UI components, which can be deployed
on a variety of mobile devices.
I
IR port
Infra Red (IR) port allows a computer and a mobile device
to communicate without using wires. IR port can be used
to transfer a mobile application from a computer to a
mobile device.
J
Java EE
It is a Java 2 Platform, Enterprise Edition (Java EE),
which defines the standard for developing componentbased multitier enterprise applications.
Java ME
It is Java 2 Micro Edition (Java ME) is a Java-based
platform that provides an environment for developing
applications for mobile devices.
Java SE
It is a Java platform to create Java applets and applications
that are stand alone and Web-based. It is a core collection
of tools and APIs.
JAD
It is a Java Application Descriptor file that specifies the
properties of a MIDlet application.
JTWI
Java Technology for the Wireless Industry (JTWI)
specification defines a standard for the Java ME runtime
environment to develop and deploy mobile applications
for mobile devices.
K
KVM Layer
It represents a virtual machine similar to the Java Virtual
Machine (JVM). The KVM is a compact JVM that is
designed for resource-restricted devices.
L
Low Level UI API
It defines a set of to classes and interfaces, which help in
creating highly customized UI components.
M
MIDlet Security
Security in a MIDlet is implemented by applying security
to MIDlet applications, downloading the resources from
trusted MIDlets, and implementing secure HTTP
connection over SSL.
MIDlet
It is a mobile application developed by using Java ME
APIs. It is a Java class file packaged into a JAD (Java
descriptor) file.

MIDP
It is a set of Java APIs that provide a complete Java ME
application runtime environment for mobile phones.
MMAPI
It provides a set of classes and interfaces, which can be
used to create and play multimedia content on a mobile
device.
MP3
MPEG layer 3 (MP3) is a popular sound file format that is
supported by the MMAPI.
MMS
Multimedia Message Service (MMS) is a protocol for
sending and receiving various types of multimedia
contents, such as images and audio and video clips.
O
Obfuscation
The compiled class files of Java can be reverse engineered
to produce the Java source files by using a tool called
decompiler. This process is a threat to the Java source
files. Obfuscation prevents this threat by preventing
reverse engineering.
Optional Package
It is a set of classes and interfaces providing specific
functionality, such as database access or multimedia.
OTA
Over The Air (OTA) provisioning is a technique for
deploying and distributing mobile applications.
P
Persistent Storage
Persistent storage is a permanent storage space that is used
for storing data and objects. The data in the persistent
storage persists even after the application that created the
data is terminated.
Profile
It defines class libraries for a narrower category of devices
within the framework of a chosen configuration.
PDAP
Personal Digital Assistant Profile (PDAP) is a profile
defined for Personal Digital Assistants (PDA).
PNG
Portable Network Graphics (PNG) is an image format that
is used to store the graphical objects in a mobile device.
Preverification
This process is done before loading a class file into the
memory of a mobile device and it reduces the amount of
work done by the mobile device.
R
Record store
It is an ordered collection of records storing the data about
a particular MIDlet.
RMS
Record Management System (RMS) is a record-based
database, which is used to persistently store the data

associated with a MIDlet.


S
SMS
Simple Message Service (SMS) is a protocol that allows
you to send and receive messages by using a mobile
device.
SSL
Secure Socket Layer (SSL) is a socket protocol that
secures the data to be transferred over the network by
encrypting it.
Sprite
MIDP Game API is a set of APIs used specifically to
develop gaming applications for mobile devices.
T
TCP/IP
It is the standard Internet protocol that allows you to send
and receive data over wired or wireless networks.
TDMA
Time Division Multiple Access (TDMA) is a secondgeneration modulation standard that uses bandwidth in the
800 MHz, 900 MHz, and 1900MHz ranges.
Ticker
It is a constantly moving piece of text that is displayed on
the UI of a mobile device.
Trusted MIDlet suite
It is a MIDlet suite for which a mobile device can reliably
determine source, authenticity, and integrity of the JAR
file.
W
WAP
Is a protocol for browsing the Internet on a mobile device.
WMA
Wireless Messaging API (WMA) is an optional package
that is used to send and receive messages from mobile
devices.
WML
Wireless Markup Language (WML) is a markup language
used to create applications for small wireless devices, such
as mobile phones.
X
X.509 certificate
It is a certificate profile that is used for implementing
trusted MIDlet suites.

Certification Mapping
This course covers the objectives of certification exam
Sun Certified Mobile Application Developer for Java
Platform, Micro Edition.

You might also like