j2me

60
Mobile Computing and J2ME Creating MIDlets Activities J2ME , PHP and MySQL Creating a User-Interface Topics Quit J2ME Programming By Engr. Rey Buesing

Upload: ibong-tagapagtanggol

Post on 21-Jul-2016

13 views

Category:

Documents


4 download

DESCRIPTION

lecture for Distributed System

TRANSCRIPT

Page 1: J2ME

Mobile Computing and J2ME

Creating MIDlets

Activities

J2ME , PHP and MySQL

Creating a User-Interface

Topics

Quit

J2ME Programming

By

Engr. Rey Buesing

Page 2: J2ME

Small Computing Devices

About J2ME

Back to Main Options

MobileComputing and J2ME

Topics

Mobile Applications

Configuration

Profiles

About MIDP

CTest

Page 3: J2ME

Process of MIDlet Creation

Using J2ME Wireless ToolKit

Back to Main Options

CreatingMIDlets

Topics

Software Tools

The MIDlet Lifecycle

Midlet and Midlet Suites

Using NetBeans’ IDE

Hands-on Exercises

Page 4: J2ME

INTRODUCTIONSmall Computing Devices A computing device that has limited processor speed and/or available memory when compared to a desktop or server computer. Example: PDA Some computing devices are meant to be embedded in another system - with no explicit human interactions.

Characteristics of Small Computing Devices: Limited memory and storage capacity Slower processing speed Applies alternative input and output methods

- touch sensitive screen for I/O- use QWERT keyboard , add-ons keyboard, or keypad- limited display screen

Page 5: J2ME

INTRODUCTION

Form factor ( physical size, shape, and weight )- influences the choice of I/O methods and hardware.- influences placement of devices’ batteries .- important in embedded systems . The smaller the device the easier it is to integrate into a larger system.

Networking - classification:• devices without permanent network connections.• devices with permanent network connection or

Always Available Devices.- enables the device to access external data and share

data.- allows the device to offload data and computations to a more powerful device.- with throughput and cost limitations.

Page 6: J2ME

INTRODUCTION

Programming Strategies For Small Devices Move computations to the server Simplify the application Build smaller application Use less memory at run time

- use scaler types like int, char, boolean, etc.- do not depend on the garbage collector- help the garbage collector- use lazy instantiation- free resources early- avoid exceptions

Code with performance in mind- use local variables- avoid string concatenations

Page 7: J2ME

INTRODUCTIONWhat is a Mobile Application ? Mobile applications or mobile apps are applications developed for small handheld devices, such as mobile phones, smartphones, PDAs and so on. Mobile apps can come preloaded on the handheld device as well as can be downloaded by users from app stores or the Internet. You can find mobile apps on both feature phones and smartphones. The most popular smartphone platforms that support mobile apps are Windows Mobile, Android, Symbian, Java ME and Palm.

Examples:• Games• Music• IM

Page 8: J2ME

INTRODUCTION Developing Mobile Apps Using J2ME

J2ME is an acronym for Java 2 Platform Micro Edition. J2ME is Sun Microsystems' answer to a consumer wireless

device platform. J2ME allows developers to use Java and the J2ME wireless

toolkit to create applications and programs for wireless and mobile devices.

Elements of J2ME1. Configurations provide a set of libraries and a virtual

machine for a category of wireless device. There are two configurations for J2ME, one for fixed wireless devices and one for mobile wireless devices.

Page 9: J2ME

INTRODUCTION

2. Profiles are APIs built on top of configurations to provide a runtime environment for a specific device, such as a PDA, cellphone, or set-top box.

Page 10: J2ME

INTRODUCTION The Purpose of Configuration

Configuration defines the minimum requirements for memory, virtual machine support, language support, and runtime libraries.

It defines the common and predictable behavior for a family of devices.

Applications are guaranteed to be portable across devices that support the same configuration.

Page 11: J2ME

INTRODUCTION Configurations For J2ME1. Connected Limited Device Configuration or CLDC This configuration is targeted at devices with extreme limitations when compared to the memory and power requirements of a conventional Java implementation.2. Connected Device Configuration or CDC CDC targets devices that are less limited in terms of power, memory, and network bandwidth than those targeted by CLDC. CDC is perhaps considered a stripped-down J2SE. Programs written to the specifications of CLDC will also run on the CDC.

Page 12: J2ME

INTRODUCTION The Purpose of a Profile A profile defines programming interfaces ( APIs ) for devices that have similar uses. The profile manages the application, user-interface , networking and I/O It can also impose additional limitations on the types of devices with which it will work.

In order to support Java apps, manufacturers need to implement a profile for their specific devices.

Page 13: J2ME

Configuration

INTRODUCTION How Profiles Are Used

Java Application

Native APIs

Profile

Native OS

Device

Page 14: J2ME

INTRODUCTIONAbout MIDP

Short for Mobile Information Device Profile MIDP is a set of J2ME APIs that define how

software applications interface with cellular phones and two- way pagers

Applications conforming to this standard are called MIDlets

An MIDP provides APIs in the following areas: Defining and controlling applications Displaying text and graphics and responding to user events Storing data in simple databases Network connectivity via a subset of HTTP

Page 15: J2ME

INTRODUCTION

Companies that have worked on the MIDP Ericsson NEC Nokia Palm Computing Research In Motion (RIM) LG TeleCom Samsung Motorola

Page 16: J2ME

INTRODUCTIONMIDlets and MIDlet Suites MIDlets are applications that only use APIs defined by the MIDP and CLDC. It is a Java class that extends an abstract class named MIDlet and applies the startApp, destroyApp, and pauseApp() methods. MIDlet suite is a set of MIDlets that are packaged together in a single JAR file. MIDlets defined in the same suite can share data and code.

Format of a MIDlet Java Programimport javax.microedition.midlet.*;public class ClassName extends MIDlet { // Declare global variables and // form objects here

void startApp() { // place code here } void pauseApp() { // place code here } void destroyApp( boolean unconditional ) { notifyDestroyed(); }}

Page 17: J2ME

CREATING MIDLETS

Design

Code

Compile

Deploy

Test

Package

Understanding the Process of MIDlet CreationDesign - MIDlets are different from other applications because they run in an environment that is very different. Issues like interactivity and usability must be considered.Code - each MIDlet must extend the abstract MIDlet class found in the javax.microedition.midlet package, much like creating an applet by extending the java.applet.Applet class. Compile, Preverify, Package - these processes can be done from the console or by using Java’s WTK or NetBeans IDE.Test - before deployment, a MIDlet must be tested using a base emulator that mimics the target device . Deploy - copying of the application to actual device. Two Ways of Deployment: - using a USB cable or a Bluetooth

- through the internet

Preverify

Page 18: J2ME

CREATING MIDLETS

The MIDlet LifecycleMobile devices, whether emulators or real, interact with a MIDlet using their own software, which is called Application Management Software (AMS).

Functions of AMS: AMS is responsible for initializing, starting, pausing, resuming, and destroying a MIDlet.

States of a MIDlet: - active - paused - destroyed

AMS

MIDlet

Paused

MIDlet

Active

MIDlet Destro

yed

startApp()

pauseApp()

destroyApp() destroyApp()

new () *

Page 19: J2ME

CREATING MIDLETS Software Development Tools 1. Text Editors - for creating and editing source code.

Example: Notepad, Wordpad, Edit.exe ( console ) , Notepad ++

2. J2ME Wireless Toolkit - for creating projects, compiling, verifying, packaging, and testing of MIDlets.

- it contains tools that are important in generating MIDlets - it provides the development environment for the MIDP 2.0 and CLDC 1.1 and for MIDP 1.0 and CLDC 1.0. - it provides the optional packages required for the optional libraries, like 3D and Mobile Media applications.

Page 20: J2ME

CREATING MIDLETS 3. NetBeans IDE - a fully interactive software development tool

that can provide complete assistance , from coding phase to deployment phase.

The Wireless Toolkit and NetBeans requires JDK development kit version 1.4.2 or greater to be installed.

Page 21: J2ME

CREATING MIDLETS Using J2ME Wireless ToolKit

Steps in Creating a MIDlet Project

Step #1: Click New Project or Click File then click New Project

Page 22: J2ME

CREATING MIDLETS Using J2ME Wireless ToolKit

Steps in Creating a MIDlet Project

Step #2: Choose the target Configuration and Profile

Page 23: J2ME

CREATING MIDLETSUsing J2ME Wireless ToolKitSteps in Creating a MIDlet Project

Upon completion, WTK createsseparate folders forthe project’s source code and library files .

Note: You can now create the program using an editor program and save it to the project’ssource code folder.

Page 24: J2ME

CREATING MIDLETS // A simple MIDlet program that can display student gradesimport javax.microedition.lcdui.*;import javax.microedition.midlet.*;public class Grades extends MIDlet implements CommandListener { // Create Variables String sna = “Juan Dela Cruz”; float pg = 60, mg = 60 , fg = 90; // Create a Display Object for output Display display; // Create a Form Object Form form; // Create Command Objects Command exitCmd = new Command("Exit",Command.STOP,1);

void startApp() { display = Display.getDisplay(this); displayGrade(); } public void pauseApp() { }

Midlet Program #1: Grades.java Part 1/2

Global

Page 25: J2ME

CREATING MIDLETS

void destroyApp( boolean unconnditional ) { notifyDestroyed(); } void commandAction(Command c, Displayable d) { String label = c.getLabel(); if( label.equals("Exit")) destroyApp(true); } void displayForm() { form = new Form("Student Grades"); form.append(“Student Name : “ + sna); form.append(“\nPrelim Grade: “ + pg ); form.append(“\nMidterm Grade: “ + mg); form.append(“\nFinal Grade : “ + fg); form.addCommand(exitCmd); display.setCurrent(form); } }

Midlet Program #1: Grades.java Part 2/2

Page 26: J2ME

CREATING MIDLETSUsing J2ME Wireless ToolKitCompiling and Running a MIDletProject

Steps:1. Click Build to compile.2. Click Run to test the program using an emulator.

Page 27: J2ME

CREATING MIDLETSUsing The J2ME Wireless ToolKitCompiling and Running a MIDletProject

Output of MIDlet Grades.java

Page 28: J2ME

CREATING MIDLETSUsing The J2ME Wireless ToolKitChanging theEmulator

Select the desired emulator then rerun the project

Page 29: J2ME

CREATING MIDLETSUsing The J2ME Wireless ToolKitCreating a Package Click Project then select Create Package

Page 30: J2ME

CREATING MIDLETSDeploying a MIDlet Package

Device

Web Server

Page 31: J2ME

CREATING MIDLETSUsing NetBeans Steps in Creating a MIDlet Project

Steps: 1. Click New Project or Click File then click New Project 2. Select Java ME 3. Select Mobile

Application4. Click Next

Page 32: J2ME

CREATING MIDLETSUsing NetBeans Steps in Creating a MIDlet ProjectSteps:

5. Type Project Name.

6. Set location ofthe project.

7. Click Set as Main Project.8. Unselect

Create HelloMIDlet.

9. Click Finish.

Page 33: J2ME

CREATING MIDLETSUsing NetBeans Adding a MIDletto a Java ME Project

Steps: 1. Locate the newly

created project from Project

Group then right-click<default package>.

2. Click New then click MIDlet.3. Click Next or Finish

Page 34: J2ME

CREATING MIDLETSUsing NetBeans Adding a MIDletto a Java ME Project

Steps: 4. Type the name of

the MIDlet.5. Give the MIDlet’s

class name .6. Specify the location

and file name for the MIDlet’s ICON.7. Specify name of

package.8. Click Finish

Page 35: J2ME

Using NetBeans Adding a MIDletto a Java ME Project

Upon completion, NetBeans adds the newly created MIDlet intothe project’sSource Packages.

A template for theMIDlet’s sourcecode is also created

CREATING MIDLETS

Page 36: J2ME

Using NetBeans Creating/EditingMIDlets

You can now type and the source code for the Grades MIDlet using NetBeans’ Built-in editor.

CREATING MIDLETS

Page 37: J2ME

Using NetBeans Compiling andRunning a MIDlet

You can compile and test the current MIDlet by clicking the RUN icon.

Clicking the RUNicon will launch the emulator .

CREATING MIDLETS

Page 38: J2ME

Using NetBeansChanging theEmulator

Steps:1. Right-click the name of the project from the Project Group then click Properties.2. Click Emulator

Platform Type.3. Select desired

emulator4. Click OK.

CREATING MIDLETS

Page 39: J2ME

Using NetBeansCreating a Package For Deployment Right-click the project’s name from the Project Group then click Deploy

CREATING MIDLETS

Page 40: J2ME

Using Display

Screens

Back to Main Options

Creatinga

User Interface

Topics

Tickers

Event Handling

MIDP User Interface Classes

Using List

Forms

Page 41: J2ME

MIDP User Interface Classes The device’s display, as seen by the MIDlet, is represented by an instance of the Display class, accessed from a named getDisplay(). Display’s main purpose in life is to keep track of what is currently shown, which is an instance of Displayable. MIDlets can change the contents of the display by passing Displayable instances to Display’s setCurrent()method.

Basic function of a typical MIDlet:1. Show a Displayable.2. Wait for input.3. Decide what Displayableshould be next.4. Repeat.

CREATING A USER INTERFACE

Page 42: J2ME

MIDP User Interface ClassesDisplayable has a small family of subclasses that represent various types of user interfaces.

CREATING A USER INTERFACE

Page 43: J2ME

Using DisplayDisplay manages a device’s screen. References to the device’s display can be made by supplying a MIDlet reference to the static getDisplay() method. Example: public void startApp() { Display d = Display.getDisplay(this); // ... }

Display’s setCurrent() methods: public void setCurrent(Displayable next) public void setCurrent(Alert alert, Displayable nextDisplayable)

The second version is used when you want to show a temporary message (an Alert) followed by something else.

CREATING A USER INTERFACE

Page 44: J2ME

Event Handling with CommandsA commandis something the user can invoke similar to a GUI button. Like a button, it has a title, like OK or Cancel, and application can respond appropriately when the user invokes the command.

Every Displayable keeps a list of its Commands. You can add and remove Commands using the following methods: public void addCommand(Command cmd) public void removeCommand(Command cmd )

Syntax For Creating Commands Command name = new Command (label., type, priority ).

The type can be used to signify a commonly used command. It must be one of the values defined in the Command class.

CREATING A USER INTERFACE

Page 45: J2ME

Event Handling with Commands

Command TypesName MeaningOK Confirms a selectionCANCEL Cancels pending changesBACK Moves the user back to a previous screenSTOP Stops a running operationHELP Shows application instructionsSCREEN Indicates generic type for specific application commands

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

CREATING A USER INTERFACE

Page 46: J2ME

Event Handling with Commands

Responding to Commands

Example: Form form = new Form(“New Form”); Display display = Display,getDisplay(); Command ok = new Command(“OK”,Command.OK,0); form.addCommand(d); form.setCommandListener(this); display.setCurrent(form);

CREATING A USER INTERFACE

Page 47: J2ME

Tickers

A ticker is simply a bit of text that scrolls across the top of a Displayable.

TheTickerclass is a simple wrapper for a string.

Example: Form form = new Form(“New Form”); Display display = Display,getDisplay(); Ticker ticker = new Ticker("This is the ticker message!"); form.setTicker(ticker); display.setCurrent(form);

CREATING A USER INTERFACE

Page 48: J2ME

ScreensScreen is the base class for all classes that represent generalized user interfaces. This class has no methods of its own, but inherits all from Displayable.

TextBoxThe simplest type of screen is the TextBox, which you’ve already seen in action. TextBox allows the user to enter a string.

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

The title is used as the screen title, while textand maxSizedetermine the initial text and maximum size of the text box.

CREATING A USER INTERFACE

Page 49: J2ME

Screens

Constraints : ANY, NUMERIC, DECIMAL, PHONENUMBER, EMAILADDR, or URL Flags: PASSWORD, UNEDITABLE, SENSITIVE, NON_PREDICTIVE, INITIAL_CAPS_WORD, INITIAL_CAPS_SENTENCE

Example: Display display = Display.getDisplay(this); TextBox tb = new TextBox( “Student Name”, 25, TextBox.ANY | TextBox.INITIAL_CAPS ) ; display.setCurrent(tb);

CREATING A USER INTERFACE

Page 50: J2ME

Screens

Alerts An alert is an informative message shown to the user.

Two types of alert: • A timed alert is shown for a certain amount of time, typically just a few seconds. It displays an informative message that does not need to be acknowledged. Example: Alert timedAlert = new Alert(“Greeting", “Good Day !”, null, null); timedAlert.setTimeout(5000); display,setCurrent(timedAlert);

CREATING A USER INTERFACE

Page 51: J2ME

Screens

• A modal alert stays up until the user dismisses it. Example: Alert modalAlert = new Alert(“Greeting", “Good Day !”, null, null); modalAlert.setTimeout(Alert.FOREVER); display,setCurrent(modalAlert);

CREATING A USER INTERFACE

Page 52: J2ME

Using Lists

After TextBox and Alert, the next simplest Screen is List, which allows the user to select items (called elements) from a list of choices. A text string or an image is used to represent each element in the list. List supports the selection of a single element or of multiple elements.

There are two main types of List, denoted by constants in the Choice interface:

• MULTIPLE designates a list where multiple elements may be selected simultaneously.• EXCLUSIVE specifies a list where only one element may be selected. It is akin to a group of radio buttons.

CREATING A USER INTERFACE

Page 53: J2ME

Using Lists

Event Handling for IMPLICIT Lists When the user makes a selection in an IMPLICIT list, the commandAction() method of the list’s CommandListener is invoked. A special value is passed to commandAction()

Example: public void commandAction(Command c, Displayable d) { if (c == nextCommand) // ... else if ( c == List.SELECT_COMMAND) // ... }

CREATING A USER INTERFACE

Page 54: J2ME

Using Lists

Creating Lists To create a List, specify a title and a list type. If you have the element names and images available ahead of time, you can pass themin the constructor: public List(String title, int type) public List(String title, int type, String[] stringElements, Image[] imageElements)

Example: List menu = new List ( “Main Options”, Choice. IMPLICIT ); menu.append(“Option 1”); menu.append(“Option 2”);

CREATING A USER INTERFACE

Page 55: J2ME

Creating Forms

A Form is a screen that can include an arbitrary collection of user-interface controls, called items.

Forms should be as small as possible.

One way to create a Form is by specifying a title: public Form(String title)

Example: Form form = new Form(“Login Section”);

CREATING A USER INTERFACE

Page 56: J2ME

Creating Forms

Form-related Objects: Spacer represents empty space in a Form. Unlike other Items, Spacer cannot gain focus and cannot have commands. It may be used for layout purposes. Example: Spacer spc = new Space( 10, 20 ) ;

TextField represents an editable string. Example: TextField tf = new TextField(“Enter a password”,” ”, 10, TextField.PASSWORD);

CREATING A USER INTERFACE

Page 57: J2ME

Creating Forms

DateField is an extremely handy mechanism by which users can enter dates, times, or both. It’s up to the implementation to determine some reasonable way for users to enter dates and times; To create a DateField, specify a label and a type. Three constants in the DateFieldclass describe the different types: • DATEdisplays an editable date. • TIMEdisplays an editable time. • DATE_TIMEdisplays both a date and a time.

CREATING A USER INTERFACE

Page 58: J2ME

Creating Forms

DateField provides two constructors. The first uses the default time zone, while the second allows you to specify a TimeZone explicitly: public DateField(String label, int mode) public DateField(String label, int mode, TimeZone timeZone )

CREATING A USER INTERFACE

Page 59: J2ME

Creating Forms

ChoiceGroup offers a list of choices. It is very similar to javax.microedition.lcdui.List. This similarity is more than coincidental; ChoiceGroupand List both implement the Choiceinterface, which is the wellspring of all of the instance methods in both classes. ChoiceGroup features the following constructors: public ChoiceGroup(String label, int choiceType) public ChoiceGroup(String label, int choiceType, String[] stringElements, Image[] imageElements)

CREATING A USER INTERFACE

Page 60: J2ME

Creating Forms

Example: String[] sem = {"1","2","S"}; ChoiceGroup semGrp = new ChoiceGroup( "Choose Semester",Choice.EXCLUSIVE,sem,null); form.append(semGrp);

CREATING A USER INTERFACE