Developing J2ME applications with EclipseME Skill Level: Introductory

Michael Juntao Yuan Writer, Analyst, and Developer

30 Nov 2004

This tutorial demonstrates how to develop J2ME applications using the IDE and the open source EclipseME plug-in.

Section 1. Before you start

About this tutorial

This tutorial demonstrates how to develop 2 Platform, Micro Edition (J2ME) applications using the Eclipse IDE, the open source EclipseME plug-in, and the Sun J2ME Wireless Toolkit.

This tutorial is written for J2ME developers who are interested in using the Eclipse IDE to increase productivity. It also addresses Java Eclipse developers who want to produce J2ME mobile applications in their favorite IDE. Having a basic knowledge of Eclipse and J2ME helps you complete the tasks described in this tutorial.

Prerequisites

To complete the tasks and run the sample code in this tutorial, you must have the Eclipse IDE Version 2.1.x or 3.x installed. You also need to download and install the free J2ME Wireless Toolkit from (http://java.sun.com/products/j2mewtoolkit/).

Section 2. Introduction

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 41 developerWorks® ibm.com/developerWorks

What is J2ME?

Java 2 Platform, Micro Edition (J2ME) is the Java platform that runs on small mobile devices. It supports the standard Java programming language and contains a subset of APIs from the Java 2 Platform, Standard Edition (J2SE) with the addition of device-specific APIs. The Mobile Information Device Profile (MIDP) is a flavor of J2ME that runs on mobile phones. Available on more than 250 million handsets, the MIDP is the most pervasive available today. In this tutorial, you focus on MIDP application development. For more information about J2ME and MIDP, see the J2ME 101 series of tutorials published by developerWorks (see Resources).

The Sun J2ME Wireless Toolkit

The Sun J2ME Wireless Toolkit (WTK) is the reference implementation of J2ME/MIDP and related optional packages. It provides the bytecode preverification tool, implementation of API class libraries, and a device emulator. The emulator does not correspond to any real physical device. Instead, it supports cutting-edge MIDP optional package APIs that are not yet implemented on physical devices. It also has fewer resource constraints than real devices (memory and CPU speed limits, for example). The WTK emulator is a reference to how the MIDP (JVM) and API library should behave according to the specification. Developers use the WTK to develop generic prototypes or to experiment with new APIs before devices become available. The WTK is one of the most popular development and learning tools for J2ME developers. The WTK Version 2.2 supports the following MIDP APIs:

• The Java Technology for the Wireless Industry (JTWI) Roadmap 1 specification (JSR 185) • Wireless Messaging API (WMA) Version 2.0 (JSR 205) • Mobile Media API (MMAPI) Version 1.1 (JSR 135) • PDA Optional Packages (JSR 75) • Java APIs for Bluetooth (JSR 82) • Mobile 3D Graphics (JSR 184) • J2ME Web Services API (JSR 172)

Eclipse and J2ME

Although the WTK provides a powerful set of J2ME development tools, it has only limited support for the integrated development experience. For developers who are used to the convenience of Integrated Development Environments (IDE), the WTK lacks key productivity features, such as team collaboration, context-sensitive code

Developing J2ME applications with EclipseME Page 2 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

editors, refactoring, unit testing, debugging, and project management. Leading Java IDEs, such as Borland JBuilder and Sun Java Studio, try to attract J2ME developers by supporting integration with the WTK.

However, even as the very popular open source IDE, Eclipse does not integrate with the WTK out of the box. This has been a source of frustration for both J2ME developers who want to leverage the powerful Eclipse IDE and Eclipse developers who want to get into device development. Fortunately, the Eclipse IDE is designed to be extendable. The EclipseME is an open source plug-in that enables the integration between Eclipse and the WTK.

Section 3. Installation and configuration

Install the EclipseME

You can download EclipseME (currently at Version 0.5.0) from its project Web site (http://eclipseme.sourceforge.net/). The downloadable package is a zip file. To install it, just unzip the file into the Eclipse installation directory. It adds several files to the existing features and plug-in directories in the Eclipse root directory.

Configure the project structure

Start the Eclipse IDE, and open the preferences dialog box by selecting Window > Preferences. The J2ME tab contains the configuration for the project directory structure. In the initial setup, put preverified class files in the verified directory, resource files (for example, image files) in the res directory, and ready-to-deploy Java Archive (JAR) and Java Application Descriptor (JAD) files in the deployed directory.

Figure 1. Project structure

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 41 developerWorks® ibm.com/developerWorks

Configure the WTK

Navigate to the Platform Components tab, and right click Wireless Toolkit > Add Wireless Toolkit to add the WTK.

Figure 2. Add the WTK

Developing J2ME applications with EclipseME Page 4 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Select the path where the WTK is installed on your computer.

Figure 3. Select the WTK path

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 41 developerWorks® ibm.com/developerWorks

After the WTK is integrated, the available J2ME configurations, profiles, and libraries are shown in the window.

Figure 4. WTK integration

Developing J2ME applications with EclipseME Page 6 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Note that SDKs from device vendors, such as Nokia and Sony Ericsson, can also be added here. Additionally, you can add a custom platform profile by combining MIDP standard libraries with custom APIs stored in third-party JAR files. This way, it's easy to add any device-proprietary APIs in the development environment.

Configure debug options

To enable MIDlet debugging, select the Debug tab and deselect the suspend options. You should also increase the timeout to 20000 milliseconds.

Figure 5. Configure debug

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 41 developerWorks® ibm.com/developerWorks

Configure the obfuscator

The EclipseME uses Proguard to obfuscate MIDlet JAR files. Obfuscation reduces the size of the byte code and protects the intellectual property of the MIDlet. To use this feature, you must select the Proguard installation directory in the J2ME > Obfuscation tab. You can also configure which class names are to be preserved in the obfuscation process. The name of the MIDlet class must be preserved to allow the device Java Runtime Environment (JRE) to locate the entry point of execution.

Figure 6. Configure Proguard

Developing J2ME applications with EclipseME Page 8 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Now, you have installed and configured the EclipseME tools. Let's go through the entire process of building, testing, and packaging an MIDP application using those tools.

Section 4. Set up the project

Start a new project

To start a new project, select New > Project. Choose the J2ME > J2ME Midlet Suite project type.

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 41 developerWorks® ibm.com/developerWorks

Figure 7. Project type

Specify a name and a root directory for the project.

Figure 8. Project name

Developing J2ME applications with EclipseME Page 10 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Then, choose a platform to develop against, if multiple WTKs and system libraries are available. The WTK provides MIDP 1.0 and MIDP 2.0 profiles.

Figure 9. Choose a platform

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 41 developerWorks® ibm.com/developerWorks

The project structure and third-party library

The source code folder is the project's root folder. According to the project structure configuration, the deployed and verified folders contain build results and, therefore, are excluded from the build path.

Figure 10. Paths

Developing J2ME applications with EclipseME Page 12 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

By default, the project's classpath includes the J2ME API libraries in the WTK. You can add any external libraries into the classpath. However, if you add external JAR libraries to the project that are not available on the physical device, you will have to package them into the distribution JAR file manually. Otherwise, the MIDlet throws a Class not found exception when you deploy it on the device.

The Package Explorer

Now you have finished the project setup. The project name is displayed in the Package Explorer. Notice that a JAD file is automatically generated for the project; you will need it later in this tutorial.

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 41 developerWorks® ibm.com/developerWorks

Figure 11. Package Explorer

Section 5. Working with the source code

Create a new MIDlet

The EclipseME provides a wizard to create a new MIDlet class.

Figure 12. New MIDlet wizard

Developing J2ME applications with EclipseME Page 14 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

It automatically inherits from the javax.microedition.midlet.MIDlet class. In this example, the MIDlet implements the CommandListener interface to handle user input events.

Figure 13. New MIDlet

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 41 developerWorks® ibm.com/developerWorks

The skeleton Java source code file generated from the wizard is as follows in Figure 14.

Figure 14. Generated source code

Developing J2ME applications with EclipseME Page 16 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

The TutorialMidlet class

The TutorialMidlet is the MIDlet class that provides the entry of execution for the application. The Java runtime first instantiates this class and then calls its startApp() method to start the midlet. The destroyApp() method is called when the user terminates the application.

The TutorialMidlet class controls and displays all the UI screens in the application. All the user-generated soft key events (the user presses a soft key, for example) are handled by the TutorialMidlet class since it implements the CommandListener interface and attaches itself as the command listener for all screen objects. The UI event callback method is as follows: commandAction().

package tutorial; import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class TutorialMidlet extends MIDlet

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 41 developerWorks® ibm.com/developerWorks

implements CommandListener { Display display; Command greetCommand; Command exitCommand; Command clearCommand; Command backCommand; WelcomeScreen welcomeScreen; HelloScreen helloScreen; // instantiate the internal variables public TutorialMidlet () { display = Display.getDisplay(this); greetCommand = new Command ("Greet", Command.OK, 0); exitCommand = new Command ("Exit", Command.EXIT, 0); clearCommand = new Command ("Clear", Command.CANCEL, 1); backCommand = new Command ("Back", Command.SCREEN, 1); welcomeScreen = new WelcomeScreen (); welcomeScreen.addCommand (greetCommand); welcomeScreen.addCommand (clearCommand); welcomeScreen.setCommandListener (this); helloScreen = new HelloScreen (); helloScreen.addCommand (exitCommand); helloScreen.addCommand (backCommand); helloScreen.setCommandListener (this); } // Called when the MIDlet is started by the AMS protected void startApp () { display.setCurrent (welcomeScreen); } protected void pauseApp () { // Do nothing } protected void destroyApp (boolean unconditional) { notifyDestroyed (); } public void commandAction (Command c, Displayable d) { if (c == greetCommand) { String name = welcomeScreen.getName (); helloScreen.setName(name); display.setCurrent (helloScreen); } else if (c == clearCommand) { welcomeScreen.setName(""); display.setCurrent(welcomeScreen); } else if (c == backCommand) { display.setCurrent (welcomeScreen); } else if (c == exitCommand) { destroyApp (true); } } }

Realtime checking for errors

The TutorialMidlet class makes use of WelcomeScreen and HelloScreen classes, which you have yet to type in. The advanced Java editor in Eclipse alerts

Developing J2ME applications with EclipseME Page 18 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

you to this inconsistency by flagging the relevant parts of the code with red bars. If you place the mouse over the red line, the editor pops up with an explanation box informing you why it thinks it detects an error. Realtime syntax checking allows developers to take advantage of the consistency checking capabilities of the Java compiler without actually waiting for the compiling to complete.

Figure 15. Real-time error checking

If the "Build automatically" option in Eclipse's "Project" menu is selected, Eclipse tries to continuously build the project in the background whenever the project is updated. In this case, the Package Explorer also shows the compiling errors detected in the building process.

s Figure 16. Automatic build errors

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 41 developerWorks® ibm.com/developerWorks

The WelcomeScreen class

The WelcomeScreen extends the Form class to represent a screen that contains several high-level MIDP UI components. You can use Eclipse's default "New Class" wizard to add it to the project.

Figure 17. Create new class

Developing J2ME applications with EclipseME Page 20 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

As you have seen, the soft key commands and event handlers of the WelcomeScreen are added in the TutorialMidlet class. The data in the nameField UI component can be accessed from outside this class using Java Beans style getter and setter methods. The image used on the form is from an external PNG image file, welcome.png. The file must reside in the midlet's runtime classpath in order to be accessible.

package tutorial; import javax.microedition.lcdui.*; public class WelcomeScreen extends Form {

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 41 developerWorks® ibm.com/developerWorks

private TextField nameField; public WelcomeScreen () { super ("Welcome"); Image img; // Construct the image from the media file try { img = Image.createImage("/welcome.png"); } catch (Exception e) { e.printStackTrace (); img = null; } ImageItem imageItem = new ImageItem ("", img, ImageItem.LAYOUT_CENTER, "Welcome"); nameField = new TextField ("Please enter your name", "", 10, TextField.ANY); append (imageItem); append (nameField); } public void setName (String n) { nameField.setString (n); } public String getName () { return nameField.getString (); } }

The HelloScreen class

The HelloScreen extends the Canvas class to represent a screen that needs to be rendered by the application itself. The paint() method redraws the entire screen, and it is called by the system whenever the screen needs updating. Again, the soft key commands and event handlers of the HelloScreen are added in the TutorialMidlet class. The name string rendered on this screen is set by the setName() method before the screen is displayed. The image file hello.png must also reside in the midlet's runtime classpath.

package tutorial; import javax.microedition.lcdui.*; public class HelloScreen extends Canvas { private int width, height; private String name; private Image img; public HelloScreen () { width = getWidth (); height = getHeight (); name = "unknown"; // Construct the image from the media file try { img = Image.createImage("/hello.png"); } catch (Exception e) { e.printStackTrace ();

Developing J2ME applications with EclipseME Page 22 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

img = null; } } public void setName (String n) { name = n; } // Paint the screen based on the name protected void paint (Graphics g) { g.setColor(0xffffff); g.fillRect(0, 0, width, height); g.setColor(0x000000); g.drawImage (img, width / 2, height / 4, Graphics.VCENTER | Graphics.HCENTER); g.setFont(Font.getFont( Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE)); g.drawString (name, width / 2, height * 3/4, Graphics.BASELINE | Graphics.HCENTER); } }

No more errors

Now, with all the source code typed in, Eclipse shows no errors or inconsistencies anymore. You are ready to run the midlet!

Figure 18. No more errors

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 41 developerWorks® ibm.com/developerWorks

Section 6. Run the midlet

Copy the resource files

The WelcomeScreen and HelloScreen classes make use of two external image files. The MIDlet runner and packager need to know whether to find those files in order to make them accessible to the MIDlet. Recall that you configured the "res" directory to be the resource directory. So, add a "res" directory under the project root, and copy the two image files into it.

Figure 19. Copy the resource files

Developing J2ME applications with EclipseME Page 24 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Run the midlet

To run a midlet in the emulator, bring up the "Run" dialog from the "Run | Run ..." menu. Choose the "Wireless Toolkit Emulator" tab, and click the "New" button to define a new run profile. You can specify the class name of the MIDlet to run in the profile. Next, click the "Run" button.

Figure 20. Run the midlet

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 41 developerWorks® ibm.com/developerWorks

Emulator in action

The WTK emulator is started, and you can test the MIDlet.

Figure 21. Emulator

Developing J2ME applications with EclipseME Page 26 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Figure 22. Emulator

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 41 developerWorks® ibm.com/developerWorks

Developing J2ME applications with EclipseME Page 28 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Section 7. Debug the midlet

Set break points

Using Eclipse's "Run" menu, you can set break points, or watch points, at the cursor position in the source code editor. The green dot on the left of the editor in the following figure shows a method break point on the commandAction() method. It causes the MIDlet execution to pause whenever the user presses a soft key.

Figure 23. Set a break point

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 41 developerWorks® ibm.com/developerWorks

Run the debugger

You can now run the midlet in debugging mode using the "Run | Debug ..." menu item.

Figure 24. Start the debugging

Developing J2ME applications with EclipseME Page 30 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

The emulator would otherwise start normally, but when you hit the break point (in this case, by pressing a soft key to invoke the command handler commandAction() method), Eclipse changes its display from the Java perspective to the debugging perspective. It displays the call stack, the current break point, and the values of the variables in the stack. After reviewing that data, you can resume execution using the "Run" menu.

Figure 25. The debugging perspective

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 41 developerWorks® ibm.com/developerWorks

Section 8. Packaging the MIDlet suite for deployment

Edit the JAD file

With the MIDlet compiled and tested, you can now prepare the deployment. The first step is to compose the deployment descriptor file (the JAD file). The auto-generated "EclipseMETutorial.jad" file under the project root directory is a template for the JAD file. If you double-click it, you can edit its content in the source editor. The EclipseME customizes the JAD editor with an intuitive UI, which enforces that all the required JAD attributes are included and correctly spelled.

Developing J2ME applications with EclipseME Page 32 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Figure 26. Required JAD attributes

If you have multiple MIDlets in the project, you can select which MIDlet classes to include in the MIDlet suite defined in this JAD file.

Figure 27. MIDlet attributes

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 41 developerWorks® ibm.com/developerWorks

You can also specify attributes that provide optional information about the MIDlet suite.

Figure 28. Optional attributes

Developing J2ME applications with EclipseME Page 34 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

The over-the-air (OTA) properties can be used to send notifications back to the deployment server when the MIDlet suite is installed or deleted.

Figure 29. OTA attributes

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 41 developerWorks® ibm.com/developerWorks

The user-defined attributes can make deploy-time information available to the MIDlet at runtime. (We do not have any user-defined attributes here.)

Figure 30. User defined attributes

Developing J2ME applications with EclipseME Page 36 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Generate the JAR file

Right click on the project name in the Package Explorer, and select "J2ME | Create Package" to create the JAR file for the MIDlet suite. The pre-verified class files in the "verified" directory and the resource files in the "res" directory are included in the JAR file. The JAR manifest is derived from the JAD attributes you have just edited. Choose the "J2ME | Create Obfuscated Package" to generate the Proguard obfuscated JAR file.

Figure 31. Create package

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 41 developerWorks® ibm.com/developerWorks

The JAR file and a copy of the JAD file are placed in the "deployed" directory as you have configured. Now you are ready to copy those files to an OTA server or deploy them directly to devices through local connections.

Figure 32. The deployment package

Developing J2ME applications with EclipseME Page 38 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Section 9. Summary and resources

Summary

In this tutorial, you learned how to use EclipseME and the Sun WTK to enable J2ME development on the Eclipse IDE platform. Those free tools allow Java developers to quickly learn and prototype J2ME applications for mobile phones.

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 41 developerWorks® ibm.com/developerWorks

Downloads

Description Name Size Download method Code sample wi-nokiasource.zip28KB HTTP

Information about download methods

Developing J2ME applications with EclipseME Page 40 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Resources

• You can download the Eclipse IDE from the Eclipse Web site. The site also has documentation on how to use the IDE and how to develop plug-ins. • The Sun J2ME Wireless Toolkit is freely available for download. • The EclipseME project is an open source Eclipse plug-in that supports J2ME/MIDP development. • The J2ME 101 series of tutorials on IBM developerWorks is a good place to get started with J2ME and MIDP programming: • "J2ME 101, Part 1: Introduction to MIDP's high-level user interface" (developerWorks, November 2003). • "J2ME 101, Part 2: Introduction to MIDP's low-level UI" (developerWorks, December 2003). • "J2ME 101, Part 3: Inside the Record Management System" (developerWorks, December 2003). • "J2ME 101, Part 4: The Generic Connection Framework" (developerWorks, January 2004).

About the author

Michael Juntao Yuan Dr. Michael Juntao Yuan is a writer, analyst, and developer for end-to-end mobile solutions. He has extensive experience with J2ME, Java 2 Platform, Enterprise Edition (J2EE), and .Net technologies. Michael has published more than 30 mobile-related articles in leading technical and academic journals. He is also the author of two books: Enterprise J2ME (Prentice Hall, 2003) and Developing Scalable Applications (Addison-Wesley and Nokia, 2004). For technical questions or comments about the content of this tutorial, contact the author at [email protected].

Developing J2ME applications with EclipseME © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 41 of 41