/
Developing Developing

Developing - PowerPoint Presentation

trish-goza
trish-goza . @trish-goza
Follow
409 views
Uploaded On 2016-03-25

Developing - PPT Presentation

MIDlets Dr Miguel A Labrador Department of Computer Science amp Engineering labradorcseeusfedu httpwwwcseeusfedulabrador Outline MIDlet life cycle Hello World example User interface classes and APIs ID: 268624

command midlet file record midlet command record file exit user application list player public displayable methods jar screen string

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Developing" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Slide1

Developing MIDlets

Dr. Miguel A. LabradorDepartment of Computer Science & Engineeringlabrador@csee.usf.eduhttp://www.csee.usf.edu/~labradorSlide2

Outline

MIDlet life cycleHello World exampleUser interface classes and APIsLists, text boxes, forms, alertsMedia APIRecord Management SystemsSecuritySlide3

MIDlets

Java program compiled using the APIs included in the CLDC and MIDP specificationsAfter compilation, several steps need to be done before using the MIDlet in a real deviceDebugged in emulatorsPassed through the offline preverifier

PackagedCreates the Java Archive file (JAR) and Java Application Descriptor (JAD) file JAR file contains the manifest file

Automatically generated by the jar toolInformation about the MIDlet, such as name, vendor, version and configuration and profile utilized

JAD file contains additional information, such as URL and size

Very useful for the mobile decide to decide whether to download the

MIDlet

or notSlide4

Manifest and JAD Examples

Manifest File Example

JAD File Example

Manifest-Version: 1.0

Ant-Version: Apache Ant 1.7.0

Created-By: 1.6.0_03-

b05

(Sun Microsystems Inc.)

MIDlet

-2:

CalculatorWebService

, ,

edu.cse.usf.book.ws.CalculatorWebServiceMIDlet-1: TCPTest, , edu.cse.usf.book.TCPTestMIDlet-Vendor: VendorMIDlet-Name: TCPTestMIDlet-Version: 1.0MicroEdition-Configuration: CLDC-1.0MicroEdition-Profile: MIDP-2.0

MIDlet

-1:

TCPTest

, ,

edu.cse.usf.book.TCPTest

MIDlet

-2:

CalculatorWebService

, ,

edu.cse.usf.book.ws.CalculatorWebService

MIDlet

-Jar-Size: 12747

MIDlet

-Jar-URL: TCPTest.jar

MIDlet

-Name:

TCPTest

MIDlet

-Vendor: Vendor

MIDlet

-Version: 1.0

MicroEdition

-Configuration: CLDC-1.0

MicroEdition

-Profile: MIDP-2.0Slide5

MIDlets

All MIDlets have the same life cycle

Paused

Active

Destroyed

destroyApp

()

destroyApp

()

pauseApp

()

startApp

()

New Application Instance

EndSlide6

A Hello World MIDlet Example

import javax.microedition.midlet.*;

import javax.microedition.lcdui

.*;

public class

HelloWorld

extends

MIDlet

implements

CommandListener

{

private Command

exitCommand; private TextBox tbox;// MIDlet constructorpublic HelloWorld() {// Create "Exit" CommandexitCommand = new Command("Exit", Command.Exit, 1);

// Create

TextBox

to display the output

tbox

= new

TextBox

("Hello World

MIDlet

", "Hello, World!", 15, 0);

// Include the Exit Command in the interface and set its Listenertbox.addCommand(exitCommand

);tbox.setCommandListener(this);// Set the TextBox as the current screen

Display.getDisplay(this).setCurrent

(tbox);

}Slide7

A Hello World MIDlet Example

// The system calls this function to start the MIDlet

protected void

startApp() {}

// The application is switched to the paused state

protected void

pauseApp

() {}

// The application is destroyed

protected void

destroyApp

() {

boolean force}// MIDlet destroys itself if user gives the Exit Commandpublic void commandAction (Command c, Displayable d) { if (c==exitCommand) { destroyApp(false); notifyDestroyed{};

}

}

}Slide8

Hello World MIDletSlide9

The User Interface Hierarchy of Classes

The package javax.microedition.lcdui contains most of the classes and methods needed to design GUIs

Display

Displayable

Command

Canvas

Screen

List

StringItem

TextBox

Alert

Form

Item

CustomItem

Spacer

ChoiceGroup

TextField

ImageItem

DateField

Gauge

0 ... 1

0 ... n

0 ... nSlide10

The User Interface API

Hierarchy of classesDisplay class at the topManages the display and input devices of the systemContains methods to retrieve the properties of the device and to request the display of objectOnly one instance of Display per MIDlet

Reference of that instance can be obtained by getDisplay() methodDisplayable object contains the UI objects that are shown in the display

setCurrent() and getCurrent() utilized to set and retrieve the current Displayable

The application changes the current Displayable based on user action

Displayable

object may have listener and command objects associated

User uses these objects to interact with the UI

When the user selects a command, the application is automatically notified

The application may react changing the Displayable by another oneSlide11

The User Interface API

Commands provide users with a way to navigate through the Displayables of an applicationIf a Displayable has no command associated with it, the user has no way to change the current DisplayableAll commands have a string label, priority, and command typeCommands are added or removed using the addCommand

() and removeCommand() methodsSix command types:BACK, OK, CANCEL, HELP, EXIT, STOP

Following example shows the implementation of three commands, two generic commands, save and delete, and one specific command, the exit commandSlide12

Commands Example

class ExampleCommand extends Screen implements CommandListener

{ Command save = new Command ("Save",

Command.SCREEN, 2};

Command delete = new Command ("Delete",

Command.SCREEN

, 3};

Command exit = new Command ("Exit",

Command.EXIT

, 4};

MIDlet

midlet; public ExampleCommand (MIDlet mymidlet) { midlet = mymidlet; setCommandListener(this);

addCommand

(save);

addCommand

(delete);

addCommand

(exit);

}

public void commandAction (Command c, Displayable d) { if (c == save) { \\ Save data

} else if (c == delete) { \\ Delete data } else if (c == exit) { \\ Exit the application

midlet.notifyDestroyed(); }

}}Slide13

Lists, Text Boxes, Forms, and Alerts

Displayable class has two subclasses: Canvas and ScreenCanvas contains objects that allow the developer to have precise control of what is drawn on the displayScreen contains high-level objects that implement complete user interface components such as lists, text boxes, and forms

List class is a Screen that displays a list of choice elementsEach element includes a string and may have an icon

Lists can be implicit, exclusive, and multiple choiceAppend, delete, insert, set, getString

, and

getImage

methods

The type of list is selected using the interface class

Choice

TextBox

class is a Screen that allows the user to input and edit text

Application can set input constraints

ANY, NUMERIC, DECIMAL, PHONENUMBER, URL, EMAILADDRA text box must have commandsSlide14

Lists, Text Boxes, Forms, and Alerts

Form is a Screen that may contain StringItems, ImageItems, DateFields, TextFields, Gauges, and ChoiceGroups

Any of the subclasses of class ItemForm can be manipulated using the insert, append, delete, set, get, size, and deteleAll

methodsAlerts are Screens that can inform the user about errors and other exceptions, or as short informational notes and remindersAlerts are displayed for certain amount of time using the

setTimeout

method, or modal, which requires the user input to close it

ALARM, CONFIRMATION, ERROR, INFO, and WARNING typesSlide15

List Example

List list = new List (String title, int

listType

, String[ ] stringElements

, Image[ ]

imageElements

);

where

listType

can be IMPLICIT, EXCLUSIVE, or MULTIPLE;

stringElements

(

imageElements) is the initial array of elements(images)e.g., List list = new List (``Email list'', Choice.IMPLICIT, ``labrador@cse.usf.edu, ajperez@cse.usf.edu, pedrow@cse.usf.edu'', null);Slide16

Alert Example

Alert alert = new Alert (String title, String alertText

, Image alertImage

, AlertType.XXX);

where XXX can be any of the

alertType

e.g., Alert

alert

= new Alert (``Warning'', ``Delete all?'', null,

AlertType.WARNING

);Slide17

The Media API

Designed to support sound in resource-constrained devicesSubset of the Mobile Media API, an optional package meant for Java ME devices with advanced sound and multimedia capabilitiesSupports tone generation and media flow control (audio playback)Implemented in two packagesThe javax.microedition.media package, which is a fully compatible subset of classes included in the Mobile Media API

The javax.microedition.media.control

package that defines specific control types that can be used with a PlayerThree main componentsManager: used by the application to request Players

Player: plays the media

Wav, MP3, MIDI files and tone sequences

Controls: implement the controls of the Player

Start, stop, closeSlide18

Creating a Player

The createPlayer method of the Manager class can create a player in two different waysPlayer

Manager.createPlayer (String

url)where

url

specifies the protocol and content of the data as follows:

<protocol>:<content location>

e.g., Player p =

Manager.createPlayer

(``http://hello.wav'');Slide19

Creating a Player

A player can also be created to playback media from an inputStreamStart(), stop(), close() methods Player

Manager.createPlayer (

InputStream stream, String type);

e.g.,

InputStream

istream

=

getClass

().

getResourceAsStream

(``hello.wav'');Player p = Manager.createPlayer(istream, ``audio/X-wav'');p.start();Where type can be: Wave audio files (audio/x-wav), AU audio files (audio/basic), MP3 audio files(audio/mpeg), MIDI files (audio/midi), Tone sequences (audio/x-tone-seq)Slide20

Generating Tones

The Manager class can also be used to generate tonesVolume is a value from 0 to 100Duration is the duration of the tone in millisecondsNote defines the tone of the noteNumber from 0 to 127note = (12 x

log2 (f/440)) + 69

Frequency 440 Hz corresponds to note 69, which is MIDI note A

Manager.playTone

(

int

note,

int

duration,

int

volume)Slide21

The Record Management System (RMS)

Simple record-oriented database that allows MIDlets to persistently store data in the mobile deviceIncluded in the javax.microedition.rms packageUses the concept of record store, a collection of persistent records

Records are arrays of bytes of different lengths and types within a record storeRecords are automatically identified by a recordID

Monotonically increasing-by-one mechanism with no wrap aroundAdjacent records in a record store do not necessarily have subsequent record IDsRecord stores are uniquely named using the name of the

MIDlet

suite plus the name of the record store

MIDlet

suites are identified using the attributes

MIDlet

-vendor and

MIDlet

-name of the application descriptorSlide22

The Record Management System (RMS)

The RMS API does not include locking mechanisms but ensures that record store operations are atomic, synchronous, and serializedIt is the programmer’s responsibility to coordinate access when multiple threads within the same MIDlet attempt to access the same record simultaneouslyNo corruption of data guarantee but the serialization mechanism might give MIDlets access to the record in an undesired sequence

Methods to manipulate record storeslistRecordStores, deleteRecordStore,

openRecordStore, closeRecordStore, getNumRecords,

getSize

,

getSizeAvailable

,

getNextRecordID

,

getVersion

,

getLastModifiedMethods to manipulate recordsaddRecord, deleteRecord, getRecordSize, getRecord, setRecordSlide23

Opening a New Record Store

public void openRecStore(String recordStore_name

){

try{

RecordStore

rs

=

RecordStore.openRecordStore

(

recordStore_name,true

); } catch(Exception e) { System.err.println(e.toString()); }}Slide24

Adding a New Record to a Record Store

public void writeRecord(String str

){

byte[] rec

=

str.getBytes

();

try

{

rs.addRecord

(

rec, 0, rec.length); } catch (Exception e) { System.err.println(e.toString()); }}Slide25

Security

Security is guided by the following goalsConfidentialityDisclosure of information only to authorized users or systemsEncryption is a common mechanism to provide confidentialitySymmetric and Asymmetric encryptionIntegrityData cannot be modified without proper authorization

Achieved by cryptographic methods plus additional informationAuthenticityMaking sure the message is authentic; it comes from the real sourceDigital signatures using asymmetric encryption

AvailabilityMaking sure information is available when neededSlide26

MIDlet Security

MIDP 1.0 specification used the sandbox modelRun in a controlled and separate environment and do not interfere with each otherMIDP 2.0 expands this model including the concepts of trusted MIDlet and protection domains

Untrusted MIDlet suite is one whose authenticity and integrity of JAR file cannot be trusted by the deviceExecuted in

untrusted and restrictive domainMIDP 2.0 includes the mechanisms to identify and trust a MIDlet suite and the concept of protection domain for trusted

MIDlets

Protection domain is a set of permissions associated with a root certificate in the device

A specific domain can be defined in the device using the public key of the domain entity, e.g., a software development company

Then, a

MIDlet

signed by the company will be given access to all those resources included in the permissions of the domainSlide27

MIDlet Security

Digital signatures and authentication methods are utilized to decide whether to trust or not a MIDlet suiteInternet X.509 Public Key Infrastructure standard included in RFC 2459 and RFC 2437 “PKCS #1: RSA Cryptography Specifications, version 2.0”First, the MIDlet is signed; then, at download time, it is authenticated

Entire process consists of the following stepsSender creates a signing certificate sending its Distinguished Name and public key to a Certificate Authority (CA) to obtain a RSA X.509 certificateSender encodes and inserts certificate(s) in the JAD file

Sender signs the JAR file with its private key to provide MIDlet integrity; however, it does not include the JAD fileReceiver downloads the

MIDlet

, checks the JAD file and verifies signer certificates and JAR signatureSlide28

MIDlet Security

Receiver verifies signer certificates by looking at the CA in the JAD file and the root certificate authorities stored in the deviceIf authentication fails, MIDlet is not installedReceiver verifies JAR signatureGets signer’s public key from the CA and uses this key, the signature included in the JAD file, and the digest included in the JAR file to verify it

Certificates are used in MIDP 2.0 security for authenticationPackage javax.microedition.pki provides the

Certificate interfacegetIssuer(), getNotAfter(),

getNotBefore

(),

getSerialNumber

(),

getSigAlgName

(),

getSubject

(),

getType(), and getVersion() methodsNetworking security achieved by Secure Socket Layer (SSL) and the Transport Layer Security (TLS) protocolsHttpsConnection and SecureConnection interfacesMethod getSecurityInfo can be applied to an open connection to fill a SecurityInfo objectObtain protocol name and version, cipher suite, certificate of the connection