lab 2 j2me java 2 micro edition writing programs for mobile phones using java l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Lab 2: J2ME: Java 2 Micro Edition (Writing Programs for Mobile Phones using Java) PowerPoint Presentation
Download Presentation
Lab 2: J2ME: Java 2 Micro Edition (Writing Programs for Mobile Phones using Java)

Loading in 2 Seconds...

play fullscreen
1 / 62

Lab 2: J2ME: Java 2 Micro Edition (Writing Programs for Mobile Phones using Java) - PowerPoint PPT Presentation


  • 325 Views
  • Uploaded on

MIT D-Lab ICT4D. Lab 2: J2ME: Java 2 Micro Edition (Writing Programs for Mobile Phones using Java). Luis F. G. Sarmenta originally delivered: 3/13/2008 draft 2: 4/10/2008. Recap: Mobile Phone Capabilities, Apps. SMS (Text Messaging) –based services send text commands, receive info

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Lab 2: J2ME: Java 2 Micro Edition (Writing Programs for Mobile Phones using Java)' - rhona


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
lab 2 j2me java 2 micro edition writing programs for mobile phones using java

MIT D-Lab ICT4D

Lab 2: J2ME: Java 2 Micro Edition(Writing Programs for Mobile Phones using Java)

Luis F. G. Sarmenta

originally delivered: 3/13/2008draft 2: 4/10/2008

recap mobile phone capabilities apps
Recap: Mobile Phone Capabilities, Apps
  • SMS (Text Messaging) –based services
    • send text commands, receive info
    • receive alerts and subscriptions
  • MMS (Multimedia Messaging) –based services
    • send and receive multimedia to/from server
  • J2ME (Java 2 Micro Edition) applications
    • programs running on the phone
    • e.g., games
  • Internet/Web services
    • via WAP (limited) and/or GPRS (dialup-speed connection)
    • via 3G (broadband speed connection)
  • Location-based services
    • services that make use of location of users
  • Micropayment applications
    • ability to send/transfer cellphone credits via SMS
    • leads to cash-less, credit-card less, electronic payment mechanisms
what is j2me for
What is J2ME for?
  • Writing Programs that run on the phone
    • no need to be connected online
    • uses processor and interface of phone
  • Applications
    • Games
      • for fun, but can be educational
    • Calculation / Computation tools
      • e.g., medical calculators, etc.
    • Provide a better user interface to a service
      • e.g., Maps for mobile (Google, Microsoft, et al)
      • can be useful for data forms
what j2me lets you do
What J2ME lets you do
  • Computation / logic
    • general-purpose language
    • limited only by processor speed and memory
  • Graphics
    • including 3D on new phones
  • Connectivity
    • SMS, MMS, Bluetooth, HTTP
  • Other Features
    • NFC/RFID, Location, etc.
  • “Write Once Run Anywhere”
    • … IF you write your program well, AND your device supports all optional features you use
deployment and business model
Deployment and Business Model
  • Development or Free Use
    • via Bluetooth, cable, or infrared
    • “free” download over the web via GPRS/3G
      • download the jad file first, which makes phone download the jar file
      • Note: you may pay traffic cost
      • Some MNO’s may not allow this
  • Commercial deployment
    • packaged with phone
    • download from the MNO
    • download from a software vendor/aggregator’s web site
    • request by SMS
    • (all of these usually require network connectivity, but may not charge you traffic cost)
references
Note: Our lab sessions for this class are only meant to jump-start you and get you on your way. You should read further on your own!

Book (Highly Recommended!)

Li and Knudsen. Beginning J2ME: From Novice to Professional, Third Edition. Published by Apress.(http://www.apress.com/book/view/1590594797)

Examples

The Sun Wireless Toolkit has many examples!

See also http://java.sun.com/javame/reference/

See also source code download available from Apress

Some Lecture Notes by Others

http://eprom.mit.edu/education.html

http://web.mit.edu/21w.780/www/spring2007/

References
tools
Tools
  • Java
  • Sun Wireless Toolkit
  • Eclipse
  • EclipseME
mobile phone for our labs thanks to nokia research center cambridge
Mobile Phone for Our Labs(Thanks to Nokia Research Center Cambridge!)
  • N82 and N95
    • camera, 3G, GPS, TV out
  • E61i
    • QWERTY keyboard
  • 6131 NFC
    • mid-range phone with NFC (contactless RFID) reader
  • N810
    • Internet tablet (not a phone)
    • hi-res screen, GPS, camera, QWERTY, etc.
  • 2610
    • low-end phone
    • only $9.99 for an official refurb unit, no contract!
why high end phones
Why High-End Phones?
  • You can always simulate a low-end phone with a high-end phone … but not the other way around
  • For some projects, using high-end phones is OK, since only a few people (e.g., health workers) need to have these
  • Also … prices will inevitably go down in the future
  • In any case, we will encourage designing solutions that have the broadest impact
    • e.g., SMS-based services and platform-independent J2ME
basics

Basics

adapted from MIT AITI lecture to high school students in Kenyaby Mike Gordon (MIT)

Summer 2007

compilation for j2me
Compilation for J2ME
  • Extra steps versus desktop Java:
    • Compilation using Java compiler
      • Must include the J2ME Java libraries
    • Pre-verification of bytecode
    • Package the classes application for deployment
      • Create a jar archive of the class files
  • All this is done for you in the Java Wireless Toolkit
terminology
Terminology

Soft Buttons

Navigation (Arrow) Buttons

Select (OK) Button

cldc midp applications
CLDC/MIDP Applications
  • All cell phone applications inherit from the MIDlet class
    • javax.microedition.midlet.MIDlet
  • The MIDlet class defines 3 abstract methods that the cell phone app must override:
    • protected abstract void startApp();
    • protected abstract void pauseApp();
    • protected abstract void destroyApp(boolean unconditional);
midlets
MIDlets
  • These methods are called by the J2ME runtime system (interpreter) on your phone.
    • startApp(), when application is started
    • pauseApp(), when application is paused
    • destroyApp(boolean) when application is exited
life cycle of a midlet
Life Cycle of a MIDlet

Constructor

destroyApp()

Paused

pauseApp()

startApp()

destroyApp()

Active

Destroyed

differences between j2se and j2mep
Differences Between J2SE and J2MEP
  • No floating point (before CLDC 1.1)
  • System.out.print/println don’t do anything on real phone
  • Subset of java.lang
    • Limited implementation of many classes
  • Very limited java.util / java.io
  • Make sure you are reading the JavaDoc for the J2ME MIDP when you are developing!
the midlet philosophy
The MIDlet Philosophy
  • Abstraction:
    • Specify the user interface in abstract terms
    • Just specify the components to add
    • A limited set of predefined components
    • Let the MIDP implementation decide on the placement and appearance
  • Example
    • add a “Done” command somewhere on the screen
the midlet philosophy20
The MIDlet Philosophy
  • The device’s display is represented by an object of the Display class
    • Think of it as an easel
  • Objects that can be added to a Display are subclasses of Displayable
    • Canvas on the easel
  • MIDlets change the display by calling setCurrent(Displayable) in Display
the midlet philosophy21
The MIDlet Philosophy

Show a Displayable with something on it

Wait for input from user

Decide what Displayable to show next and what should be on this Displayable.

Go to 1.

the displayable hierarchy
The Displayable Hierarchy

Displayable

Canvas

Screen

Alert

List

Form

TextBox

  • The Screen sub-classes are abstract, meaning it is up the MIDP implementation to decided on their appearance
  • All these classes are defined in javax.microedition.lcdui
commands
Commands

Commands

  • A command is something the user can invoke
  • We don’t really care how it is shown on the screen
  • Example:
    • Command c = new Command(“OK”, Command.OK, 0);
  • You can add commands to a Displayable using:
    • public void addCommand(Command)
responding to command events
Responding to Command Events
  • When a Command is invoked by the user, a method is called to service the command
  • The exact method is:
      • public void commandAction( Command c, Displayable d)
      • c is the Command invoked and d is the Displayable the Command was added to.
responding to command events26
Responding to Command Events
  • We need to tell the Displayable the object in which to call commandAction()
  • Two Steps:
    • The class of the object must implement the interface CommandListener
      • CommandListener defines commandAction()
    • You tell the Displayable which object by calling setCommandListener(CommandListener) on the Displayable
example
Example

import javax.microedition.lcdui.*;

import javax.microedition.midlet.MIDlet;

public class HelloWorld extends MIDlet implements CommandListener {

private static Command CMD_EXIT = new Command("Exit", Command.EXIT, 0);

private static Command CMD_NEXT = new Command("Next", Command.OK, 0);

private TextBox textBox1;

private TextBox textBox2;

example28
Example

public void startApp()

{

textBox1 = new TextBox("TextBox1",

"The first Displayable", 30, TextField.ANY);

textBox1.addCommand(CMD_NEXT);

textBox1.setCommandListener(this);

textBox2 = new TextBox("TextBox2",

"The second Displayable", 30, TextField.ANY);

textBox2.addCommand(CMD_EXIT);

textBox2.setCommandListener(this);

Display.getDisplay(this).setCurrent(textBox1);

}

example29
Example

public void commandAction(Command c, Displayable d)

{

if (d == textBox1 && c == CMD_NEXT)

Display.getDisplay(this).setCurrent(textBox2);

else if (d == textBox2 && c == CMD_EXIT)

notifyDestroyed();

}

public void pauseApp()

{

}

public void destroyApp(boolean u)

{

}

forms
Forms
  • A form includes collection of UI controls called Items

public Form(String title)

public Form(String title,Item[] items)

  • public int append()
  • public void set(int index,Item item)
  • public void delete(int index)
  • public void deleteAll()
  • public int size()
  • public Item get(int index)
forms example
Forms example
  • Form form = new Form(“Form Title”);
  • StringItem strItem = new StringItem(“Label:”, “Value”);
  • form.append(strItem);
forms items
Forms - Items
  • String , textfield, image Items, datefield
  • Choice Group – similar to Lists before
  • events and item changes as well
  • Can create custom items to use on your own and now you can build up almost any type of UI component to make your needs
example form and sms
Example: Form and SMS

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;

publicclass Hello extends MIDlet implements CommandListener {

privatestatic Command CMD_EXIT = new Command("Exit", Command.EXIT, 0);

privatestatic Command CMD_OK = new Command("OK", Command.OK, 0);

private Form form;

private TextField textField;

public Hello() {

}

protectedvoid destroyApp(boolean arg0) throws MIDletStateChangeException {

}

protectedvoid pauseApp() {

}

protectedvoid startApp() throws MIDletStateChangeException {

form = new Form("");

textField = new TextField("Name", "", 20, TextField.ANY);

form.append(textField);

form.addCommand(CMD_EXIT);

form.addCommand(CMD_OK);

form.setCommandListener(this);

Display.getDisplay(this).setCurrent(form);

}

publicvoid okPressed() {

SMSLibrary.sendShortMessage("Hello " + textField.getString(), "6174606583");

}

publicvoid commandAction(Command c, Displayable d) {

if (c == CMD_OK) {

okPressed();

} elseif (c == CMD_EXIT) {

notifyDestroyed();

}

}

}

some notes
Some Notes
  • Don’t forget to add the Midlet class file to the list of Midlets in the jad
  • Make sure Java Compiler is set to generate 1.1 code
sms and messaging api
SMS and Messaging API
  • For simple sending, just use the SMSLibrary class we provide for you
  • See Knudsen book for more details and more advanced features
    • receiving SMS
    • sending and receiving MMS
    • binary SMS
    • etc.
nfc contactless
NFC (Contactless)
  • NFC – Near Field Communications
    • communicate with contactless / “RFID” devices
  • Supported by Nokia 6131 NFC phone and a few others
  • Reading Unique ID is simple
  • You can also send more complex commands to the NFC
  • Download Nokia 6131 NFC SDK from forum.nokia.com
  • Get NFC tags from Rich Fletcher
other features40
Other Features
  • GUI Controls and Graphics
  • Location
  • Security
  • Bluetooth
  • Web
  • etc.
  • See Knudsen book for Bluetooth and Web access
  • See Sun Wireless Toolkit Examples for other examples
exercise
Exercise
  • Collect user’s input and send it via SMS to server
    • no need to receive the SMS via J2ME for now
j2me basic gui programming

J2ME Basic GUI Programming

from MIT AITI lecture in Kenyaby Mike Gordon (MIT)

Summer 2007

j2me gui
J2ME GUI
  • Idea: Use abstractions to support many different mobile devices, different screen sizes, colors, different input types
  • Displayables
    • Alerts
    • Lists
    • Form
    • TextBox
textbox
Textbox
  • allows the user to enter a String (zipcode,name,password)
  • depending on input may be a tedious process

public TextBox(String title, String text, int maxSize, int constraints)

  • title = screen title
  • text = initial text on screen
  • maxSize = maximum size of text box
  • constraints – restrict input
textbox constraints
TextBox - Constraints
  • Constrain the input characters
    • TextField.ANY – allows any type of input supported by the device
    • TextField.NUMERIC– restricts to only integers
    • TextField.DECIMAL– allows numbers with fractional parts
    • TextField.PHONENUMBER – requires a telephone number
    • TextField.EMAILADDR – requires an email address
    • TextField.URL – requires a web address
text box flags
Text Box - Flags
  • Flags define behaviour, opposed to restricting it
    • TextField.PASSWORD
    • TextField.UNEDITABLE
    • TextField.SENSITIVE
    • TextField.NON_PREDICTIVE
    • TextField.INITIAL_CAPS_WORD
    • TextField.INTIAL_CAPS_SENTENCE
  • No Validation than use TextField.ANY and 0 for constraints parameter
text box flags47
Text Box - Flags
  • Combine flags and constraints with | (or)

Displayable d =

new TextBox(“Email”,64,TextField.ANY | TextField.PASSWORD);

alerts
Alerts
  • alert types: ALARM, CONFIRMATION,ERROR,INFO, and WARNING
  • timed – certain amount of time – “Your transaction complete”
  • modal – until user dismisses it – “are you sure you want to quit?” “exit without saving?”
alerts49
Alerts

public Alert() or

public Alert(String title, String alertText, Image alertImg, AlertType alertType)

  • any or all parameters can be null
  • default timeout , but can change timeout length
  • Forever timeout means that it is modal
alerts50
Alerts
  • You can create an alert with:

Alert alt = new Alert(“Sorry”, “I Am sorry Dave”, null, null);

  • Set the timeout to 5 seconds by:

alt.setTimeout(5000);

  • Make it a modal alert by:

alt.setTimeout(FOREVER);

lists
Lists
  • users select items (called elements) from choices
  • Exclusive -Single Selection – ex. radio buttons
  • Multiple – Multiple Selection – ex. check list
  • Text String or image is used to represent each element
lists52
Lists

Exclusive Multiple

creating lists
Creating Lists

public List(String title, int type)

public List(String title, int type,String[] stringElements, Image[] imageElements)

modifying lists
Modifying Lists
  • public void set(int elementNum, String stringPart, Image imagePart)
  • public void insert(int elementNum, String stringPart, Image imagePart)
  • public int append(String stringPart, Image imagePart)
modifying lists55
Modifying Lists
  • public String getString(int elementNum)
  • public String getImage(int elementNum)
  • public void delete(int elementNum)
  • public void deleteAll()
  • public boolean isSelected(int index)
  • public int getSelectedIndex()
  • public void setSelectedIndex(int index, boolean selected)
forms56
Forms
  • A form includes collection of UI controls called Items

public Form(String title)

public Form(String title,Item[] items)

  • public int append()
  • public void set(int index,Item item)
  • public void delete(int index)
  • public void deleteAll()
  • public int size()
  • public Item get(int index)
forms example57
Forms example
  • Form form = new Form(“Form Title”);
  • StringItem strItem = new StringItem(“Label:”, “Value”);
  • form.append(strItem);
forms items58
Forms - Items
  • String , textfield, image Items, datefield
  • Choice Group – similar to Lists before
  • events and item changes as well
  • Can create custom items to use on your own and now you can build up almost any type of UI component to make your needs
form layout
Form Layout
  • Left to right, rows top to bottom
  • items have labels, and can also have commands
  • set size
  • set layouts for individual items
    • setLayout(); getLayout();
    • LAYOUT_LEFT, LAYOUT_CENTER....
commands60
Commands

To Create a command, you need a name, type and also a priority.

Ex:

Command c = new Command(“OK”, Command.OK, 0);

public void addCommand(Command cmd)

public void removeCommand(Command cmd)

command types
Command Types

There are different types of commands available for you to use:

Command.OK – Confirms a selction

Command.CANCEL – Cancels pending changes

Command.BACK – Moves the user back to a previous screen

Command.STOP – Stop a running operation

Command.HELP – Shows application Instructions

Command.SCREEN – indicates generic type for specific application commands

Command c = new Command("Launch", Command.SCREEN, 0);

j2me gui resources
J2ME GUI Resources

Knudsen and Li. Beginning J2ME: From Novice to Professional, Third Edition. Apress. (http://www.apress.com/book/view/1590594797)

  • http://www.onjava.com/pub/a/onjava/excerpt/wirelessjava_ch5/index1.html
  • http://developers.sun.com/mobility/midp/articles/ui/ - Sun's J2ME GUI tutorial
  • http://www.j2mepolish.org/
    • A powerful dual-license open-source GUI Designer which may be useful for your own projects beyond this course