devxlogo

Automate Your J2ME Application Porting with Preprocessing

Automate Your J2ME Application Porting with Preprocessing

ecause Java is theoretically portable, people assume that when you develop a Java mobile application, it should run correctly on all Java-enabled devices. Like most things theoretical, this just doesn’t work in the real world. During the short life of J2ME mobile applications, many developers have expressed concerns that interoperability problems are not going to be solved so easily by new initiatives like MIDP 2.0 or JTWI.

The reality is that J2ME may be globally portable but J2ME applications are not. This means that byte-code runs correctly on all Java handsets but the behavior of an application must be adapted for almost each handset. There are 1200 mobile devices, all of which have different capabilities, support various Java platforms?including MIDP, and support optional APIs and optional parts of APIs. Not to mention that each of these implementations has its own unique set of bugs (click here to see a demonstration of this fragmentation of device characteristics and features).

The result of this is that, in a typical development cycle, porting and testing can consume from 40 to 80 percent of your time, depending on your level of experience and on the number of devices you need to support.

Testing your ported mobile applications on real mobile phones isn’t always easy. A good emulator should reproduce all the bugs of the real device, but emulators don’t always exist and when they do, they’re far from reliable.

Bugs are another difficulty?you either need resolve bugs in your source code or deactivate the problem features, all of which can be different depending on the firmware version. Manufacturers face difficulties when there are bugs in their virtual machines. This causes problems with the integration of the VM in the handset at the hardware level.

Mobile operators need to control the quality of the distributed midlets, because low-quality midlets affect operator service. Operators also need to transpose older, more successful midlets for newer device models and for wider availability. This is why developers have to be able to port their applications to these new devices quickly.

Do You Need Automatic Porting?
The number of devices your application is able to support is the main question?and the one that most effects your return on investment. Automating your porting has many benefits:

  • It reduces the time to market and enables J2ME prototypes.
  • It automates tedious tasks.
  • It allows you to focus on your application logic instead of various device specs.
  • It allows you to produce optimized applications to each device.

First, you’ll need take into account the specificities of each device model. Your application should use optional features whenever available. Table 1 shows some examples of what functionalities your application should support depending on the device.

If the device …

… Your application should

supports sounds

play sounds

supports alpha-blending

display the menu by varying opacity

has strong .jar file size limitations

remove not mandatory images

supports fullscreen

use fullscreen

has enough heap memory and supports large .jar file sizes

use optional features like bitmap fonts

supports camera control

be able to customize games using snapshots taken with the camera

supports Bluetooth

use the SMS or HTTP connections to communicate with others users (ie. chat, etc.)

supports SMS

use it to pay to activate the current application

supports PDAP

use it to access images in an internal gallery

can initiate a phone call

make phone calls

supports running applications in background

run applications in the background

Table 1: Examples of the specificities of device models

In-house Porting Solutions
So, you’ve decided you do need to automate porting your application. Sure, you could outsource it, but if you’re thinking about doing it in-house, you’ve basically got four methods from which to choose.

  1. Build one Version per Device Series: This approach is to simply develop an application for a specific series of models, for example, the Nokia Serie40 Edition 1. The problem here is that the more APIs you support, or the more your application stresses the device, the more you fragment the series since support for advanced APIs highlights the small differences within the series. For example, two similar devices will have wildly varying performance results due to the number of images on the screen.
  2. Dynamic Detection of the Handset: This option involves testing your application during execution. For example, suppose your model is a Nokia handset. Your application would detect the device model during execution and select the appropriate behaviour depending on the model.

    This allows you to call methods only available on specific handsets?like fullscreen mode. You have to create one class for each specific implementation (NokiaCanvas, SiemensCanvas, and StandardCanvas). The following code demonstrates:

    try {   Class.forName("com.nokia.mid.ui.FullCanvas");   Class myClass = Class.forName("NokiaCanvas");   myCanvas = (ICanvas)(myClass.newInstance());} catch (Exception exception1) {   try {      Class.forName("com.siemens.mp.color_game.GameCanvas");      Class myClass = Class.forName("SiemensCanvas");      myCanvas = (ICanvas)(myClass.newInstance());   } catch (Exception exception2) {       myCanvas = (ICanvas) new StandardCanvas();   }}

    You basically create an interface, Icanvas, and three implementations, one for Nokia devices, one for Siemens devices, and another one for standard MIDP devices.

    Then you use Class.forName in order to determine whether a proprietary API is available. If no exception is thrown, you use the NokiaCanvas. Otherwise, it means the current device doesn’t support this API. In this case, you test another API (for example, Siemens). If another exception is thrown, it means you have to use the standard canvas.

    Because this solution supposes the inclusion of the logic of the behavior of each the model of a device in each application, it quickly becomes impossible.

  3. Using Alteratives Like AOP or Extended Java: In his recent DevX article, Allen Lau discussed using AOP to solve the problem of fragmentation. His idea is to concentrate the application logic in one location and to modify the code of the application by adding or removing portions of code.

    This approach solves some problems, but having to adapt the structure of your application to different platforms may, in the end, force you to use another, complementary solution. This is because it can be very difficult to optimize the application to each device model?especially to support optional APIs.

    Additionally, this method does not solve the problem of adapting the content (images, sounds, etc.) to each device model. You can use Java extensions to automatically transform your source code, which is an interesting approach, but it really increases work load.

  4. Using a Preprocessor: Using a preprocessor, your source code will be automatically activated or deactivated depending on certain conditions.

    For example, to set the full screen mode on a Nokia device, you have to extend FullCanvas, not Canvas. On a MIDP 2 device, you have to call setFullScreenMode. On a MIDP 1 device, this isn’t possible, so you stay in a non-fullscreen mode.

    //#ifdef NOKIA   extends com.nokia.mid.ui.FullCanvas//#else   extends Canvas//#endif   {...//#ifndef MIDP2      setFullScreenMode(true);//#endif

    A preprocessor processes this source code, then you set the directives. So, to generate the application for a Nokia device:

    //#define NOKIA

    The preprocessor produces:

       extends com.nokia.mid.ui.FullCanvas   {

    For a MIDP 2 device, (“//#define MIDP 2”), it produces:

       extends Canvas   {      setFullScreenMode(true);

    This solution allows for one body of source code to be adapted to each device model. You need only develop to the reference source code, including the directives. All other modifications made to the processed files will be lost after the next preprocessing.

    Though this solution relies on the old concept of preprocessing, this is the only technique open-ended enough to solve all the problems you’ll encounter trying to port to multiple device models.

What’s Involved in Porting with a Preprocessor?
The basic principle is to keep only one version of your source code, which is then preprocessed to generate code adapted to each device model.

Here are some things to keep in mind:

  • You’ll need a thorough knowledge of the specific behavior of each device model.
  • You’ll need to know the Java features supported by each device model.
  • You’ll need to know which operations are more or less covered by pre-processing (things like deployment).
  • Remember that pre-processing does not convert resources (things like images or sounds).
  • You need to completely automate your solution?a parameterized solution is not sufficient.
  • You’ll need to invest in the development of an automated compilation and packaging process.

You’ll need to use conversion tools to adapt resources like images and sounds to the capabilities of each device model. The images will have to be optimized; for instance, you’ll need to remove optional information in the headers of .png images, group small images in big images, reduce the number of colors for each image, preload resources, etc.

You may have to create a series of Java devices with the same characteristics, features, and behaviour. Then, you can produce one application for this series, not for each device model. The features of this series will depend essentially on the features you want to use in your applications. The more optional features you use, the more fragmentation you’ll be dealing with.

You’ll need to update the application in order to take into account unexpected resources. For example, if the device supports big .jar files and has a high heap memory, you can store a background image for your app. Otherwise, the image will not be included in your .jar file and you will need to draw the image simply. In this case, the .jar size will decrease and the heap memory will be less consumed.

Remember, screen size is an important issue when it comes to mobile programming, so don’t hesitate to use all the available techniques to reduce image size (like dynamic transformation of images or transformation before packaging).

Another good practice is to manage the interactions with the system. For example, during an incoming call, stop sounds and pause your midlet during the call.

A Concrete Example
Suppose you want to port the game MyGame on the following devices: MIDP 1, MIDP 2, MIDP 1 NokiaUI, and MIDP 1 Motorola.

Here’s a step-by-step overview of the process:

  1. Download and install Ant and Antenna.
  2. Create a specific class for the sound. This class will include the specific code to play sounds for each specific device.
  3. Create a series of Antenna XML files for each device model (ie MIDP 1, MIDP 2, MIDP 1, NokiaUI, and MIDP 1 Motorola). These files will:
    • Preprocess the source files, retaining only the lines concerning the current device.
    • Build the project by compiling the source files and pre-verifing the classes.
    • Run the ported midlet in the emulator for testing.

Seems easy, right? Creating the SoundManager Class
The SoundManager class contains the instructions to play a basic sound and to set the backlight. It supports the following generic devices:

  • MIDP 1: This device doesn’t support sounds and backlight, so the methods will be empty.
  • MIDP 2: This device supports sounds and backlight, so the lines of code between //#ifdef MIDP2 and //#endif will be selected.
  • MIDP 1 NokiaUI: This device supports sounds and backlight, so the lines of the code between //#ifdef NOKIAUI and //#endif will be selected.
  • MIDP 1 Motorola: This device supports only backlight, so the method to play a sound will be empty.

Listing 1 shows the code.

Creating the BUILD.XML File
In the BUILD.XML file, you will select the appropriate directories. It’s a manual operation, so, it’s best to create the XML files for each device and keep them.

In the case of the MIDP 2 profile, the preprocessing of the file SoundManager.java will produce this output:

import javax.microedition.media.*;import javax.microedition.media.control.*;import javax.microedition.media.control.ToneControl;import javax.microedition.lcdui.*;import java.io.*;public class SoundManager {  Display display;    public SoundManager(Display display) {    this.display = display;  }  public void doLight() {    display.flashBacklight (duration);  }  public void doSound() {    try {      InputStream is = getClass().getResourceAsStream("music.mid");      Player audioPlayer = Manager.createPlayer(is, "audio/midi");      audioPlayer.start();    } catch (IOException ioe) {    }  }}

For the MIDP 1 profile, it produces:

import javax.microedition.lcdui.*;import java.io.*;public class SoundManager {  Display display;    public SoundManager(Display display) {    this.display = display;  }  public void doLight() {  }  public void doSound() {  }}

You select the profile of the device in this line:

Antenna takes the content of the attribute symbols (MIDP 2 in this example) and inserts //#define MIDP2 at the beginning of each file, like this:

//#define MIDP2//#ifdef MIDP2import javax.microedition.media.*;import javax.microedition.media.control.*;import javax.microedition.media.control.ToneControl;//#endif//#ifdef NOKIAUIimport com.nokia.mid.sound.*;import com.nokia.mid.ui.*;//#endif//#ifdef MOTOROLAimport com.motorola.multimedia.*;//#endifimport javax.microedition.lcdui.*;import java.io.*;

Building the Preprocessed Source Code
Next, build the preprocessed source code, which means compiling the two files you’ve created.

The name of the .jad file and its content are specified in the tag:

                    

It's advisable to always use the same name for the icon (for instance, icon.png).

To package the midlet, create the .jar file. Select the resources to be integrated in your .jad file. Here are some simple guidelines for this process:

  • Separate graphics for different types of screens (big screens, medium screens, small screens, etc.).
  • Separate the icons of each size in a sub-directory (res_icon32x32, res_icon16x16, etc.).
  • Separate the resources for sounds (res_midifiles, res_ottfiles, etc.).

In Table 3, the left column describes the code in the right column.

 

Name the project.

Specify where to find WTK.

 

Specify the midlet name.

 

 

 

Specify the standards APIs you use (WMA, MMAPI, PDAP, 3D, Bluetooth, Web services).

 

 

 

 

 

 

Specify the CLDC version.

 

Specify the MIDP version (MIDP 1 or MIDP 2) :

-        

-        

 

Specify the proprietary APIs (Nokia Serie40, Nokia Serie60, …).

-        

-        

 

 

 

Clean the classes directory.

 

   

   

     

       

     

   

 

 

 

Clean the output directories: outputin, outputclasses, outputsrc

   

   

   

   

   

   

Launch the pre-processor process

   

Launch the compilation process

   

Launch the packaging process

   

      jarfile="outputin${midlet.name}.jar"

      name="${midlet.name}"

      vendor="You"

      version="1.0"

      target="">

     

     

   

 

  

     

Include the resources (for the big screens or for the small screens).

-        

-        

     

Include the icon (format 32x32 or 16x16) :

-        

-        

     

Include the sounds files (midi files or ott files) :

-        

-        

     

 

     

   

 

 


Table 3. Building the Preprocessed Code.

Creating the RUN.XML File
To run the emulator, you have to create a XML file. The emulators have to be installed in the directory wtklibdevices of the WTK. You have to use the device name displayed in WTK (the directory name for the device) and specify it in the following line in the attribute device:

Table 4's left column explains the code for the RUN.XML file, shown in the right column.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Run the emulator (WTK, Nokia Serie40 or Nokia Serie60) :

-         For WTK :

-         For Nokia Serie40 Edition 1 :

-         For Nokia Serie60

   

 

 

This example supports basic sounds and backlight for some devices. But in reality, you'd also have to support other features like keyboard constants, fullscreen support, screen refresh loop, regulation of frame rate, and image and sound formats.

Addressing the Complete Chain of Production
Remember that deployment and testing are also very important. Because each small, manual action has to be repeated for each device model, mobile development can quickly becomevery tedious. Imagine renaming all the .jad files, the .jar files, and modifying the content of each .jad file, which includes the name of the .jar file. Or imagine that your upload to the test WAP server for test purposes is manual, forcing you to use your FTP client for 300 or 400 devices!

As strategic as porting is, it's always good to take into account all the optional APIs (like Bluetooth, 3D, file connection, SMS, MMS, etc.) and the optional parts of APIs (like camera support, audio recording, .jpeg, etc.). You shouldn't continue to produce the same application on all the devices while some devices can propose more powerful features.

While porting is a fundamental problem, it's not a deal breaker for producing optimized and rich mobile applications. Ultimately, a completely interoperable mobile application is not possible due to mobile device structure. The trend is to embed more and more increasingly complex software, which means that implementations will always have problems.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist