Friday, January 14, 2011

Mobile Application Development using JME (J2ME)

Summary: This introduces mobile application development using the Java Micro Edition (JME)







Introduction to Mobile Application Development using JME (J2ME)

Mobile phones have invaded every single aspect of our modern lives and have made us completely dependent on them. Traditionally a mobile phone was just a piece of hardware with an embedded crude operating system which would allow us to make/receive phone calls and send/receive text messages. Today with the advancement and affordability of technology, mobile phones and devices are capable of performing a multitude of tasks using software.
Almost all modern mobile devices are Java enabled which allows them to run software applications built using the Java platform. However as most mobile phones have limited processing and storage capabilities, these mobile applications have to be simple, light weight and very efficient. Knowing that mobile applications have to be simple in order to run on most mobile devices, we can question whether we ourselves could write our own applications (with limited Java programming skills) and install them on our mobile phones without paying money to download applications which don't really address our needs. This brief guide will help you create your first mobile application and will equip you with the initial knowledge of the tools and techniques you would need to build much more robust mobile applications as you gain more experience.
Java Micro Edition (JME or J2ME)
JME, or J2ME as it is sometimes called, is the Java framework which allows programs to run on mobile devices. As this article is more hands on and is written to introduce you to actually writing JME programs, I will not discuss the technical theory behind how it works. Once you have written your first application, you can read more about JME athttp://java.sun.com/javame/technology/index.jsp .
Make sure you pay special attention to two configurations
the profile
You should also read about the two main Virtual Machines
What you need to start
To start writing your first mobile application you will need the following installed on your computer. These tools are provided free by Sun Micro Systems (presently part of Oracle) and can be downloaded from their website.
  1. Java Development Kit (JDK) 6 or higher (Download from: http://java.sun.com/javase/downloads/widget/jdk6.jsp)
  2. Java ME SDK 3.0 or higher (Download from: http://java.sun.com/javame/downloads/sdk30.jsp)
You need to install the JDK before you install the JME SDK. Follow the step-by-step instructions to install the JDK and JME SDK using the default settings. Once you have installed both the JDK and JME SDK you are ready to write your first application.
The IDE
Open the Java ME Platform SDK (you should have a shortcut on your desktop). This contains an IDE which will allow you to write, run and debug your applications before you install them onto your Java enabled mobile device. When you initially start up the IDE you will see the following screen which provides some sample application projects. You can run them later on to get an understanding of the different programming concepts introduced in each one.
Figure 1
Figure 1 (graphics1.png)
Writing your first mobile application
Click on “Create New Project”.
Figure 2
Figure 2 (graphics2.png)
Select MIDP application as the project type, which allows you to create a standalone mobile application. Click “Next” to continue.
Name your project (e.g. MyFirstApp) and choose a location to create the project folder. The “Set as Main Project” check box will tell the IDE to run this MIDlet when the application is launched. A MIDP program is called a 'MIDlet'. Uncheck “Create Hello MIDlet”. The Hello MIDlet is a 'Hello World' program automatically created for you. Since displaying 'Hello World'' using a program doesn't really serve a purpose, we will try to create a more interactive application as your first one.
Click 'Next' to continue.
Figure 3
Figure 3 (graphics3.png)
Now you can select the different versions of the CLDC configurations and MIDP profiles. As you become more experienced in MIDP application development, you can write applications for specific configurations and profile versions. For now leave the default settings as they are.
Using the 'Device' drop down you can select various mobile phone emulators for testing purposes. As this is your first program let's leave the default one.
Click 'Finish' to start programming.
Figure 4
Figure 4 (graphics4.png)
In the 'Projects' window you can now see your project. Expand the 'Source Packages' folder and right click on the 'Default Package'. Packages are a key feature of Java and Object Oriented Programming (OOP). You can read more about packages at http://java.sun.com/docs/books/tutorial/java/package/index.html .
Right-click on ‘Default Package’ and select ‘New’ > ‘MIDlet…’ .
Figure 5
Figure 5 (graphics5.png)
Name your MIDlet as ‘Guess The Animal’ and click ‘Finish’
Figure 6
Figure 6 (graphics6.png)
Now the IDE will add some code by default to make your job easier.
Figure 7
Figure 7 (graphics7.png)
Now let’s see what these pieces of code do line by line.
Line 1-4 / 8-10: The text is grayed out. This means that they are comments. You can add any comment you want into a program to help you understand the coding logic you have written.
A comment is made using
if the comment is only one line: // comment
if the comment is multiple lines: /* comment line 1
comment line 2 */
Line 6: Imports all the classes in the javax.microedition.midlet package into your program. Please refer to http://java.sun.com/docs/books/tutorial/java/package/index.html for more details.
Line 11: Creates the ‘GuessTheAnimal’ class extending the MIDlet class. Please read http://java.sun.com/docs/books/tutorial/java/IandI/subclasses.html for more details on inheritance.
Line 12-13startApp() method is executed automatically when the application starts.
Line 15-16pauseApp() method is executed automatically when the application state is paused.
Line 18-19destroyApp() method is executed when the application is closed.
You can learn more about methods at http://java.sun.com/new2java/divelog/part1/page6.jsp .
Now let’s add some code and some code and get this working.
Delete all the code in the IDE window and copy and paste the following code block into the empty window.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* @author yourname
*/
public class GuessTheAnimal extends MIDlet implements CommandListener {
private Display display; // Reference to a display
private Form fmMain; // A Form
private TextField question; // A text field with the question
private ChoiceGroup animals; // A list of animals to select from
private Alert answer; // An alert to notify whether answer is correct
private Command cmGuess; // The Guess Command
private Command cmExit; // The Exit Command
// constructor
public GuessTheAnimal(){
display = Display.getDisplay(this); // instantiate the display for this MIDlet
fmMain = new Form("Guess the Animal"); // new form
question = new TextField("Animal's Description","It has a stripes on its body, " +
"it preys on other animals, it has long teeth, " +
"it runs fast",TextField.LAYOUT_EXPAND, TextField.UNEDITABLE );// Set the text in the text box
fmMain.append(question); // add the question to the form
animals = new ChoiceGroup("Animals", ChoiceGroup.EXCLUSIVE);
animals.append("Tiger", null);
animals.append("Snake", null);
animals.append("Zebra", null);
animals.append("Hipo",null);
fmMain.append(animals);
cmGuess = new Command ("Guess", Command.ITEM, 1); // new command
fmMain.addCommand(cmGuess); // add the Guess command to the form
cmExit = new Command ("Exit", Command.EXIT, 1); // new command
fmMain.addCommand(cmExit); // add the Exit command to the form
fmMain.setCommandListener(this); // Listen for events
}
public void startApp() {
display.setCurrent(fmMain); // set the current display to fmMain
}
public void pauseApp() {
//You can add code later on
}
public void destroyApp(boolean unconditional) {
/*You can add code later on.
Usually used to clean up or systematically close an application */
}
private void checkAnswer(){
//Check whether the answer is correct
if (animals.isSelected(0)){
answer = new Alert("Answer","Congratulations! You have guessed correctly",null,null);
}
else {
answer = new Alert("Answer","Sorry! You have guessed wrong",null,null);
}
answer.setTimeout(Alert.FOREVER);
display.setCurrent(answer, fmMain);
}
//Listens to commands issued by users
public void commandAction(Command c, Displayable s){
// check to see if "Guess" button was selected
if (c == cmGuess){
checkAnswer();
}
// check to see if "Exit" button was selected
if (c == cmExit){
destroyApp(false);
notifyDestroyed();
}
}
}
Now your IDE window will look like the following.
Figure 8
Figure 8 (graphics8.png)
To compile and your program click on the run
Figure 9
Figure 9 (graphics9.png)
button.
Figure 10
Figure 10 (graphics10.png)
Now you will see the emulator running your application.
Figure 11
Figure 11 (graphics11.png)
Try to guess the animal and see what happens.
Congratulation! You just built and ran your first mobile application.
Now let’s look at the code.
Figure 12
Figure 12 (graphics12.png)
Line 6-7: Imports the midlet and lcdui packages to be used in the program. You can have a look at the features they have at
Figure 13
Figure 13 (graphics13.png)
Line 13: Declares the GuessTheAnimal class extending the MIDlet class and implementing ‘CommandListener’ interface.
You can read more about implementing interfaces at http://java.sun.com/docs/books/tutorial/java/IandI/createinterface.html.
Figure 14
Figure 14 (graphics14.png)
Line 14: Declares a ‘Display’. This refers to the screen of your mobile phone/device. More details at http://java.sun.com/javame/reference/apis/jsr037/javax/microedition/lcdui/Display.html
Line 15: Declares a ‘Form’. This is a container which will hold other components. More details at http://java.sun.com/javame/reference/apis/jsr037/javax/microedition/lcdui/Form.html
Line 16-20: Declares the components of the program. You can read about each component at http://java.sun.com/javame/reference/apis/jsr037/javax/microedition/lcdui/package-summary.html.
Figure 15
Figure 15 (graphics15.png)
Line 23: Declares the constructor. This is automatically called when the program is run. We use this method to initialize all the components of the program.
Line 24: Sets the display to the current screen.
Line 27-29: Initializes the ‘TextField’ which holds the question. More details at http://java.sun.com/javame/reference/apis/jsr037/javax/microedition/lcdui/TextField.html .
TextField.LAYOUT_EXPAND: Stretches the TextField to the width of the screen.
TextField.UNEDITABLE: Makes the TextField read-only.
Line 30: Adds the TextField to the Form.
Line 32-36: Initializes a ChoiceGroup (radio buttons) and adds the animal values to it. More details athttp://java.sun.com/javame/reference/apis/jsr037/javax/microedition/lcdui/ChoiceGroup.html
Line 39: Initializes a ‘Command’ called “Guess”. More details at http://java.sun.com/javame/reference/apis/jsr037/javax/microedition/lcdui/Command.html
Line 40: Adds the ‘Command’ to the form. Now you can use the top left and right command keys of your phone to execute tasks.
Line 45: Sets the ‘CommandListener’ to the current form. Now the application can detect key presses.
Figure 16
Figure 16 (graphics16.png)
Line 49: When the application starts up, the focus is given to the fmMain form on the screen.
Figure 17
Figure 17 (graphics17.png)
Line 75: Declares the ‘commandAction’ method. This is executed when a command button is pressed on your phone. More details athttp://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/CommandListener.html#commandAction%28javax.microedition.lcdui.Command,%20javax.microedition.lcdui.Displayable%29
Line 77: Checks whether the pressed command is ‘cmGuess’. If so it calls the method ‘checkAnswer()’.
Line 83: Destroys the application.
Line 84: Notifies that the application has been closed properly. More details athttp://java.sun.com/javame/reference/apis/jsr037/javax/microedition/midlet/MIDlet.html#destroyApp%28boolean%29
Figure 18
Figure 18 (graphics18.png)
Line 61: Declares a user defined method called ‘checkAnswer’.
Line 63: Checks whether the first element “Tiger” is selected in the ChoiceGroup.
Line 64: Initiates an ‘Alert’ to be displayed. More details at http://java.sun.com/javame/reference/apis/jsr037/javax/microedition/lcdui/Alert.html
Line 69: Tells the application that the alert has to be displayed on the screen until the user says ‘OK’. This can be set to a specific time frame as well.
Line 70: Sets the focus of the screen to the ‘Alert’.
Now you have a good understanding of how these components/methods work within a MIDP application. This tutorial covered most of the features of a MIDP application using forms. You can develop many interactive applications using only the techniques introduced in this tutorial.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

java

Popular java Topics