Home > Articles > Programming > Java

Like this article? We recommend

Running the Emulator from the Command Line

The J2ME emulator included with the J2ME Wireless Toolkit is a command-line tool, which means that it must be run from the command line unless you are using a visual development environment. Even if you are using a visual development environment, it's not a bad idea to learn how to use the command-line emulator because you are likely to become more acquainted with the different emulator properties by running directly from the command line. Keep in mind that most visual J2ME development environments employ the same command-line emulator; they just launch it automatically without you ever having to deal with the command line yourself.

The standard J2ME emulator ships as part of the J2ME Wireless Toolkit. In addition to this emulator, some device vendors make available their own emulators for use in testing MIDlets with their respective devices. Motorola includes such an emulator as part of their Motorola SDK for J2ME. The next two sections show you how to run MIDlets using the emulators in the J2ME Wireless Toolkit and the Motorola SDK for J2ME.

The J2ME Wireless Toolkit

Unlike many command-line Java tools, the J2ME emulator is not an executable native application that you can run directly in your native operating environment. The emulator is actually a Java application, which means that you must use the Java interpreter to run it. Also, keep in mind that J2ME is built on a set of special APIs that must somehow be available to the Java interpreter to successfully emulate a MIDlet. Associating the APIs with the emulator is as simple as altering the CLASSPATH environment variable before invoking the Java interpreter.

The run.bat Script

To help make the process of setting the class path and invoking the emulator a little easier, the J2ME Wireless Toolkit includes a special script file called run.bat that sets the CLASSPATH variable accordingly and launches the emulator in the Java interpreter. This script is located in the apps\example\bin directory within the J2ME Wireless Toolkit installation directory. Figure 3.1 shows the result of executing the run.bat script at the command-line.

NOTE

The run.bat script can be named differently on platforms other than Windows. It is common for Windows scripts (batch files) to be named with a .bat file extension.

As Figure 3.1 shows, the run.bat script launches the J2ME emulator and displays a splash screen showing the Java logo. Clicking the upper-right button with the mouse removes the splash screen and makes available several MIDlets for testing. In a moment I'll get into the details of these MIDlets and how to interact with them using the emulator's phone interface. For now, I want to take a look inside of the run.bat script to see what's going on. Following is excerpted code for the run.bat script, which shows how the class path is altered and how the Java interpreter is used to invoke the emulator:

cd ..\..\..\

set CLASSPATH=lib\kvem.jar;lib\kenv.zip;lib\lime.jar;apps\example\bin\example.jar

java -Dkvem.home=. com.sun.kvem.midp.Main DefaultGrayPhone -descriptor apps\
_example\bin\example.jad

cd apps\example\bin

Figure 3.1 The run.bat script launches the J2ME emulator, which shows an image of a phone with a java splash screen.

The directory changes in the script code are necessary to establish the J2ME Wireless Toolkit installation directory as the root directory for emulation. More important is the modified CLASSPATH variable, which is altered to include the paths of relevant J2ME libraries that are required for emulation. The kvem.jar and kenv.zip files contain classes for the emulator KVM (virtual machine), whereas the lime.jar file contains other J2ME support classes. The example.jar file contains the executable code for the various sample MIDlets that are included in the J2ME Wireless Toolkit (more on these later in this section).

With the class path properly set, the remaining step is to launch the emulator using the Java interpreter. The –D option to the interpreter is used to set the kvem.home system property, which is in turn used by the emulator to identify the root directory of the J2ME Wireless Toolkit. This is the only system property that must be set for the emulator, although there are other emulator properties. The actual emulator class file specified to the Java interpreter is com.sun.kvem.midp.Main. The remaining arguments on the command-line are passed along to the emulator. The first emulator argument is the name of the device to emulate, which in this case is DefaultGrayPhone. The next argument must be set to –descriptor, followed by the name of the application descriptor file (JAD file). The JAD file is responsible for conveying to the emulator how the application is organized.

I mentioned that the kvem.home system property is the only required property of the emulator, but that there are several other optional properties. Table 3.2 lists all the properties supported by the J2ME emulator.

Table 3.2 Attributes for the Device Profiles Supported in the J2ME Wireless Toolkit

Property

Type

Status

Default Value

kvem.home

String

Required

None

http.proxyHost

String

Optional

None

http.proxyPort

Integer

Optional

None

kvem.trace.gc

Boolean

Optional

False

kvem.trace.calls

Boolean

Optional

False

kvem.trace.class

Boolean

Optional

False

kvem.trace.exceptions

Boolean

Optional

False


The http.proxyHost and http.proxyPort properties are used to set the host and port of the HTTP proxy to be used during emulation. The remaining properties are used to turn on and off tracing information for garbage collection, method calls, class loads, and exceptions. All the tracing properties are set to false by default, which means you must explicitly turn them on to view tracing information during emulation.

The Sample MIDlets

Referring to the emulator session that was invoked by the run.bat script file, you probably noticed several MIDlets listed in the phone's display (see Figure 3.2).

All these MIDlets are included as examples in the J2ME Wireless Toolkit, and are available for testing. Following are the sample MIDlets that ship with the standard J2ME Wireless Toolkit:

  • Sokoban—A game where you slide blocks into slots

  • Tickets—A concert ticket bidding system

  • Colors—A demonstration of using colors

  • Stock—A client/server stock ticker

  • Tiles—A tile puzzle game

  • Many Balls—A demonstration of threaded animation

  • Sampler—A demonstration of several graphics features

  • Properties—A demonstration of obtaining information about the device

  • Http Test—A demonstration of establishing an HTTP connection

  • Pong—A pong game

  • Star Cruiser—A game where you navigate a ship through a star field

  • Space Invaders—A space invaders game

  • UIDemo—A demonstration of various GUI controls

All of the MIDlets except for UIDemo are available for testing using the aforementioned run.bat script file. UIDemo is itself a MIDlet suite, and includes its own run.bat script file that is located in the apps\UIDemo\bin directory. Testing the UIDemo MIDlet suite is a great way to become familiarized with the different GUI components that are available for J2ME development. You learn all about these components and how to develop MIDlets using them on Day 8, "Making the Most of MIDlet GUIs."

Running Without a Script

Thus far you've seen how to use a script to invoke the emulator and execute a suite of MIDlets specified in the examples.jad file that is included in the J2ME Wireless Toolkit. Although this is handy for getting started with the emulator quickly, it isn't quite so convenient if you want to run other MIDlets or supply additional properties to the emulator. For this reason, it is important to understand how to invoke the emulator directly from the command line without the help of the standard run.bat script file. Of course, the run.bat script gives you virtually all the information you need to carry out this task. Following is the general form of invoking the emulator:

java -cp ToolkitRoot\lib\kvem.jar;ToolkitRoot\lib\kenv.zip;ToolkitRoot\lib\
_lime.jar;JARFile
-Dkvem.home=ToolkitRoot [-DProperty=Value] com.sun.kvem.midp.Main 
_DeviceName –descriptor DescriptorFile

I realize this looks rather messy, but bear with me because it's really not too bad when you understand what's going on. First of all, let's clarify what the placeholders mean:

  • ToolkitRoot—The root directory of the J2ME Wireless Toolkit (usually \j2mewtk)

  • JARFile—The JAR file containing the MIDlet(s) you are testing

  • Property/Value—A property/value pair for an emulator property (see Table 3.2 for available properties)

  • DeviceName—The name of the device profile to be used by the emulator

  • DescriptorFile—The relative or absolute path of the application descriptor (JAD) file

You might have noticed that this command-line form for invoking the emulator is very similar to the run.bat script you saw earlier, especially when you consider that the class path settings are now being carried out directly on the command line using the –cp option. The real trick is getting the placeholders filled in properly. If you're invoking the emulator from the J2ME root directory, you can just insert a period (.) for ToolkitRoot. Otherwise, you'll need to specify the root directory everywhere ToolkitRoot appears in the command. The JARFile specifies the JAR file containing the MIDlet classes that you are testing. The only property you must specify is kvem.home, which must be set to the J2ME root directory. The DeviceName can be set to any of the following standard device profiles: Pager, MinimumPhone, DefaultGrayPhone, or DefaultColorPhone. Finally, the JAD file for the MIDlet(s) must be specified as the last argument in the command.

To help you cement in your mind the use of the emulator from the command line, here is an example of invoking the emulator from a single command using the pager profile and the J2ME example MIDlets:

java -cp.\lib\kvem.jar;.\lib\kenv.zip;.\lib\lime.jar;.\apps\example\bin\ _example.jar
-Dkvem.home=. com.sun.kvem.midp.Main Pager -descriptor apps\ _example\bin\example.jad

The result of issuing this command is shown in Figure 3.3, which reveals the flexible nature of device profiles and how much variance there can be among different devices.

Figure 3.3 By specifying pager as the device name when executing the emulator, a pager device is used as the basis for testing midlets.

If you are a command-line guru, you might already realize that this approach has a problem. The problem is that some command lines limit commands to 128 characters, which isn't enough for this hefty command. The workaround is to create your own script (batch) file to house the command. In practice, you will probably want to create scripts for your own MIDlets anyway because typing out such long commands can get cumbersome.

Controlling the Device

Because you can't make any calls or receive pages using the virtual devices represented by the J2ME emulator, it shouldn't be too surprising that you can't touch the screen to click the buttons. Instead, you can use the mouse to click any of the buttons displayed as part of a device in the emulator. Additionally, certain keys on your computer keyboard are mapped to device keys. The numeric keypad on the keyboard maps directly to the keypad on a phone device. Similarly, the letter keys and several command keys on the keyboard are all usable on the pager device. Arrow keys on the keyboard apply to all of the standard devices that are available for testing with the emulator.

The Motorola SDK for J2ME

Now that you know how to run the standard emulator included with the J2ME Wireless Toolkit, it's time to turn your attention to the Motorola SDK for J2ME and its very capable emulator. The drill is very similar to the standard J2ME emulator in that there is a script to help make things easy. The Motorola version of run.bat is called runEmul.bat, and its excerpted source code follows:

@if NOT "%1"=="" set MYCLASS=%1
@if   "%1"=="" set MYCLASS=com.mot.j2me.midlets.bounce.Bounce

set CLASSPATH=

set J2ME_RESOURCE_DIR=c:\MotoSDK\lib\resources

cd ..\bin

java -Djava.library.path=../lib -classpath ./Emulator.jar;./ConfigTool.jar 
_com.mot.tools.j2me.emulator.Emulator -classpath../demo/midlets;../lib
javax.microedition.midlet.AppManager %MYCLASS% -JSA 1 1

cd ..\scripts

One interesting thing about this code is that it accepts a command-line argument, which is referenced by %1 in the code. The idea is that you can specify the name of a MIDlet class file to runEmul.bat and it will run it using the emulator. The second line of the script shows the default behavior if you don't provide a class file—the Bounce example MIDlet is executed.

Instead of using the CLASSPATH environment variable, the Motorola emulator specifies dependent libraries directly in the command that invokes the interpreter. One environment variable that it does set, however, is J2ME_RESOURCE_DIR, which is the directory where any resources are stored for use with the MIDlets. Instead of using the CLASSPATH environment variable, the path of the standard J2ME libraries is stored in the java.library.path system property. Additionally, several support JAR files are specified using the –classpath option to the Java interpreter.

The emulator class itself is specified as com.mot.tools.j2me.emulator.Emulator. Everything in the command that appears after the emulator class is passed along to the emulator application as arguments. So, the first argument to the emulator is the path to the MIDlet(s) being executed. The second argument is the application manager that is responsible for running the MIDlets. The most significant argument is the %MYCLASS% argument, which contains the name of the actual MIDlet being executed. Finally, the –JSA 1 1 arguments at the end of the command are used internally by the emulator and are specified the same for all MIDlets.

Now that you understand how the runEmul.bat script works, let's take it for a test drive. If you change to the directory containing the script and simply enter runEmul at the command line, the Bounce example MIDlet will be executed, as shown in Figure 3.4.

To execute a different MIDlet, specify the full classname on the command line as the only argument to the runEmul script. Following is the command necessary to run the Scribble MIDlet using the Motorola emulator:

runEmul com.mot.j2me.midlets.scribble.Scribble

Figure 3.4 The runemul.bat script launches the motorola J2ME emulator and executes the bounce sample midlet by default.

The result of this command is shown in Figure 3.5 after I've done some doodling in the Scribble MIDlet.

Figure 3.5 The scribble midlet is executed in the motorola emulator by specifying the full classname as the only argument to runemul.bat.

Changing Devices

Although the default device shown in Figure 3.5 is generally reminiscent of a real mobile phone, it would be much more interesting to see an actual Motorola phone in the emulator. If you recall from earlier in the lesson, the Motorola SDK for J2ME supports several commercial Motorola devices, all of which are mobile phones. You can easily tweak the emulator to use one of these devices with a simple property addition to the command that invokes the emulator in the Java interpreter. The property is called deviceFile, and is used to specify a device file containing a custom device profile. Following is an example of how the main command in runEmul.bat changes to use the Motorola iDEN mobile phone device file:

java -Djava.library.path=../lib -classpath ./Emulator.jar;./ConfigTool.jar 
_com.mot.tools.j2me.emulator.Emulator -classpath../demo/midlets;../lib
-deviceFile resources/MotorolaiDENPlatform.props
javax.microedition.midlet.AppManager %MYCLASS% -JSA 1 1

Notice in the code that the device file is specified as resources/MotorolaiDENPlatform.props. This simple change to the emulator command results in the Motorola iDEN device profile being used instead of the generic phone profile. Keep in mind, however, that you've been using runEmul.bat to run MIDlets using the Motorola emulator, as opposed to invoking it directly with the Java interpreter by hand. Fortunately, the Motorola SDK for J2ME includes additional scripts for running MIDlets with each different device:

  • runEmul.bat—Runs a MIDlet using the generic phone.

  • runMotoiDEN.bat—Runs a MIDlet using the Motorola iDEN phone.

  • runMotoi1000.bat—Runs a MIDlet using the Motorola iDEN i1000 phone.

  • runStarTac.bat—Runs a MIDlet using the Motorola StarTac phone.

  • runMyDevice.bat—Runs a MIDlet using a custom device.

All of these scripts except for the last one are used to run the emulator using existing device profiles with which you probably have some degree of familiarity. The last script, runMyDevice.bat, is used to run the emulator with an entirely custom device. You learn how to create a custom device and use it with the Motorola emulator on Day 6.

Getting back to the device profiles for Motorola devices, following is an example of executing the PaddleBall example MIDlet in the emulator using the runMotoiDEN.bat script:

runMotoiDEN com.mot.j2me.midlets.paddleball.PaddleBall

Figure 3.6 shows the result of this command, which reveals a photo-realistic Motorola iDEN phone in the emulator.

Figure 3.6 The paddleball midlet is executed in the motorola emulator using the motorola iden phone.

The Sample MIDlets

Similar to the J2ME Wireless Toolkit, the Motorola SDK for J2ME includes several sample MIDlets that you can try out using the Motorola emulator. Following are the sample MIDlets that ship with the Motorola toolkit:

  • Bounce—An animation demonstration

  • PaddleBall—A paddle ball game

  • Scribble—A demonstration of drawing with basic graphics

  • FontDemo—A demonstration of using fonts

  • GraphicsDemo—A demonstration of several graphics features

  • RecordStoreDemo—A database demonstration

  • AlertTest—A demonstration of timed and modal alerts

  • ChoiceGroupTest—A demonstration of the choice group GUI component

  • DateFieldTest—A demonstration of the date field GUI component

  • FormTest—A demonstration of forms

  • GaugeTest—A demonstration of the gauge GUI component

  • KeyEventsTest—A demonstration of handling key events

  • TextBoxTest—A demonstration of the text box GUI component

  • TextFieldTest—A demonstration of the text field GUI component

  • TickerTest—A demonstration of the ticker GUI component

  • UDP Tutorial MIDlets—Two MIDlets that demonstrate UDP network communication

All of the MIDlets can be tested using any of the runXXX.bat Motorola script files.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020