Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
10.7%
Mobile Programming with J2ME


by Rohitha Hemachandra


           In this article series we hope to describe how to program mobile telephones, pagers, PDAs, and other small devices using Java technology. It is about the Mobile Information Device Profile (MIDP), which is part of the Java 2 Platform, Micro Edition (J2ME). It is concise and complete, describing all of MIDP as well as moving into several exciting advanced concepts such as 3D graphics and cryptography. This article series covers MIDP 2.0, and has been updated to track the Java Technology for the Wireless Industry (JTWI 1.0) de facto standard. Every topic has been revised and meticulously updated.

 You’re probably reading this because you’re excited about building wireless applications with Java. This article is aimed at people who already have experience programming in Java. At a minimum, you should understand the Java programming language and the fundamentals of object-oriented programming. If you are unfamiliar with Java, we suggest you read an introductory book or take a course.

 The following topics will be covered during these lessons series.

Creating a User Interface

Lists and Forms

Custom Items

Persistent Storage

Connecting to the World, applications can send and receive data over the Internet.

Wireless Messaging

Bluetooth and OBEX

          Programming a Custom User Interface

            The Game API

            3D Graphics

            Sound, Music, and Video: MMAPI

 By keeping in touch with these lessons you will be able to understand and create your own mobile applications and mobile games easily.

J2ME

J2ME isn’t a specific piece of software or specification. All it means is Java for small devices. Small devices range in size from pagers, mobile phones, and personal digital assistants (PDAs) all the way up to things like set-top boxes that are just shy of being desktop PCs. J2ME is divided into configurations, profiles, and optional APIs, which provide specific information about APIs and different families of devices. A configuration is designed for a specific kind of device based on memory constraints and processor power. It specifies a Java Virtual Machine (JVM) that can be easily ported to devices supporting the configuration. It also specifies a strict subset of the Java 2 Platform, Standard Edition (J2SE) APIs that will be used on the platform, as well as additional APIs that may be necessary. Device manufacturers are responsible for porting a specific configuration to their devices. Profiles are more specific than configurations. A profile is based on a configuration and provides additional APIs, such as user interface, persistent storage, and whatever else is necessary to develop running applications for the device. Optional APIs define specific additional functionality that may be included in a particular configuration (or profile). The whole caboodle—configuration, profile, and optional APIs— that is implemented on a device is called a stack. For example, a possible future device stack might be CLDC/MIDP + Mobile Media API. See the section “Platform Standardization” later in this lesson for information on JSR 185, which defines a standard J2ME stack. Currently, there are a handful of configurations and profiles; the most relevant ones for J2ME developers are illustrated in Figure 1-1.



Building a simple mobile application

MIDP applications are piquantly called MIDlets, a continuation of the naming theme begun by applets and servlets. Writing MIDlets is relatively easy for a moderately experienced Java programmer. After all, the programming language is still Java. Furthermore, many of the fundamental APIs from java.lang and java.io are basically the same in the MIDP as they are in J2SE. The actual development process, however, is a little more complicated for MIDlets than it is for J2SE applications. Beyond a basic compile-and-run cycle, MIDlets require some additional tweaking and packaging. The complete build cycle looks like this: Edit Source Code. Compile. Preverify. Package . Test or Deploy. To show how things work, and to give you a taste of MIDlet development, this lesson is dedicated to building and running a simple MIDlet. In later, we’ll delve into the details of the MIDP APIs. In this lesson, you’ll get a feel for the big picture of MIDlet development. Tooling Up MIDlets are developed on regular desktop computers, although the MIDlet itself is designed to run on a small device. To develop MIDlets, you’ll need some kind of development kit, either from Sun or another vendor. Remember, MIDP is only a specification; vendors are free to develop their own implementations. The world is full of MIDlet development tools if you know where to look. Furthermore, many of these tools are freely available. The bare bones set of tools is Sun’s MIDP reference implementation. This includes the preverify tool (more on later), a MIDP device emulator, source code, and documentation. You can download the MIDP reference implementation by following the links from http://java.sun.com/products/midp/.

However, we don’t recommend using the reference implementation unless you really enjoy being in the middle of the gritty details of building and packaging MIDlets. (You should also investigate the reference implementation if you are interested in porting the MIDP runtime to a new device or platform.) A much better tool for beginners is Sun’s J2ME Wireless Toolkit, available from http://java.sun.com/products/j2mewtoolkit/. The J2ME Wireless Toolkit (or J2MEWTK, as it’s affectionately known) includes a GUI tool that automates some of the tedious details of building and packaging MIDlets, providing a simple path from source code to running MIDlets. At the same time, the J2ME Wireless Toolkit is a relatively lightweight solution, almost a miniature IDE, not something that will choke your machine. Larger IDEs are available in abundance, from device manufacturers, wireless carriers, IDE vendors, and open source communities. You can use whatever development kit you wish. We suggest you start with the J2ME Wireless Toolkit, which is easy to use and authoritative. We’ll be using the J2ME Wireless Toolkit (version 2.2, or WTK 2.2). Other development environments generally use the J2ME Wireless Toolkit as a plug-in anyhow, so your experiences are likely to be similar no matter what tool you use.

 

Creating Source Code

Writing Java source code is the same as it always was: use your favorite text editor to create a source file with a .java extension. The example we’ll build and run is HelloMIDlet, To get you started with MIDlet development, let's write a simple MIDlet. Once you've chosen a text editor, type, cut and paste the following code:

Source Code

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;

 public class HelloMIDlet extends MIDlet implements CommandListener {

  private Form mMainForm;

 

   public HelloMIDlet() {

    mMainForm = new Form("HelloMIDlet");

    mMainForm.append(new StringItem(null, "Hello, MIDP!"));

    mMainForm.addCommand(new Command("Exit", Command.EXIT, 0));

    mMainForm.setCommandListener(this);

   }


   public void startApp() {

    Display.getDisplay(this).setCurrent(mMainForm);

   }

 

  public void pauseApp() {}

  public void destroyApp(boolean unconditional) {}

  public void commandAction(Command c, Displayable s) {

   notifyDestroyed();

  }

}

Compiling a MIDlet

Writing MIDlets is an example of cross-compiling, where you compile code on one platform and run it on another. In this case, you’ll be compiling a MIDlet using J2SE on your desktop computer. The MIDlet itself will run on a mobile phone, pager, or other mobile information device that supports MIDP. The J2ME Wireless Toolkit takes care of the details as long as you put the source code in the right directory.

1. Start the toolkit, called KToolbar.

2. Choose New Project from the toolbar to create a new project.


3. When the J2ME Wireless Toolkit asks you for the name of the project and the MIDlet

    class name, use “HelloMIDlet” for class name and use “HelloSuite” for project name.

4. Click the Create Project button, and then the OK button to dismiss the project settings  window.

          

Figure 2-1. Creating a new project with the J2ME Wireless Toolkit

The J2ME Wireless Toolkit represents projects as subdirectories of its apps directory. The following shows the contents of the HelloMIDlet directory after the new project is created:

<J2ME Wireless Toolkit directory>

apps

                HellowSuite

bin

lib

res

src

Save the source code as HelloMIDlet.java in the project’s src directory. You can simply click the Build button in the J2ME Wireless Toolkit toolbar to compile the open project. Behind the scenes, the J2ME Wireless Toolkit uses J2SE’s compiler. Normally, when you’re compiling J2SE source code, the CLASSPATH environment variable points to all the classes that your source code needs to know about. When you use javac to compile a file, there are some implied APIs that get included, like the classes in java.lang. With MIDlets, however, the situation is a little more complicated. Say that you use the java.lang.System class in your MIDlet. How do you (or how does the J2ME Wireless Toolkit) let the compiler know that you want to use the MIDP version of this class, not the J2SE version? The answer is a command line option, -bootclasspath. This option lets you point to a classpath that describes the fundamental APIs against which you will be compiling your source code. In this case, this option should be used to specify the classes directory in the MIDP reference implementation installation. If you install the MIDP reference implementation, the command line looks like this:

javac -bootclasspath \midp\classes HelloMIDlet.java You will need to adjust the path to classes if you installed the MIDP reference implementation in a different location.

 Preverifying Class Files

Now comes an entirely new step in building your program, preverifying. Because the memory on small devices is so scarce, MIDP (actually, CLDC) specifies that bytecode verification besplit into two pieces. Somewhere off the device, a preverify step is performed. The device itself is only required to do a lightweight second verification step before loading classes.

If you are using the J2ME Wireless Toolkit, you don’t have to worry about preverifying class files, and you may not even notice that it’s happening when you click the Build button. As you may recall, bytecode verification is one of the foundation stones of Java’s runtime security model. Before a classloader dynamically loads a class, the bytecode verifier checks the class file to make sure it behaves well and won’t do nasty things to the JVM. Unfortunately, the code that implements the bytecode verifier is bulky, too large to fit on a small device like a mobile phone. The CLDC dictates a two-step bytecode verification:

 1. Off the device, class files are preverified. Certain checks are performed, and the class file is massaged into a format that the lightweight second-step verifier can easily handle. This format is really just a regular class file, with some additional data attached by the preverifier.

 2. On the device, the second step of verification is performed as classes are loaded. If a class file has not been preverified, it is rejected. The MIDP reference implementation and the J2ME Wireless Toolkit contain a tool called preverify that performs the first step. The preverify tools takes, as input, a class file. It produces a preverified class file. You need to specify a classpath so that the tool can find the class you want to preverify as well as any referenced classes. Finally, you can specify an output directory using the -d option. To overwrite an existing class file with a preverified version, you could do something like this:       

preverify -classpath .;\ midp\ classes -d . HelloMIDlet

In this example, the -d option tells preverify to write the preverified class file to the current directory. Don’t forget about inner classes, which must also be preverified. Note Splitting bytecode verification into two pieces like this has important security ramifications. Devices should only download code from trusted sources, using a secure method because some bytecode verification is performed off the device. (See Chapter 3 for more information on MIDlet suite security.) An attacker could supply malicious code that appeared to be preverified, even if it violated the rules of the full J2SE bytecode verifier. To the MIDP second-step verifier, the code would look okay and it would be loaded and run. Sun’s J2ME Wireless Toolkit Emulators The J2ME Wireless Toolkit includes several different emulators that you can use to test your applications. When you click the Run button in the J2ME Wireless Toolkit, your application is launched in the currently selected emulator. The Wireless Toolkit Devices The J2ME Wireless Toolkit 2.2 contains four main device emulators:


               

• DefaultColorPhone is a device with a 240×320-pixel color screen. This is the device     shown later in Figure 2-2 and is used for most of the screen shots in the remainder of this               book.

• DefaultGrayPhone has a 108×208 pixel grayscale screen.

• MediaControlSkin is similar to the default phone emulator and has a color screen of

108×208 pixels, but its buttons are labeled with controls like a music player: a square

for stop, a triangle for play, volume control buttons, etc.

• QwertyDevice is a smartphone with a 636×235-color screen and a miniature QWERTY

keyboard.


Running MIDlets

Sun’s MIDP reference implementation includes an emulator named midp. It emulates an imaginary MID, a mobile telephone with some standard keys and a 182×210-pixel screen. The J2ME Wireless Toolkit includes a similar emulator, as well as several others. Once you’ve got a preverified class file, you can use the midp emulator to run it. The emulator is an application that runs under J2SE and acts just like a MIDP device. It shows itself on your screen as a representative device, a generic mobile phone. You can run your MIDlet by typing the following at the command line, assuming you added \midp\bin to your PATH: midp HelloMIDlet If you’re using the J2ME Wireless Toolkit, you can simply choose an emulator from the Device combo box and click the Run button to fire up your application. If all goes well, you’ll see something like the window shown in Figure 2-2 in the next section. Congratulations! You’ve just built and run your first MIDlet.

                             

   Share/Save
No votes yet

retet

this is very good

Good Article

this is great for me & i think its very helpful for newbie to J2ME.its cool.thnx.....

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options