Getting Started with J2ME

Moderators: Moderator, Global Moderator

Post Reply
Tami
Administrator
Administrator
Posts: 0
Joined: Sun Apr 25, 2004 1:05 pm

Getting Started with J2ME

Post by Tami »

Getting Started with J2ME
This article is excerpted from J2ME Games with MIDP2 by Carol Hamer (Apress, 2004; ISBN 1590593820)

[attachment=728]attachment[/attachment]

If you are engaged in game development, you might want to consider using Java 2 Micro Edition. This article will help get started; soon, you'll be well on your way to building your first game. It is excerpted from J2ME Games with MIDP2, written by Carol Hamer (Apress, 2004; ISBN 1590593820).

IN THIS CHAPTER, I cover what you need to do to set up your computer for Java 2 Micro Edition (J2ME) game development and how to get your games running on an actual target device. Once you have your development environment running, you can start by building and modifying the examples from this book. You can download all the source code for the examples from the Downloads section of the Apress Web site (http://www.apress.com). This includes all the image files, descriptor files, and optional scripts.
Downloading and Installing the Toolkit

If you haven’t already downloaded and installed a development toolkit, you can get the standard one at http://java.sun.com/j2me/download.html. Look for the J2ME Wireless Toolkit 2.0. If you’re planning to develop some games that will also runwith Mobile Internet Device Profile (MIDP) 1.0, you may also want to download the J2ME Wireless Toolkit 1.0.4 for backward-compatibility testing. Many other J2ME emulators are available on the Web for free download, but for the rest of this chapter I’ll assume you’re using the J2ME Wireless Toolkit 2.0 from Sun.

If you have trouble downloading the toolkit from Sun, keep in mind that you need to register at the Sun site and log in. This shouldn’t be a problem—it doesn’t cost anything. You have to submit your e-mail address, but Sun has never sent me any spam as a result of my registration, so don’t worry about anything.

The J2ME Wireless Toolkit contains a minimal MIDlet development environment (called KToolbar), a cell-phone emulator, and a number of helpful demo applications with source code. It also contains a clear and comprehensive manual in Hypertext Markup Language (HTML). I therefore won’t take up too much space in this chapter repeating information contained in the manual about using the toolkit. I’ll just highlight a few additional points that I noticed about toolkit in the “Compiling and Running from the Command Line” and “Using KToolbar” sections.
Building an Application for MIDP

I’ll stick with tradition and start with the classic “Hello, World” application. This example will illustrate how to get a minimal MIDlet compiled and running.

When you examine the demo applications that are bundled with the toolkit, you’ll notice that they consist of a jar file and a jad file. The jar file contains the class files, the resources, and a manifest file (just as you’d expect to find in any jar file). The jad file is a Java properties (text) file that contains information to help the device run the application. The manifest file (MANIFEST.MF) found inside the jar file contains the same information as the jad file minus two properties: MIDlet-Jar-URL and MIDlet-Jar-Size.

Listing 1-1 is an example of the jad file I wrote for my “Hello, World” application. I called this file hello.jar.

Code: Select all

Listing 1-1.hello.jar

MIDlet-1: Hello World, /images/hello.png, net.frog_parrot.hello.Hello
MMIDlet-Description: Hello World for MIDP
MIDlet-Jar-URL: hello.jar
MIDlet-Name: Hello World
MIDlet-Permissions:
MIDlet-Vendor: frog-parrot.net
MIDlet-Version: 2.0
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-2.0
MIDlet-Jar-Size: 3201
The MIDlet-1 (and MIDlet-2, and so on) property gives the name of the MIDlet, the location of the MIDlet’s icon, and the fully qualified name of the MIDlet class to run. The first two items describe how the MIDlet will appear on the menu of MIDlets. The icon should be in the jar file, and its location should be given in the same format as is used by the method Class.getResource(). Thus, in this example, your jar file should contain a top-level folder called images, which contains an icon called hello.png, as shown in Figure 1-1.

[attachment=729]attachment[/attachment]

Figure 1-1. This is the icon hello.png.

The MIDlet-Jar-Size property gives the size of the corresponding jar file in bytes, which you can find by looking at the properties or long listing of the jar fille. Be aware that if you rebuild the demos or your own applications using the build script or batch file bundled with the toolkit, you must manually update the size of the jar file in the jad file. If the MIDlet-Jar-Size property in the jad file doesn’t match the size of the jar file, the MIDlet won’t run.

NOTE Since the size generally changes with every build, and it’s annoying to open your jad file in a text editor with every build, I’ve included some build script modification suggestions in the “Compiling and Running from the Command Line” section.

The MIDlet-Jar-URL property gives the address of the MIDlet jar relative to the location of the jad file. If the jar file and the jad file are kept in the same directory, this is just the name of the jar file. It’s also possible to use a complete Uniform Resource Locator (URL) if the jar file is located somewhere else on the Internet. Chapter 7 discusses the MIDlet-Permissions property, but for simple games, you can omit it or leave it blank. The other properties are self-explanatory.

This section shows the “Hello, World” application. The MIDlet will display the message Hello World! on the screen and remove it (or later put it back) when you click the Toggle Msg button. Clicking the Exit button will terminate the MIDlet. The application consists of two classes: the MIDlet subclass called Hello and the Canvas subclass called HelloCanvas. How it works is sufficiently simple that I’ll leave the explanations of the various steps in the comments. Chapter 2 includes in-depth discussion of how a MIDlet works. Listing 1-2 shows the code for Hello.java.

Code: Select all

Listing 1-2.Hello.java

  package net.frog_parrot.hello;
  import javax.microedition.midlet.*;
  import javax.microedition.lcdui.*;
  /**
  * This is the main class of the "Hello, World" demo.
  * 
  * @author Carol Hamer
  */
public class Hello extends MIDlet implements CommandListener {
  /**
  * The canvas is the region of the screen that has been allotted 
  * to the game. 
  */
HelloCanvas myCanvas;
  /**
  * The Command objects appear as buttons in this example.
  */
private Command exitCommand = new Command("Exit", Command.EXIT, 99);
/**
  * The Command objects appear as buttons in this example.
  */
private Command toggleCommand = new Command("Toggle Msg", Command.SCREEN, 1);
/**
  * Initialize the canvas and the commands.
  */
public Hello() {
  myCanvas = new HelloCanvas(); 
  myCanvas.addCommand(exitCommand);
  myCanvas.addCommand(toggleCommand);
  // you set one command listener to listen to all
  // of the commands on the canvas: 
  myCanvas.setCommandListener(this);
}
//---------------------------------------------------------// implementation of MIDlet
/**
  * Start the application.
  */
public void startApp() throws MIDletStateChangeException {
  // display my canvas on the screen:
  Display.getDisplay(this).setCurrent(myCanvas); 
  myCanvas.repaint();
}
/**
  * If the MIDlet was using resources, it should release 
  * them in this method.
  */
public void destroyApp(boolean unconditional) 
    throws MIDletStateChangeException {
}
/**
  * This method is called to notify the MIDlet to enter a paused
  * state. The MIDlet should use this opportunity to release
  * shared resources.
  */
public void pauseApp() {
}
//--------------------------------------------------------- // implementation of CommandListener
  /*
  * Respond to acommand issued on the Canvas. 
  * (either reset or exit).
  */
public void commandAction(Command c, Displayable s) {
  if(c == toggleCommand) {
    myCanvas.toggleHello();
  } else if(c == exitCommand) {
    try {
      destroyApp(false);
      notifyDestroyed();
    } catch (MIDletStateChangeException ex){
    }
  }
 }
}

Listing 1-3 shows the code for HelloCanvas.java.

Listing 1-3.HelloCanvas.java

package net.frog_parrot.hello;

import javax.microedition.lcdui.*;

/**
  * This class represents the region of the screen that has been allotted
  * to the game.
  *
  * @author Carol Hamer
  */
public class HelloCanvas extends Canvas {
  //-------------------------------------------------------  // fields
  /**
  * whether the screen should currently display the
  * "Hello World" message.
  */
boolean mySayHello = true;
//---------------------------------------------------------
//    initialization and game state changes
/**
  * toggle the hello message.
  */
void toggleHello() {
  mySayHello = !mySayHello;
  repaint();
}
//---------------------------------------------------------
// graphics methods
/**
  * clear the screen and display the "Hello World" message if appropriate.
  */
public void paint(Graphics g) {
  // get the dimensions of the screen:
  int width = getWidth ();
  int height = getHeight();
  // clear the screen (paint it white):
  g.setColor(0xffffff);
  // The first two args give the coordinates of the top
  // left corner of the rectangle. (0,0) corresponds
  // to the top-left corner of the screen.
  g.fillRect(0, 0, width, height);
  // display the "Hello World" message if appropriate:.
  if(mySayHello) {
    Font font = g.getFont();
    int fontHeight = font.getHeight();
    int fontWidth = font.stringWidth("Hello World!");
    // set the text color to red:
    g.setColor(255, 0, 0);
    g.setFont(font);
    // write the string in the center of the screen
    g.drawString("Hello World!", (width - fontWidth)/2,  
                  (height - fontHeight)/2,
                  g.TOP|g.LEFT);
   }
  }
}
The “Hello, World” application is simple enough to run with MIDP 1.0 as well as with MIDP 2.0. Figure 1-2 shows what the “Hello, World” application looks like when running on the Wireless Toolkit 1.0.4’s DefaultGrayPhone emulator.

[attachment=730]attachment[/attachment]

Figure 1-2. The “Hello, World” application

The MIDlet development environment KToolbar is easy to use, and it’s well documented. Even if you’re not planning to use KToolbar, you should definitely browse the documentation a bit so you have a good idea of what sorts of tasks KToolbar can do (you may decide you want to use it after all...).

KToolbar is a “minimal” development environment in the sense that, unlike JBuilder, it doesn’t contain a text editor. It’ll create and update your jad and manifest files and your project’s directory tree for you after you fill in the details in a set of Graphical User Interface (GUI) windows, but you have to create all the source files yourself in your own text editor. Also unlike JBuilder, it doesn’t create its own project file describing your project. This is handy because you can open a “project” in KToolbar, even if you created the directory tree for the project yourself, instead of having KToolbar create it for you. All you need to do is make sure your project’s root directory is in the right place (in the apps folder inside the WTK2.0 folder), and you can open it as a project in KToolbar.

In addition to setting up your project, KToolbar will preverify and build your project and then run it in the emulator at the click of a GUI button. It also has a whole suite of useful features for debugging and performance monitoring. Plus, it has tools for signing your MIDlet. (Chapter 7 covers more about signing.) Figure 1-3 shows what KToolbar looks like.

[attachment=731]attachment[/attachment]

Figure 1-3. KToolbar
Compiling and Running from the Command Line

Running the MIDlet in the emulator from the command line is simple. All I did was go to the bin directory under the toolkit’s WTK2.0 directory. From there I typed ./bin/emulator followed by an option giving the name of the jad descriptor file corresponding to the MIDlet I wanted to run. For example, to run the “Hello, World” application on my system, I typed the following line:

Code: Select all

./bin/emulator -Xdescriptor: /home/carol/j2me/book/ch02/bin/hello.jad
Another useful option when running the emulator from the command line is the option that gives you a choice of different devices. The option is -Xdevice, and the choices are DefaultColorPhone, DefaultGrayPhone,MediaControlSkin, and QwertyDevice. The previous command including this option looks like this (note that it needs to be typed on a single line):

Code: Select all

./bin/emulator -Xdevice:Qwerty Device
-Xdescriptor:/home/carol/j2me/book/ch02/bin/hello.jad
Figure 1-4 shows the DefaultColorPhone emulator. You’ll find other emulator options listed in the toolkit documentation’s “Running the Emulator” section.


[attachment=732]attachment[/attachment]

As I mentioned previously, if you rebuild your project from the command line using the scripts bundled with the toolkit, you’ll need to update the MIDlet-Jar-Size property in your jad file after rebuilding. This isn’t necessary if you’re using

KToolbar, but personally I like to build my jar files myself whenever possible so I know what’s in them. If you’re planning to build your jar files using scripts, you’ll probably want to change the build script so you won’t have to update the jad file by hand in a text editor after every build. This section assumes that you’re using Linux or Unix. (I’d guess that those people who aren’t using Linux/Unix are also not building their jar files from the command line, so they probably have already skipped this section.)

The build script in Listing 1-4 requires that the MIDlet-Jar-Size property is the last line of the jad file, as it is in the examples I provided. Note that this script assumes you have a file tree configured as follows: Under your project’s main directory, you must have four subdirectories: bin (which contains this script as well as the jad and MANIFEST.MF files), a tmp classes directory (which may be empty), a classes directory (containing a subdirectory called images that contains all of your image files), and a src directory that contains the directory tree for the source code of the MIDlet you’d like to compile.

Code: Select all

Listing 1-4. Build Script

# This script builds and preverifies the code
# for the example games.
# reset this variable to the path to the correct javac
# command on your system: JAVA4_HOME=/usr/java/j2sdk1.4.0_01/bin
# reset this variable to the corresct path to the WTK2.0
# directory of the WTK2.0 toolkit that you downloaded: WTK2_HOME=../../../WTK2.0
echo "clear directories"
# it's better not to leave old class files lying
# around where they may accidentally get picked up
# and create errors... rm ../tmpclasses/net/frog_parrot/*/*.class rm ../classes/net/frog_parrot/*/*.class
echo "Compiling source files"
$JAVA4_HOME/javac -bootclasspath $WTK2_HOME/lib/midpapi.zip \
-d ../tmpclasses -classpath ../tmpclasses ../src/net/frog_parrot/*/*.java
echo "Preverifying class files"
$WTK2_HOME/bin/preverify \
-classpath $WTK2_HOME/lib/midpapi.zip:../tmpclasses \
-d ../classes ../tmpclasses
echo "Jarring preverified class files"
$JAVA4_HOME/jar cmf MANIFEST.MF hello.jar -C ../classes .
echo "Updating JAR size info in JAD file..."
NB=`wc -l hello.jad | awk '{print $1}'`
head --lines=$(($NB-1)) hello.jad > hello.jad1
echo "MIDlet-Jar-Size:" `stat -c '%s' hello.jar`>> hello.jad1
cp hello.jad1 hello.jad
Ideally it’d be nice to have access to a whole range of devices to test your game on throughout the development phase. But even working for a large corporation you won’t necessarily have access to every device on which you may want to run your games. Fortunately, the emulator has a number of performance parameters you can set in order to approximate your target devices as closely as possible. These parameters include the heap size, the virtual machine speed, the refresh speed, and the network speed. You can set these parameters from KToolbar. The toolkit’s HTML documentation gives details on how to do it.

The bad news is that according to the emulator’s own documentation, “Setting the VM speed parameters does not emulate real device speed, even though a real device skin might be used. ” Furthermore, the documentation states, “Setting the network throughput speed does not emulate actual network transmission speed. ” So testing your game with a range of values for these two parameters will give you an idea of how your game will perform on various devices, but it’s not perfect. Additionally, it can be difficult to find out precisely what to set these parameters to in order to emulate a given device. The device manufacturer’s site usually has some product specs, but not always all the detail you’d like. If the product details aren’t in an obvious location, then your best bet is usually to go to Google and search for the device name plus specs. A good place to start to get a list of possible devices from various manufacturers to develop for is http://www.microjava.com.

If you have a particular device in mind, the next best thing to testing on the actual target device is to test on an emulator designed by the device’s manufacturer. Most major device manufacturers (including Nokia, Motorola, Ericsson, Samsung, and Siemens, to name a few) offer emulators or at least emulator skins you can download. As usual, you can find these by consulting the manufacturer’s Web site or Google. (Additionally, I found a comprehensive list of links to emulator downloads at the site http://www.jroller.com/page/shareme/J2MEEmulators.) These often have proprietary class libraries included, so you should probably avoid using a proprietary toolkit as your primary development tool unless you’re 100 percent certain you’re developing games for only one particular brand of device. On the other hand, if you have plenty of room on your development machine, it wouldn’t hurt to install some additional toolkits to fine-tune your games for particular devices.

Running Your Game on an Actual Cell Phone

The emulator is a helpful development tool, but even though it works well, it’s no substitute for testing your game on an actual device. Plus, playing your game on your own cell phone is the fun part! The idea of how to load the file onto the phone is pretty simple, but you need to be aware of a few details.

You have two ways to proceed. The first is to transfer files from your PC using a serial/Universal Serial Bus (USB) cable or an infrared connection. This option doesn’t require the data to even leave your house. The second option is more exciting. It consists of placing the required files on a server on the Internet and downloading them using a data connection from the phone—using Global System for Mobile Communications/General Packet Radio Service (GSM/GPRS).

Both methods have advantages. The first method doesn’t require you to make a call from the phone and is therefore completely free (except for the cost of the cable if one isn’t included with the phone). Also, since the transfer takes place entirely within your own network (generally behind your firewall), there’s no danger of your game being downloaded by unauthorized users. But this technique can place additional requirements on your local system. For example, in the case of Nokia, the software that’s used to perform the transfer works only on Windows, and the PC that the data is being loaded from must have an infrared port or a separate USB cable.

The second method, placing the games on a Wireless Application Protocol (WAP)–accessible Web page, is clearly preferable if you intend to distribute the games yourself—even if you’re distributing it only to your friends. After all, if you set it up so that you can download your game off the Internet, you can tell other people where it is and they can download it as well. For this option you need to be sure that your phone service contract includes WAP access and application downloading. (This is a typical option that’s offered with a Java-enabled phone, so the salesperson who sells you the phone will probably suggest it to you before you even have to ask about it.) You’ll also need a server on which to place the files. This shouldn’t be too difficult to come by since most Internet Service Providers (ISPs) offer some personal Web space with standard Internet access contracts. All additional software needed for this means of data transfer exists in free versions for all platforms.

In this book I’ll cover only how to transfer your games to the device through the Internet and not through direct file transfer because transferring the files directly is vendor dependent. If you’d like to transfer the files to your phone directly, then the first step is to go to the Web site of the phone’s manufacturer. In the case of Nokia, for example, the necessary software is easy to find on the site and is well documented. The same should be true of most other makers of Connected Limited Device Configuration (CLDC) devices.
Using WAP

WAP is the protocol that small devices use to access the Internet.

The principle of WAP is that your cell-phone provider makes available a gateway through which your phone can access the Internet. Since small screens make standard browser functions and standard HTML pages unusable, there’s another markup language specially designed for cell phones and other small devices called Wireless Markup Language (WML). If your phone contract specifies WAP access and doesn’t restrict browsing to some specific portal and sites, you can direct your phone to a WML page listing your MIDlets. From there you can download them. This is similar to a standard HTML Web page embedding a Java applet.

So, to prepare your games for download, you first need to upload them onto a Web server. You need to place the WML file on the server as well as the jar and jad files. In addition, you may have to perform some configuration so that the Web server, when accessed, returns a correct Multipurpose Internet Mail Extensions (MIME) type description for those files. Otherwise, the phone may be unable to recognize them. The following sections explain these steps in detail using the Nokia 6100 as the example phone.
Preparing the WML File

You can use WML to display interesting content by itself, offering User Interface (UI) elements such as forms, buttons, and so on. But you don’t need to do anything fancy to make a page from which your game can be downloaded. In fact, it’s better to resist the temptation to make a complex WML page because of the screen limitations of the target device. Try to keep it small and simple. Listing 1-5 shows a minimal example suitable for a download page. The file is called hello.wml.

Code: Select all

Listing 1-5.hello.wml

<?xml version="1.0"?>
<&#33;DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
 &nbsp;"http&#58;//www.WAPforum.org/DTD/wml_1.1.xml">
<wml>
<card id="hello">
<p>
Hello world&#33;
</p>
<p>
<a href="hello.jad">Hello World App</a>
</p>
</card>
</wml>
Here’s how it works: The first two lines are mandatory to identify the file as WML. The content of the page must be enclosed between the <wml> opening tag and the </wml> closing tag. The <card> tag delimits one screen of data for the device (not much&#33;). As you may guess if you know some HTML or Extensible Markup Language (XML), this page will display one line containing the text Hello world&#33; and another line with a link with the text Hello World App, as shown in Figure 1-5.

[attachment=733]attachment[/attachment]

For this link to work, the server directory containing the file hello.wml must contain a jar file called hello.jar and a jad file called hello.jad.

The page can contain multiple game links, and you add them in the obvious way. For example, inside the enclosing <card> tags, you could add a second triple such as the following:

Code: Select all

<p>
<a href="maze.jad">Amazing Maze&#33;</a>
</p>
on the lines immediately following these lines:

Code: Select all

<p>
<a href="hello.jad">Hello World App</a>
</p>
(Obviously, you must also upload the corresponding jar and jad files to the server for this link.) But if you have a large number of downloadable jar files, you’ll probably want to arrange them on a series of separate pages. If you have multiple versions of the same game suite that are optimized for different devices, it’s a good idea to make a separate WML page for each device rather than making a page for each game suite and having the page contain the versions for multiple devices. Also, it’s better to put the lengthy explanations of which version is which on a normal Web page and just put simple descriptive tags on your WML page to save the user the annoyance of excessive scrolling.

One word of warning: The <p></p> tags enclosing the links in the previous files aren’t optional. In the case of the Nokia 6100, the device failed to recognize the links without the <p></p> tags.

Many Web servers aren’t configured by default to recognize the file types associated with WAP/WML/J2ME by the file extensions. If you’re lucky, just uploading the files (described in the previous section) to a directory in the public area of the server will be sufficient. If you’re not, the cell phone will complain that the files are in an unrecognized format (even though the jad file is just text...). If you run into this problem, you’ll need to do a little bit of server configuration. I’ll explain what to do in the case of the popular Apache server.

If the Apache server is running on your own machine—which is a convenient option if you have cable or Asymmetric Digital Subscriber Line (ADSL)—all you need to do is update the httpd.conf file. (On Red Hat 9, this file is located at /etc/httpd/conf/httpd.conf.) Just add the following lines to the file:

Code: Select all

#### WAP/WML/JAD
##
AddType text/vnd.wap.wml wml
AddType text/vnd.wap.wmlscript wmls
AddType application/vnd.wap.wmlc wmlc
AddType application/vnd.wap.wmlscriptc wmlsc
AddType image/vnd.wap.wbmp wbmp
AddType text/vnd.sun.j2me.app-descriptor jad
AddType application/java jar
####
Then you must restart the server to make this information available. On Red Hat 9 you can restart the server by typing the following command as root:

Code: Select all

# service httpd restart
If the Web server you’re using belongs to your ISP, first check if the server is already configured to recognize the required types. (To check, create the page and then try to access it with your cell phone as described in the following section.) If you’re using Web space made available by the cell-phone provider, then there’s a high probability that the ISP has already taken care of the proper configuration.

If the server hasn’t been configured correctly, you may be able to fix it yourself. Here’s what to do if your ISP uses an Apache server (other servers may have similar tricks that you can find by consulting the documentation or Google...): You won’t be allowed to change the main configuration file, but you can inform Apache of the correct MIME types by placing the same lines as previously in a file called .htaccess somewhere in your Web space area. (Note that you must put such a file in every directory in which you place WAP/WML/J2ME files.) Here’s the file .htaccess:

Code: Select all

#### WAP/WML/JAD
##
AddType text/vnd.wap.wml wml
AddType text/vnd.wap.wmlscript wmls
AddType application/vnd.wap.wmlc wmlc
AddType application/vnd.wap.wmlscriptc wmlsc
AddType image/vnd.wap.wbmp wbmp
AddType text/vnd.sun.j2me.app-descriptor jad
AddType application/java jar
####
Of course, you can’t ask the ISP to restart its server, but it isn’t necessary because Apache will notice the new file automatically. It’s possible that the main configuration (which you don’t control) forbids this type of user-directed overriding. In that case, you’ll have to ask the ISP to change its policy or use another ISP.
Accessing the WML File and Downloading Applications

Now for the fun part: downloading the games onto the phone&#33; Recall that in this section I’ll use the Nokia 6100 as an example. This is a typical CLDC-enabled phone, so you can apply these same ideas to other devices without too much difficulty.

Remember, you need WAP access as mentioned previously. Be sure to check the costs involved in your contract with WAP connections. For friends who simply download your games and keep them in their phones, this is unlikely to be expensive since MIDlets are quite small and the time required for downloading them will rarely exceed a single minute. For the developer, however (that’s you&#33;), it’s best to get a contract that has a fixed price with unlimited WAP usage since you’ll certainly have to perform this operation a number of times (unless you’re placing your games on your phone using a direct PC connection during the development phase).

Before you start, you must verify that the WAP access is configured on the phone. This should have been done when you got the phone, or you should have documentation from your phone service and WAP provider giving the details. In my case, I configured the phone by going to a particular Web site and giving the phone number and a PIN code. The server then sent a Short Message Service (SMS) message containing all required information to the phone, which responded by prompting me through the procedure of entering the correct settings. On the Nokia phone you can view or edit the settings by selecting the menu item Menu -> Services -> Settings -> Edit Active Service Settings.

You can then connect to the hello.wml page by selecting the menu item Menu -> Services -> Go To and typing the URL just as you would for a regular Web page. So, for example, if your domain name is frog-parrot.net, then you’d type http:// frog-parrot.net/hello.wml if the hello.wml file is in the top-level directory. (If your hello.wml is in a subdirectory, add the names of the subdirectories to the URL just as you would for any other URL.)

If you’re using your own server at home and connecting through cable or ADSL, then you may not have a nice domain name, but you should still have an Internet Protocol (IP) address to which the phone can connect. Depending on how your connection works, your IP address may change from time to time. The operating system will tell you what your current IP address is. In the case of Linux you can find out by looking for the inet addr in the output you get from typing the following command:

Code: Select all

&#036; /sbin/ifconfig ppp0
If your address is just a set of numbers, it still works perfectly well in the URL. Suppose, for example, that you entered the previous command and you got the following output:

Code: Select all

ppp0 Link encap&#58;Point-to-Point Protocol
 &nbsp; &nbsp; inet addr&#58;81.49.195.43 P-t-P&#58;193.253.160.3 Mask&#58;255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST MTU&#58;1492 Metric&#58;1
RX packets&#58;1108 errors&#58;0 dropped&#58;0 overruns&#58;0 frame&#58;0
TX packets&#58;1097 errors&#58;0 dropped&#58;0 overruns&#58;0 carrier&#58;0
collisions&#58;0 txqueuelen&#58;3
RX bytes&#58;798514 &#40;779.7 Kb&#41; TX bytes&#58;98348 &#40;96.0 Kb&#41;
In this case, the URL to enter into your phone is http://81.49.195.43/hello.wml.

Merely typing the URL into the phone can be tricky&#33; In the case of the Nokia 6100 you can get a list of symbols by hitting the asterisk+plus key (*+). Navigate through this list using the right and left arrow keys until you find the desired symbol (such as . or / for a URL), and then select Use. Fortunately, the fact that the period (.) is the default symbol may save you a little effort. If you have a fixed IP address or domain name, you can also save yourself some typing by making a bookmark to your page.

Once the URL is entered, click OK, and the phone should open your WML page&#33; From here you can click the link to your game, and your phone will download and install it.

Making Image Files

If you’re wondering where all the image files in this book came from, I drew them myself with a free program called the gimp, which you can download from http://www.gimp.org/download.html. If you decide to draw your image files with the gimp and you’d like them to have transparent backgrounds, be sure to select a transparent background when you first create a new image file. (A transparent background is nice for game objects because you don’t want the rectangular frame of one game object obscuring another game object.) Then make sure you select Save Background Color when you save the file. Also, you should save it with the .png extension so that the gimp will save it in the right format to be used by a J2ME game.

One thing to keep in mind when making images is that the difference in screen size from one device to another is the factor that’s likely to break your game most dramatically when you try to port it from one device to another. With very small screens every pixel counts, so a screen size difference that seems insignificant can translate to a major problem for a game. To make your game more portable, you should of course avoid using hard-coded numerical values when drawing the graphics. Additionally, it helps to make different versions of your images in different sizes. If you have only a few image files, it’s probably OK to have the game dynamically choose which images to use based on screen calculations, but if you have quite a number of image files, it’s usually preferable to maintain different versions of the game’s jar file for different devices. Graphics in the png format tend to be pretty small, but they can add up quickly and therefore significantly impact the size of your jar.

This article is excerpted from J2ME Games with MIDP2 by Carol Hamer (Apress, 2004; ISBN 1590593820). Check it out at your favorite bookstore today.
Image

[color=\"#41211C\"]It takes years to build up trust and only seconds to destroy it

[/color]
Josh
Newbie
Newbie
Posts: 0
Joined: Fri Jun 04, 2004 2:54 pm

Getting Started with J2ME

Post by Josh »

Interesting.... I did a quick skim of this. I think I'll read through this a little later <img src=\'http://www.killanet.net/forum3/public/s ... iggrin.gif\' class=\'bbc_emoticon\' alt=\':D\' />
[align=center]

Image

“If you stop learning, you stop living.” ~Tami Quiring

“It's the rare man who understands the value of a single perfect rose.”

[/align]
Post Reply

Return to “Java”