Introduction To Mobile Phone Programming In Java Me

7m ago
62 Views
0 Downloads
234.72 KB
13 Pages
Transcription

Introduction to Mobile PhoneProgramming in Java Me(prepared for CS/ECE 707, UW-Madison)Author: Leszek Wilandand Suman Banerjee1

Content1. Introduction2. Setting up programming environment3. Hello World Application4. GUI and User Interaction5. Networking2

1. IntroductionIn this tutorial I will explain the main concepts of developing mobile applications in Java Me. Iwill start with setting up programming environment in Windows operating system and thenproceed with showing Java Me programming model on the example of a number of mobileapplicationsJava Me is a specification of a subset of Java platform which provides a set of Java APIs fordevelopment for small and resource-limited devices. Since this can include many technologicallydifferent devices, Java Me is furthermore divided into configurations and profiles which definesome certain part of the Java Me APIs which are suitable to be run on a particular device. MobilePhones have to implement CLDC (Connected Limited Device Configuration) along with MIDP(Mobile Information Device Profile) which both define API which we as programmers can use tobuild mobile applications. However, both CLDC and MIDP come in different versions suitable fordifferent mobile phones. As of now, Nokia N95 implements the newest version of both CLDCwhich is 1.1 and MIDP which is 2.0. It is important to mention that a new 3rd version of MIDP iscurrently under development. Java Virtual Machine for mobile devices has been rewritten and it isnot anymore the memory hungry one well known from PC but has been specially optimized forsmall devices such as mobile phones.2. Setting up programming environmentThere are four main components to be installed in order to start programming in Java for mobiledevices. The first one is Java SE (Standard Edition) Development Kit which you might alreadyhave installed on your machine; the recommended version is 1.5.0. Next you should download andinstall Sun Java Wireless Toolkit for CLDC; current version 2.5.2 which can be found at thefollowing oad.html?feed JSCScroll down to the bottom of the page to find the file. Next install Nokia SymbianOS/S60 SDK forJava. There are multiple versions of this SDK each for a different group of devices. Nokia N95supports the newest version of the SDK: S60 3rd edition, Feature Pack 2 which can be found underthe following id/6e772b17-604b 4081999c31f1f0dc2dbb/S60 Platform SDKs for Symbian OS for Java.html3

Look on the right hand side and chose 3rd Edition FP2v1.1 (455 MB) file for downloading.The last thing to install is Eclipse or some other Integrated Development Environment capable ofworking with Java Me Edition (Java Micro Edition) for example NetBeans with Mobility Pack. Inthis document I will show how to set up a project with Eclipse so if you don't have Eclipse alreadyinstalled on your machine you can find it ops/R-3.2.2-200702121330/index.phpAn additional Eclipse Me plug-in would be needed for Eclipse to work properly with Java ME andit can be found at the following group id 86829Unpack the zip file and copy all the files in plug-ins and features directories to the correspondingdirectories in your Eclipse folder. Having done this, we can proceed to configure Eclipse to workproperly with Java ME and the phone emulator. Firstly, select Window- Preferences and choseJ2ME node and select Device Management. Press import and browse forC:\S60\devices\S60 3rd MIDP SDK FP2 Beta or any other directory you installed the S60SDK, click refresh and make sure that both S60Emulator and S60Device devices' checkboxes arechecked. Press finish and then import again. This time browse for C:\WTK2.5.2 directory, clickrefresh and make sure that all four devices are selected, then press finish. Back in the main dialogselect DefaultColorPhone as the default device. Unfortunately, choosing any other one wouldmake the application fail. Having done that, go to Window- Preferences, expand node Java Build Path, then For item Source and output folder, select the radio button Folders, and keep thedefaults (src and bin). Next expand node Java- Debug and uncheck Suspend execution onuncaught exceptions and Suspend execution on compilation errors, and at the end set Debuggertimeout(ms) to 15000 This is enough to start programming for mobile devices and since we havethe phone emulator it is easy to test anything we have written. However, in order to moveapplications easily from computer to a real phone we would need Nokia PC Suite which does thatfor us. It can be found at:http://europe.nokia.com/pcsuite3. Hello World ApplicationOnce all the elements of the programming environment are installed we are ready to create a firstJava Me application. Start with opening Eclipse and then select File- New- Project. Expand J2Menode and choose J2ME MIDlet Suite. Press next, give the project a unique name and press nextagain, also make sure that in the “Group:” menu, Sun Java Wireless Toolkit is chosen and in“Device” menu DefaultColorPhone is selected. Press next and select “Allow output folders forsource folders” and press finish. Once Java Me project is created we need to add a MIDlet class tothe project which is the heart of each Java Me application. To do so, right click on the project,select New- Other and choose J2ME MIDlet. This will create a skeleton for Java Me application.Generally, any Java Me program for embedded devices such as Nokia smart phones is called a4

MIDlet. There are few differences between Main class of a Standard Java Application and a Mainclass of a Java Me application. First of all, Java Me Main class does not have main() function, butinstead has three empty methods and is derived from MIDlet class (is a subclass of MIDlet class).Each Java Me application has to have a Main class which is derived from MIDlet and contain thefollowing three methods:1. protected void destroyApp(boolean arg0);2. protected void pauseApp();3. protected void startApp();A MIDlet is simply a backbone of the application and when it is started, Java Virtual Machinewould load that Main class and start its startApp() method which in this case acts like the oldmain() function known from Java SE. The destroyApp(boolean arg0) method is called wheneverwe want the application to terminate, whereas the pauseApp() is called by the underlying operatingsystem when it needs to free up some extra resources and would like our application to stopexecuting for some time. This might happen, for example, if there is an incoming call and theoperating system needs to free as much resources as possible to deal with this task. Therefore, ifour application uses a lot of system resources this would be the place to free them up. However, ifwe leave this method empty then no resources will be freed by the operating system.The following simple MIDlet, does not do anything in particular. It is also not capable of any userinteraction whatsoever, and therefore cannot be terminated if started on the mobile phone. If run onthe computer it can be easily killed by closing the simulator window. The"System.out.println("Hello World");" statement will not have any effect when run on the phonesimulator or on the device itself, and therefore cannot be used for printing output. It would beprinted, however, on the Eclipse console and so it is very helpful for debugging.Code 1public class Main extends MIDlet {public Main() {// TODO Auto-generated constructor stub}protected void destroyApp(boolean arg0) {// TODO Auto-generated method stub}protected void pauseApp() {// TODO Auto-generated method stub}protected void startApp() throws MIDletStateChangeException {}System.out.println("Hey");}5

The final step of the development process is to install above Java Me application on mobile device.To do so, we need to generate a jar file which then is copied to the phone. Right click on theproject and select J2ME- Create Package (on the very bottom). This will generate one jar and onejad file, both of which are stored under deployed directory in the Java Me project. Once the outputfiles are ready we will install them on the phone device using Nokia PC Suite application. Firstconnect the device to the computer preferably by USB cable and choose PCSuite from the optionsdisplayed on the device screen. Then start PC Suite application on your machine and select InstallApplication item which is on the left bottom of the application window. Browse for the project jarfile and by pressing an installation arrow between My Computer and My Phone window copy thejar file to the device where you can finish the installation process.4. GUI and User InteractionThere are two ways to build a user interface with Java Me. First and the easiest is using high levelAPI which consists of already created components which can be mixed together in almost anyfashion. The high level API does also take care of displaying it properly on the screen, scrollingthrough the menus if needed and basically make our life much easier. All the components have tobe eventually attached to an object which is derived from Displayable class to be displayed on thescreen. So when using high level API to build a user interface we end up attaching different GUIelements such as TextFields, Buttons, Lists or TextString to an object which is derived fromDisplayable such as Form, then we set that Displayable to be displayed on the screen, and that is it.This means that we can prepare many different user interfaces or menus and switch between themas easily as it is to set a new Displayable to be displayed on the screen. Once we have the GUIready we need to take care of user interaction, and this is done by making one of our classes,preferably MIDlet, to implement CommandListener interface which consists of one method:public void commandAction(Command c, Displayable g);Code 2public class Main extends MIDlet implements CommandListener{6

public Main() {// TODO Auto-generated constructor stub}protected void destroyApp(boolean arg0) {// TODO Auto-generated method stub}protected void pauseApp() {// TODO Auto-generated method stub}protected void startApp() throws MIDletStateChangeException {System.out.println("Hey");}}public void commandAction(Command c, Displayable g) {// TODO Auto-generated method stub}Any time there is a user generated event the commandAction() method is called with Commandand Displayable arguments passed to it. We can respond to the user input by checking whatcommand has been generated and react accordingly. The above MIDlet implementsCommandListener interface but still cannot process any user input since we have not defined anycommands which would let the user to interact with the application. Before proceeding to explainhow to do this I will shortly write about the second way of building GUI which is low level API. Itlets us directly deal with what is displayed on the screen by defining a paint() method which iscalled every time screen has to be refreshed. It also provides a way of capturing any user input,whereas high level API can capture only these event which are directly generated by interactingwith buttons displayed on the screen, therefore it misses all the alphanumeric keys. In order to uselow level API one of the classes has to be derived from Canvas class and implements the paintmethod.protected void paint(Graphics g);The canvas object defines several other method apart from paint() which are used mainly forhandling low level user interface I will primary focus on paint() and keyPressed(). The followingMIDlet demonstrate use of low level API:Code 3public class LowLevelAPI extends Canvas{7

protected void paint(Graphics arg0) {// TODO Auto-generated method stub}protected void keyPressed(int keyCode) {}}Like commandAction() method for high level API we check the keyCode and depending on thekey code take up some specific actions.So far, we know that there are two types of API available for building GUI and that user input canbe handled by either implementing commandAction() or keyPressed() method or both of them.Now I will proceed with showing how to build a simple GUI using high level API. As I mentionedbefore only the elements which are derived from Displayable or Screen can be displayed on thedevice. Screen has 4 main subclasses each of which can be used to build GUI, and when ready, bedisplayed on the screen by setting it as a current Screen. These subclasses are: Alert, List, TextBoxand Form. Alert: is a screen that shows data to the user and waits for a certain period of time beforeproceeding to the next Screen. List: contains a list of choices and the set of methods to query what option have beenselected by the user. TextBox: allows user to input text. Form: can contain an arbitrary mixture of items: images, read-only text fields, editable textfields, editable date fields, gauges, choice groups, and custom items each of which can beattached to the form in any fashion.The implementation handles layout, traversal and scrolling automatically. Apart from these fourderived from the Screen classes there is a number of components derived from Item class, whichcan be attached to a Form and used as a building blocks of the whole GUI.In order to handle user interface we need to define a set of commands which are then attached tothe Displayable. It can be any class which is derived from Displayable, such as: Alert, List,TextBox, Form and also the low level API class: Canvas. Each command is represented by aseparate Command object with a name, command type and the priority. Once we have GUI andcommands defined, we need to register this Displayable object with a CommandListener, which isdone by calling setCommandListener() method on the Displayable object.8

I will show now how to build an application which lets users type a text in one window and print