Ads 468x60px

Pages

Wednesday, July 20, 2011

Developing mobile games with J2ME

The Game API
The Game API in J2ME facilitate easy development of game applications for mobile devices. Although most of the game applications are nowadays developed with the help of Eclipse, some small entry level games can be developed with the help of sun java wireless tool kit. The Java ME includes the javax.microedition.lcdui.game package that contains the classes such as GameCanvas class and Layer class. In addition to this, the following classes are present in this package.

  • The GameCanvas class
  • The layer class
  • The LayeManager class
  • The TiledLayer class
  • The Sprite class


The GameCanvas class
The GameCanvas class is a sub-class of the javax.microedition.lcdui.canvas class that allows developer to develop game user interface. Its functions include handling commands and input events that has been inherited from the canvas class.. Mobile developers mostly use the game canvas class for easy development of games.

The following code shows the use of GameCanvas class

public void GameCanvasDemo extends GameCanvas iplements Runnable

{

 public void run()

 {

 while(true)

 {

  repaint();

 }

 }

 public void paint(Graphics g)

 {

 }

 protected void keyPressed(int keycode)

 {

 }

}


The Layer class
The Layer class represents a visual layer of a game. Each layer has a position that is represented in terms of coordinates. Also, each layer has height and width and can be made visible or invisible depending on the application requirements. Always the initial position of a layer has (0,0) as its coordinates. The layer class has the abstract method public void paint() that must be implemented in the game application.

The LayerManager class
The LayerManager class as its name implies is used to manage the elements of the layer class. This class can be used to maintain the objects of the Layer class in a sequential manner as required by the application. It also provides functionalities such as view window to control and render game's layer on the screen.

The following code shows the implementation of the LayerManager class

LayerManager manager = new LayerManager();

lmanager = new LayerManager();

int w = getWidth();

int h = getHeight();

lmanager.setViewWindow(96,0,w,h);

Sprite sprite = new Sprite(imageframes, 16, 16);

manager.append(sprite);


The TiledLayer class This class in used to represent the layer in a game application in terms of a number of tiles. A tiled layer is a visual object that is filled from a palette of tiles. A single large image can be divided into a number of tiles with the help of the TiledLayer class. Each tile will then be assigned a unique index number which can later on be used for reconstruction of the original image.

The following code shows the constructor of the TiledLayer class.

public TiledLayer(int columns, int rows, Image image, int width, int height)


The Sprite class
The sprite class is used to represent graphical images that can move around and interact with each other on a 2-dimensional game application. However, in the game API, these images are known as sprite. Each sprite is represented in the cartesian coordinated consisting of x and y coordinates. In a game application, the sprite class is mainly used to develop animated graphics.

The following code shows the implementation of the Sprite class

void init()
{

 try

 {

 image = Image.createImage("/filename.png);

 }


 catch(Exception e)
 {


 }
 msprite = new Sprite(image, 90, 34);

}

public void paint(Graphics g)

{
 msprite.setRefPixelPosition(1,1);

 msprite.nextFrame();

 msprite.paint(g);

}

Canvas class

Implementing Canvas class


import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 public Sample()

 {

  display = Display.getDisplay(this);

  Canvas canvas =  new Mycanvas();

 }

 
 public void startApp()

 {

  display.setCurrent(canvas);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

public class New extends Mycanvas
{
 public void paint(Graphics g)

 {

 g.setColor(0,255,0);

 g.drawRect(10,10,40,20);

 }

}

DateField class

Implementing DateField class


import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 private DateField date;

 private Form form;

 public Sample()

 {

  display = Display.getDisplay(this);

  date = new DateField("Date", DateField.DATE_TIME);

  form = new Form("hello");

 }

 
 public void startApp()

 {

  form.append(date);

  display.setCurrent(form);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

Image class and ImageItem class

Implementing Image class and ImageItem class


import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 private Image image;

 privae ImageItem imageitem;

 private Form form;

 public Sample()

 {

  try

  {

  display = Display.getDisplay(this);

  image = Image.createImage("/nature.png");

  imageitem = new ImageItem("image", image,

         ImageItem.LAYOUT_CENTER, "image");

  form = new Form("hello");

  }

  catch(Exception e)

  {

  }

 }

 
 public void startApp()

 {

  form.append(imageitem);

  display.setCurrent(form);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

Gauge class

Implementing Gauge class


import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 private Gauge downloadbar;

 private Form form;

 public Sample()

 {

  display = Display.getDisplay(this);

  downloadbar = new Gauge("donload", False, 70, 30);

  form = new Form("hello");

 }

 
 public void startApp()

 {

  form.append(downloadbar);

  display.setCurrent(form);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

TextField class

Implementing TextField class


import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 private TextField textfield;

 private Form form;

 public Sample()

 {

  display = Display.getDisplay(this);

  textfield = new TextField("hello", " ", 256, TextField.ANY);

  form = new Form("Hello");

 }

 
 public void startApp()

 {

  form.append(textfield);

  display.setCurrent(textfield);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

List class

Implementing List class


import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 private List list;

 public Sample()

 {

  display = Display.getDisplay(this);

  list = new List("hello", Choice.EXCLUSIVE);

 }

 
 public void startApp()

 {

  list.append("apple");

  list.append("mango");

  list.append("orange");

  list.append("jackfruit");

  display.setCurrent(list);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

Command class and Form class

mplementing command and Form Class


import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 private Command exit;

 private Form form;

 public Sample()

 {

  display = Display.getDisplay(this);

  exit = new Command("exit",Command.EXIT,1);

  form = new Form("hello");

 }

 
 public void startApp()

 {

  form.addCommand(exit);

  display.setCurrent(form);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

Display and TextBox class

Implementing Display and TextBox Class


import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 private TextBox textbox;

 public Sample()

 {

  display = Display.getDisplay(this);

  textbox = new TextBox("hello", " ", 256, TextField.ANY);

 }

 
 public void startApp()

 {

  display.setCurrent(textbox);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

Tuesday, July 12, 2011

Multimedia in J2ME

The mobile media API in J2ME provides a frmaework for embedded facilities in mobile devices that support java platform. The MMAPI comes under the specification of the Java technology for wireless industry specification. The MIDP 2.0 also comes with a subset of MMAPI specification that allow mobile devices to play multimedia. On the other hand MMAPI is provided as an optional package in Java ME. The MMAPI includes a high level interface so that mobile devices support audio and video playback. An important advantage of MMAPI is that applications developed using MMAPI are not protocol or device specific. This enables different application developers to implement these APIs in their mobile devices independent of the application format. Also, the MMAPI supports both CLDC and CDC configurations. The basic features of MMAPI are as listed below.
  • It provides support for a wide range of audio and video formats
  • It enables new features to be added to the existing specification without modifying the older version.
  • It provides a flexible and extensible framework.
  • The processing requiremeents of MMAPI is limited.
  • It requires very less memory.
  • It consumes only a limited amount of resources.


javax.microedition.media Package
The javax.microedition.media package provides multimedia audio support. This package also supports the MIDP 2.0 specification. This package includes the classes and interfaces that provide audio support. The following interfaces are includes in this package.
  • The Control interface
  • The Controllabe interface
  • The Player interface
  • The PlayerListener interface


The code for implementing the player listener interface is as shown below
Player myplayer = Manager.createPlayer("/filename.mp3");
myplayer.setLoopCount(10);
myplayer.start();


A simple j2me program to play an audio file is shown below

import javax.microedition.midlet.*;

import javax.microedition.media.*;

public class Audiosample extends MIDlet

{

 public void startApp()

 {

  try

  {

  Player myplayer = Manager.createPlayer(getClass()

  .getResourceAsStream("nature.wav"),"audio/x-wav");

  player.start();

  }

  catch(Exception e)

  {}

 public void pauseApp()

 {

 }

 public void destroyApp(boolean unconditional)

 {

 }

}

Messaging in J2ME

Messaging in J2ME

Messaging applications that are capable of sending and receiving messages to and from mobile devices can be easily developed with the help of J2ME. Thus J2ME provides the wireless messaging API to facilitate the development of wireless messaging applications. The wireless messaging API is an optional package availabe in J2ME which can be used for developing messaging services on mobile phones. The wireless messaging API specification defines APIs for sending and receiving all types of messages such as text, binary,CBS and multipart. Different types of interfaces are provided by WMA to create, send and receive the messages. WMA is also an optional API mentioned in JSR 120 and JSR 205 specifications. A wide range of devices support the Generic Connection Framework(GCF) defined in CLDC. The primary function of GCF is to provide classes and interfaces to connect the devices that take part in the messaging process. The javax.wireless.messaging provides implementation of all the functions required to develop a messaging application.


The following two packages are available in WMA.

  • javax.microedition.io.
  • javax.wireless.messaging

The javax.microedition.io Package
This package provides networking support, so that mobile devices can connect with each other in a networked environment. A highly sophisticated protocol has been defined to facilitate the exchange of data. The main objective of this package is to provide protocol or generic independent mobile devices. An important point to be noted is that GCF is contained in javax.microedition.io package and facilitates the connection procedure. This approach of providing the connectivity is known as generic as a common API is used for all the basic connection types. This can be achieved with the help of an interface hierarchy which is extensible and a URL. This URL can be used to identify the location and methods to access the resource. Also, the address portion of the URL can be used to identify the handset and the application. An example of client connection URL is shown below.
(MessageConnection)Connector.open ("sms://+999...);

The format of the URL can be represented as follows.
protocol://recipient:port

In the above URL, the protocol or scheme helps to identify how the connection is made and the various types of information that is transferred through the protocol. The reciepient can be either the receiver's phone number or e-mail address.


The javax.wireless.messaging Package
This package contains APIs that help the applications to send and receive wireless messages. It contains a base interface known as Message that represents the communicated message. It also has several sub-interfaces such as BinaryMessage, TextMessage andMultipartMessage that corresponds to binary, text and multipart messages respectivly. Additionally an interface known as MessageConnection interface which is a sub-interface of the GCF's connection interface is also defined. Another interface known as MessageListener interface is used for asynchronously listening the messages that is being received. Now there are different format of messages such as binary, text and multipart messages. Each of these message types are created in a manner that is different from each other.
A small example of creating a binary message is shown below.

byte[]  loadedmsg = null;

String destination = "123456";

String port = "1234";

String adress = "sms://" + destination + ":" + port;

MessageConnection mycon = null;

try

{

 mycon = (MessageConnection) Connector.open(adress);

 BinaryMessage mymessage = (BinaryMessage)

  mycon.newMessage(MessageConnection.BINARY_MESSAGE);

 mymessage.setPayloadData(loadmsg);

 mycon.close();

}

catch(Exception ex1)

{

}


Now the code for Sending a binary message is shown below.

byte[]  loadedmsg = null;

String destination = "123456";

String port = "1234";

String adress = "sms://" + destination + ":" + port;

MessageConnection mycon = null;

try

{

 mycon = (MessageConnection) Connector.open(adress);

 BinaryMessage mymessage = (BinaryMessage)

  mycon.newMessage(MessageConnection.BINARY_MESSAGE);

 mymessage.setPayloadData(loadmsg);

 mycon.send(mymessage);
 mycon.close();

}

catch(Exception ex1)

{

}


Finally the code for receiving a binary message is as shown below

byte[]  loaedmsg = null;

tring destination = "123456";

String port = "1234";

String adress = 'sms://" + destination + ":" + port;

MessageConnection mycon = null;

mycon = (MessageConnection) Connector.open(adress);

BinaryMessage mymessage = (BinaryMessage)mycon.receive();

mycon.close();

}

catch(Exception ex1)

{

}

J2ME Classes

J2ME Classes

  • Displayable class
  • Display class
  • Command class
  • Form class
  • List class
  • TestBox class
  • TextField class
  • Gauge class
  • Datefield class
  • Image class
  • ImageItem class
  • ChoiceGroup class
  • Canvas class
  • Gamecanvas class

Displayable class
A Displayable class is used with an object that can be placed or displayed on a screen. Commands, title or ticker in an MIDP application can be a Displayable object. the methods in displayable class are as follows.

void addCommand(Command cmd)
int getHeight()
Ticker getTicker()
int getWidth()

Display class
Diaplay class is used to manage the objects that can be displayed on the screen.The display.setCurrent() method is used to display a current object on the screen. A new display object can be created as follows.

Display display = Display.getDisplay(this);

Command class
The comand class is used to set command buttons on the display screen. By clicking on these command the applications will perform a pre-defined action. There are various types of command actions in the command class as follows
BACK
CANCEL
EXIT
HELP
OK
ITEM
SCREEN
STOP
These command types can be set as required. A new command class object can be created as follows
Commmand cmd = new Command(String label, int Commandtype, int priority);

Form class
Form class is used to create a user defined form in the Midlet. The form has several sub-classes which include gauge, textfield, datefield, customitem, stringitem, imageitem and choicegroup class. A new form object can be created as follows.
Form form = new Form(String label);

List class
The list class is used to create list of items that will allow users to select options from a given list of options. The list class works similar to the choicegroup class. A new list object can be created as follows.
List list = new List(String title, Choice.EXCLUSIVE|MULTIPLE);

TextBox class
The textbox class is used to create a text box in the MIDP application tha will allow the user to enter inputs. The syntax for creating a new TextBox object is as follows
TextBox textbox = new TextBox(String title, String text, int maxsize, int constraints);

TextField class
The textfiled class is used to create a new textfield in the MIDP application wherein the users can enter the inputs. The difference between textbox and textfield class is that textfield does not limit the amount of characters that can be entered in the textfield. A new textfield object can be created as follows.
TextField textfield = new TextField(String title, " ", 256, TextField.ANY);

Gauge class
The Gauge class is used to indicate a downloading bar or progress bar in an MIDP application. There are two types of gauges in J2ME viz; interactive and non-interactive. The interactive gauge continously shows the progress. A new gauge object can be created as follows.
Gauge bar = new Gauge(String title, boolean true|false, int maxpercentage, int minpercentage);

DateField class
The datefield class is used to display the current date and time in an MIDP application. A new datefield object can be created as follows.
DateField datefield = new DateField(String title, DateField.DATE|TIME|DATE_TIME);

Image class
The image class is used to create a new image that can be displayed in an MIDP application. The image class is used in conjunction with the imageitem class, so that the image can be appended in a form. A new image can be created as follows.
Image image = Image.createImage("/filename.png");

ImageItem class
The imageitem class is used to append an image that was created using the image class to a form. The syntax for creating a new imageitem is as follows
ImageItem imageitem = new ImageItem("image", image, ImageItem.LAYOUT_CENTER, "image");

ChoiceGroup class
The choicegroup class is used to create a list of choices in the MIDP application wherein the users can select multipe choice or a single choice. The syntax for creating a new choicegroup object is as follows.
ChoiceGroup choicegroup = new ChoiceGroup(String titile, Choice.EXCLUSIVE|MULTIPLE);

Canvas class
The canvas class is used to create graphical images and manipulate graphical objects in an MIDP application. The canvas class implements the abstract method public void paint(Graphics g). In addition to this, several other methods present in the canvas class are as follows.
protected void KeyPressed(int keycode)
protected void KeyReleased(int keycode)
protected void KeyRepeated(int keycode)
protected void PointerPressed(int x, int y)
protected void PointerReleased(int x, int y)
protected void PointerDragged(int x, int y)

GameCanvas class
The gamecanvas class is used to create game applications that can be executed on a mobile device. It has several methods that can be used for implementing a game application

J2ME program to display a text and take user-inputs.



import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class Sample extends MIDlet 

{

 private Display display;

 private TextBox textbox;

 public Sample()

 {

  display = Display.getDisplay(this);

  textbox = new TextBox("hello", " ", 256, TextField.ANY);

 }

 
 public void startApp()

 {

  display.setCurrent(textbox);

 }


 public void pauseApp{ }


 public void destroyApp(boolean unconditional)

 {

  notifyDestroyed();

 }

}

About J2ME

J2ME Concepts


  • Midlets
  • Midlet Configuration
  • Midlet profiles
  • Working with Midlets
  • Developing Applications
Midlet
A midlet is basically an MIDP application which can be installed or executed in any mobile device that supports java runtime environment. Midlets are quite easy to develop as compared to other windows mobile application. The current profile version being used by mobile vendors and developers is MIDP 2.0 which supports the CLDC 1.1 configuration. CLDC 1.1 is an updated version of the CLDC 1.0 configuration

Midlet Configuration
A Configuration defines the java runtime environment for a mobile device. A standard configuration has been defined so that an application developed using that configuration can run on all mobile devices. The two standard configurations are CLDC 1.0 and CLDC 1.1.

Midlet Profiles
A Midlet profile contains the necessary APIs and packages required for developing an application. A wide range of profiles have been included in J2ME which include Foundation profile, personal profile, personal basis profile and most importantly the Mobile information device profile(MIDP) which is used to develop application for mobile devices having limited configuration.

J2ME Tutorial

Learner's palace is a perfect place for you to learn about developing mobile applications. We will try our best to introduce you through all the concepts in the programming language used to develop mobile applications. J2ME is the most widely used programming language to develop mobile application. Applications developed using J2ME can be installed on any mobile device that supports Java platform. Our tutorials are perfectly designed for newbies who are in to the field of mobile programming. We have tried implementing each and every class in J2ME, so that visitors can get a broad view of its programming part. At the end, we have include a projects category wherein, you can download some mobile applications developed by us. We just hope that you are satisfied with our wide range of tutorials.