Professional Documents
Culture Documents
DMAJ - II/SG/10-M06-V02
Copyright NIIT. All rights reserved.
COURSE DESIGN-STUDENT
GUIDE
Objectives
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.
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
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.
Objectives
In this chapter, you will learn to:
Establish network connection by using GCF
Implement network connectivity by using MIDP
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
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
InputStream mIn =
mHttpConnection.openInputStream();
int len = (int)
mHttpConnection.getLength();
Connector.READ_WRITE,true);
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<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<");
os.write((requestString+"\r
\n").getBytes());
import javax.servlet.*;
os.flush();
import javax.servlet.http.*;
if (os != null)
os.close();
*/
}
public void doPost(HttpServletRequest
request,
/**
HttpServletResponse response)
* @param request Wrapper around
client data
throws IOException,
ServletException {
InputStream in;
OutputStream out;
DataInputStream din;
DataOutputStream dout;
problem occured
*/
try{
in = (InputStream)
request.getInputStream();
out = (OutputStream)
response.getOutputStream();
/**
* @param request Wrapper around
client data
dout = new
DataOutputStream(out);
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
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.
PrintWriter out =
response.getWriter();
out.println("No GETs
allowed.");
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.*;
shadow"+","+"India has
done well in second test";
try{
in =(InputStream)
request.getInputStream();
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
();
System.out.println
("**********\n\nRequest
Got From client\n
\n**********");
dout.write(byteArr);
System.out.println
("\n\n **********\n\nnews
is sent..\n
\n***************");
/** 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;
StringBuffer sb =
int count = 0;
int requestType = 0;
String serverResponse
{
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;
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:
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
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
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
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.
specification
javax.microedition. Multi-media APIs for
media.control
playback of sound. Defines
the specific Control types
that can be used with a
Player.
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.
Answer:
True
Just a minute:
Which exception is thrown when a required
permission is not granted to a MIDlet suite?
Answer:
The SecurityException exception
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.
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.
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.
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.
Summary
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.
Objectives
In this chapter, you will learn to:
Identify Mobile Media API
Implement MMAPI package
ContentDescriptor
DataSource
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.
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
ToneControl
VideoControl
VolumeControl
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.
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.
REALIZED
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
tonePlayer.realize();
ToneControl tc = (ToneControl)
tonePlayer.getControl("ToneControl");
tc.setSequence(mySequence);
tc.start();
}
catch (IOException ioe) {}
catch (MediaException me) {}
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)
{
...
}
Answer:
Prefetch()
int id;
Thread.currentThread().sleep(10);
try {
InputStream is= getClass
().getResourceAsStream("audio.midi");
Player midiplayer =
Manager.createPlayer(is, "audio/midi");
midiplayer.start();
}
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;
VolumeControl vcontrol;
try {
try {
mp3player = Manager.createPlayer
("http://server/music.mp3");
mp3player.realize();
Player player =
Manager.createPlayer("capture://
audio");
player.realize();
vcontrol = (VolumeControl)
mp3player.getControl("VolumeControl");
if(vcontrol != null) {
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 (InterruptedException e) { }
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 CanvasVideo () {
width = getWidth();
height = getHeight();
}
public void commandAction(Command c,
Displayable s) {
if (c == done) {
}
}
}
The preceding code snippet creates a video player named
vPlayer that is defined in the CanvasVideo class,
which extends the Canvas class.
Implementing Camera
...
Player player;
VideoControl vc;
player.realize();
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();
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.
(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 ){
}
in = null;
}
public PlayerMIDlet(){
display = Display.getDisplay
{
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) {
}
}
}
}
8. Copy the given sound files, airhorn.wav and
intro.midi and paste them in the <Drive
Letter>:\JavaMEProjects\src folder.
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
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 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.
(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.
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.
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.
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
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;
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();
}
...
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.
{
// Handle or ignore the
exception
}
}
}
public void processMessage
(message) {
following figure.
Summary
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
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
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.
}
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");
}
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();
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.
// 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)
delay = 20;
import javax.microedition.lcdui.game.*;
(playerImage,32,32);
Image backgroundImage =
Image.createImage("/background.png");
playerSprite.setFrame(0);
layerManager.append(playerSprite);
layerManager.append(backgroundSprite);
// Left
playerSprite.setFrame(1);
}
// Up
input();
drawScreen(g);
playerSprite.setFrame(2);
try { Thread.sleep(delay); }
// Down
}
// Method to Display Graphics
private void drawScreen(Graphics g) {
//g.setColor(0x00C000);
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
Description
Displays the mirror image
of a Sprite object, about
Just a minute:
Which method will you use to retrieve the total
number of frames in a graphic object?
Answer:
public int getRawFrameCount()
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
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)
Developing a Tic-Tac-Toe
Application
Problem Statement
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.
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
()
{
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)
}
}
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
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
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
<WebServerAddress>:<port>/<path>/
demo.jar
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()
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
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.
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,
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
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
Certification Mapping
This course covers the objectives of certification exam
Sun Certified Mobile Application Developer for Java
Platform, Micro Edition.