Internet Mobile Services - Pawel Czarnul Home Page

191
(C) 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected] Internet Mobile Services Paweł Czarnul [email protected] http://pczarnul.eti.pg.gda.pl Computer Architecture Department Gdansk University of Technology, Poland

Transcript of Internet Mobile Services - Pawel Czarnul Home Page

Page 1: Internet Mobile Services - Pawel Czarnul Home Page

(C) 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Internet Mobile Services

Paweł Czarnul

[email protected]

http://pczarnul.eti.pg.gda.pl

Computer Architecture Department

Gdansk University of Technology, Poland

Page 2: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices - PDAs - Palm

1. Selected mobile devices present: PDAs: handheld computers, programmable wireless capability

PalmOS vs. Microsoft Pocket PC (PalmOS runs on slower/cheaper hardware)

2005: low end Palm costs around 250 USD, typical hardware: 200MHz

Processor, 32MB RAM, 320x320 color display capable of displaying 65000 colors, output stereo jack, speaker, Irda, built-in rechargeable battery (typically Lithium Ion), possibly expansion slots like SD, possibly other networking devices e.g. Bluetooth

high end Palm – 400 USD+: more memory (e.g. 256MB), faster processor e.g. 400MHz, more networking options e.g. WiFi,

2006: low end Palm still costs around 250 USD, typical hardware:

200MHz Processor, 32MB RAM, 320x320 color display capable of displaying 65000 colors, output stereo jack, speaker, Bluetooth rather than IrDA in older devices, built-in rechargeable battery (typically Lithium Ion), possibly expansion slots like SD,

WiFi, 480x320, 128MB for 100 more USD

Page 3: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices - PDAs - Palm

1. Selected mobile devices present: PDAs: handheld computers, programmable wireless capability

2006: high end Palm – 550 USD+ (more expensive): more memory (e.g.

256MB), faster processor e.g. 400MHz, WiFi, built-in hard drive (4GB etc.) - LifeDrive etc.

possibly integrated mobile phones and PDA – Treo, built-in keyboard

Page 4: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices - Pocket PC

1. Selected mobile devices present: Typical PocketPC device (Microsoft Windows Mobile 2003 SE for

PocketPC): 2005: low end (250USD): processor 200MHz, 64MB RAM, 240x320

screen, SD, MMC card support, Irda, stereo jack to higher end (800USD+): processor 600MHz, 128MB RAM,

Bluetooth, WiFi, Irda, GPS, USB, RS,

2006: low end (300USD - more): processor 400MHz (2x faster), 128MB

(2x than before) RAM, 240x320 screen, SD, MMC card support, Irda, stereo jack (same as before)

GPS for about 100USD more to higher end (800USD+): processor 600MHz, 128MB RAM,

Bluetooth, WiFi, Irda, GPS, GSM, GPRS, EDGE USB, RS, - no big changes

Page 5: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices - 20091. Selected mobile devices present:

2009: - more smartphones than PDAs – no market for pure PDAs it seems

Low-end smartphone: 400 USD 400.00 MHz processor; 128.00 MB RAM; 2.8” screen,

320x240 resolution, GPS: SiRF Star III; Navi software, microSD; Wi-Fi, Bluetooth; touch screen, data transmission UMTS, GSM, GPRS, EDGE/EGPRS, Bluetooth; frequency 900, 850, 2100, 1900, 1800; MMS, SMS, e-mail, radio, digital camera 3 MPix; working time 315 hours

High-end, 850 USD 528.00 MHz processor, 4GB memory,3.6” screen, 800x480 resolution

GPS: SiRF Star III, microSD; Wi-Fi, Bluetooth, USB 2.0; touch screen, working time 750 hours, WCDMA, HSDPA, GSM, GPRS, EDGE/EGPRS; frequency: 1900, 2100, 850, 900, 1800; wmv, wma, mp4, mp3, AAC; SMS, e-mail, MMS; radio, digital camera 3.2 MPix; HTC ExtUSB (mini-USB, audio, TV-out; USB 2.0 High-Speed), (G-Sensor);

Page 6: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices - 20091. Selected mobile devices present:

2009: PDAs Low-end, 300 USD

400.00 MHz processor, RAM: 64.00 MB; ROM: 1024.00 MB; 3.5 screen 320x240 resolution, GPS: SiRF Star III, ext. memory: Secure Digital, MultiMedia Card; mini USB, headphone ext. out, touch screen

higher-end 550 USD – in fact smartphone

624.00 MHz processor 128.00 MB RAM, 4.0” screen, 640x480 resolution, SDIO, Compact Flash Type I, Compact Flash Type II; headphones ext out, Wi-Fi, mini USB, Bluetooth; touch screen, GSM, Bluetooth; txt, doc; SMS, MMS, e-mail;

in one of the Internet shops, 6 PDAs, 40 smartphones - trend

Page 7: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices – 2012/20131. Selected mobile devices present:

2012 – specifications of a smartphone: GSM 850 900 1800 1900, UMTS Weight 130 g 3.7” screen, 16M colors 800x480 7 hours talking, 20 days stand-by 8GB memory ~ 1GHz processor clock, dual core available Touch screen, can have more than 1 SIM card Bluetooth, HSDPA, WAP, xHTML, WiFi, Hotspot WiFi USB GPS, A-GPS Radio, organizer etc., mpeg4 video Digital camera e.g. 5MP,

1. G-sensor, light sensor, approach sensor

Face detection IP67 etc.

Page 8: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Operating Systems - 20121. Changing very very quickly (source – Gartner May 2012)

a 2 percent decline in the number of mobile devices sold in 2011

around 410 million devices in Q1 2012 worldwide

OS 2012 2011

Android 56.1 36.4

iOS 22.9 16.9

Symbian 8.6 27.7

RIM 6.9 13

Bada 2.7 1.9

Microsoft 1.9 2.6

others 0.9 1.5

Page 9: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Operating Systems - 20131. Changing very very quickly (source – Gartner August 2013)

a total of ~ 225 thousand smartphones sold in 2Q 2013

OS 2Q 2013 2Q 2012

Android 79 64.2

iOS 14.2 18.8

Symbian 0.3 5.9

RIM 2.7 5.2

Bada 0.4 2.7

Microsoft 3.3 2.6

others 0.2 0.6

Page 10: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Links1. Comparison of mobile operating systems:

http://faqoid.com/advisor/os-comparison.php

http://archive.techtree.com/techtree/jsp/article.jsp?article_id=114322&cat_id=899

http://community.giffgaff.com/t5/Blog/Mobile-Operating-Systems-Compared-iOS-Android-and-Windows-Phone/ba-p/2776337

Cloud-based mobile management:

http://www.networkworld.com/news/2012/060612-gartner-mdm-259900.html

Page 11: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices - APIs

1. Trends in the recent years:

Initially mobile Java J2ME was the standard (portable) across operating systems available

The variety of existing solutions have triggered development and popularity of distinct APIs (functionally pretty much equivalent) specific for the given operating system

Still there do appear portable solutions such as Oracle ADF:

http://www.oracle.com/technetwork/developer-tools/adf-mobile/overview/index.html

http://www.oracle.com/ocom/groups/public/@otn/documents/webcontent/513078.pdf

Page 12: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices - Trends1. Trends in the recent years:

From → to (2013)

Organizers, address books, monochrome display, long battery life

Color screen, office software, dictionary, synchronize with PC from time to time

PDAs with Irda, then Bluetooth, WiFi added later

Smartphones

Smartphones including various features: digital camera, movie, sound players, radio, GPS and location based services, SMS, MMS, mail, WiFi

Tablets More consumer devices connection oriented e.g. digital cameras

running Android Integration with the cloud e.g. for backup, Goggle Cloud Messaging

Page 13: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Best Mobile App Awards - 20131. Best mobile appsEmergency notifications (Australia)http://www.bestmobileappawards.com/app-submission/emergencyaus/#.UkgCvLPkLq4

Manage healthhttp://www.bestmobileappawards.com/app-submission/manage-my-pain-pro/#.UkgCx7PkLq4 easy lunches (Sweden)http://www.bestmobileappawards.com/app-submission/izilunch/#.UkgCzbPkLq4

Care4teen

http://www.bestmobileappawards.com/app-submission/care4teen/#.UkgC1LPkLq4

Page 14: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Global Mobile Awards - 20131. Best mobile appsReal time parking availability – supported on smartphones, tablets etc.

http://www.globalmobileawards.com/winners-2013/#cat_id6

App for automotive

BMW i, MINI, Sixt and Vodafone Group for DriveNow Premium Car Sharing

http://www.globalmobileawards.com/winners-2013/#cat_id6

BlindSquare is an augmented reality GPS application for the blind.

It can locate the nearest facilities of the given kind.

NewsHunt is India’s #1 mobile newspaper app

- integrates news and jobs from 85 regional newspapers in India

Page 15: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Devices - Trends1. Trends in the recent years:

From → to (2013)

Organizers, address books, monochrome display, long battery life

Color screen, office software, dictionary, synchronize with PC from time to time

PDAs with Irda, then Bluetooth, WiFi added later

Smartphones

Smartphones including various features: digital camera, movie, sound players, radio, GPS and location based services, SMS, MMS, mail, WiFi

Tablets More consumer devices connection oriented e.g. digital cameras

running Android Integration with the cloud e.g. for backup, Goggle Cloud Messaging

Page 16: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Typical features of handhelds

1. Typical applications run on handhelds typical organizer: addresses, phones, mails etc. email, SMS play MP3, video digital camera office applications Adobe PDF reader any other application available e.g. many games, dictionaries, secure

data storage, offline document viewing

Shift to location-based services – guides in cities, online information about traffic, commute transport etc.

GPS + additional services – issue of reliability of such services/information

Integration with social portals and services Sharing information with others on the Internet

Page 17: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communication Standards - Mobile Computing - Bluetooth

1. Bluetooth wireless communication method between devices like PCs (laptops),

PDAs, mobile phones, watches, home appliances etc., similar applications like IrDA

up to 10m (specification) – 1mW, up to 100m when signal amplified uses 2.4 Ghz using 79 channels between 2.402 GHz to 2.480 GHz (23 channels in

some countries) 721 Kbps http://www.tutorial-reports.com/wireless/bluetooth/technology.php

SAFER+ (Secure and Fast Encryption Routine) – uses 128-bit keys, it is possible to authenticate (the link level) a device, devices use PINs (personal identification numbers)

devices can create shared link keys, which can be used to encrypt traffic on a link (http://www.tutorial-reports.com/wireless/bluetooth/security.php)

http://pl.wikipedia.org/wiki/Bluetooth

Page 18: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communication Standards - Mobile Computing - Bluetooth

Where does the name come from? Refers to the Danish king Harald "Bluetooth" Blaatand who unified

Denmark and Norway. Bluetooth was supposed to unify the telecom and computing industries.

uses Frequency-Hopping Spread-Spectrum (FHSS) is a spread spectrum modulation scheme that uses a narrowband carrier that changes frequency in a pattern known to both transmitter and receiver. Properly synchronized, they maintain a single logical channel.http://www.mobileinfo.com/Bluetooth/FAQ.htm#g1

generally does not interfere with other appliances due to the above

http://www.mobileinfo.com/Bluetooth/FAQ.htm

Page 19: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communication Standards - Mobile Computing - 802.11

1. 802.11 - founded in 1997 by IEEE, initially up to 2Mbps, standards: 802.11b (1999) - very popular, uses 2.4 Ghz, can interfere with other

devices like cordless phones,, microwave ovens etc.

802.11 a (1999) - uses 5 GHz, rates up to 54Mbps, incompatible with 802.11b (although dual a and b devices exist), shorter range

802.11g (2003) - uses 2.4 Ghz, up to 54 Mbps, backward compatible with 802.11b - access points and network adapters from both technologies can interoperate

two modes: network adapters communicate via access points orad-hoc mode – two adapters communicating between each other

http://compnetworking.about.com/cs/wireless80211/a/aa80211standard.htm

Page 20: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communication Standards - GPRS, EDGE, UMTS

• GPRS (General Packet Radio Service) - service that allows data to be sent via mobile telephone network

packet switching - data is sent when users have data to sent rather than reservation of the whole channel from sender to receiver (then users are billed for time regardless of whether they send data or not) - billed by size of data sent/received

can be shared among many users at the same time

theoretical max bandwidth 170kbps (practical 30), typical 4-5KB/s, latency 0.6s

specification defines the physical (PHY), Media Access Control (MAC), and Logical Link Control (LLC) layers

EDGE (up to 200 kbps) UMTS (up to 1920 kbps)

Page 21: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Programming Mobile Devices Java ME

Configurations and Profiles

Page 22: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Configurations and Profiles

1. J2ME, Configurations and Profiles J2ME is a platform for developing applications on mobile devices e.g.

mobile phones, PDAs

Since such devices differ in computational power, features, J2ME distinguishes: configuration which refers to some basic functionality of a range of

devices - usually referring to networking capabilities, memory size and processor speed, but also software-wise regarding the libraries present etc. - must be implemented in full – creates a common platform for applications, current configurations include:• Connected Limited Device Configuration (CLDC) – for low-end devices (<1MB of memory)• Connected Device Configuration (CDC) – for high-end PDAs, phones etc. (2MB of memory or more)

profile that is located on top of a configuration and can use some more specific features of the device, e.g. specific features for PDA rather than mobile phone; profile can be built on top of another profile

Page 23: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Connected Limited Device Configuration (CLDC)

CLDC specified hardware requirements: 128 KB for the virtual machine 32 KB or more for the running programs potentially slow (low bandwidth) network connection low power consumption, powered by batteries 16 or 32-bit processor

CLDC is a subset of CDC, however both include API not present in J2SE

API includes: java.util – a subset of J2SE, utility API java.io – a subset of J2SE for management of I/O java.lang – a subset of J2SE – related to the virtual machine javax.microedition.io – extension vs J2SE

CLDC specifies that the VM must act as a multithreaded system, does not have to be parallel

does not specify any display, keyboard, disk, lifecycle of an application, event handling etc.

vendors can provide their own compliant VM, Sun provides KVM (Kilobyte VM)

Page 24: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Connected Limited Device Configuration (CLDC)

API excludes: floating point operations, must not use float, Float, double, Double

(added in CLDC 1.1 in 2003) Java Native Interface (JNI) – calling native code from Java finalization of objects (finalize() is a method that is invoked before

memory is reclaimed) exceptions and Errors – only limited number of classes are

provided - assumption that applications do not recover from errors anyway!

thread groups, thread daemons (a daemon thread is a thread that does services for other threads – in an infinite loop, if there are only daemon threads left, the interpreter exits, methods setDaemon(...), isDaemon(), the other threads are called user threads)

weak references reflections custom class loading – cannot update CLASSPATH, replace

existing packages etc.

Page 25: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Connected Limited Device Configuration (CLDC)

API excludes: weak references (weak reference allows to refer to an object

without keeping it from being garbage collected. If the garbage collector collects a weakly reachable object, all weak references to it are set to null),

objects are accessible through reference objects holding references to objects so that garbage collection is possible e.g. WeakReference

reflections – can allow the code to access information about already loaded classes, possible to increment the field value by finding the field by name dynamically etc.

custom class loading – cannot update CLASSPATH, replace existing packages etc.

Page 26: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Connected Limited Device Configuration (CLDC)

API includes: Character, String, StringBuffer, Integer, Byte etc. Thread, synchronized, wait, notify java.lang.Error java.lang.OutofMemoryError java.lang.VirtualMachineError HashTable Enumeration Vector Calendar Date ByteArrayInputStream, InputStreamReader ByteArrayOutputStream, OutputStreamWriter javax.microedition.io – for network connections – class Connection,

interfaces: Connection, Input/OutputConnection, DatagramConnection, StreamConnection

Page 27: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Connected Device Configuration (CDC)

Targeted for higher-end devices with 2MB+ memory CDC implementation must include the whole Java Language

Specification, includes CLDC API taken from J2SE 1.3, includes:

java.io java.lang java.lang.ref java.lang.reflect java.net (URLConnection, URL etc.) java.security java.security.cert java.math java.text java.util java.util.zip, java.util.jar java.microedition.io

Page 28: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Profiles

1. Profile is built on top of configuration, the programmer accesses the profile, not the configuration

2. Profiles for: CDC:

FoundationProfile (JSR46 by JCP) was created with same classes (does not include AWT, Swing - for that an additional profile would have to be created on top of this one), supports HTTP and sockets

Personal Basis Profile (JSR129) – support for basic user interface (light weight) for interactive television and automotive

Personal Profile (JSR62) – full AWT support (applets in mind) – requires all Foundation Profile API and extends Personal Basis Profile. Includes: java.applet (applets), java.awt, java.awt.* (GUI), java.beans (Java Bean support), javax.microedition.xlet (life cycle management interface), java.rmimeant for PDAsupward compatible with J2SE 1.3

RMI Profile (JSR66) – requires the Foundation Profile and adds RMI (including garbage collection at both the server and the client)

Page 29: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Profiles

1. Profile is built on top of configuration, the programmer accesses the profile, not the configuration

2. Profiles for: CLDC:

Mobile Information Device Profile (MIDP) – JSR37- – for a variety of mobile devices. Applications (MIDlets) – defined by Mobile Information Device Profile Expert Group for devices with

(actually weaker and smaller devices than Palms – like phones – should then also work on Palms):• 128KB more for MIDP applications• 8KB for data storage from applications• 32KB for the Java heap• wireless communication in both ways• input keyboard, touchpad etc.• screen of 96x54 pixels or more

Page 30: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Profiles

CLDC: MIDP offers the following packages:

• java.microedition.lcdui – interface• java.microedition.midlet – MIDlet applications• java.microedition.rms – persistent storage – Record Management System (RMS)• java.microedition.io (HttpConnection present here! - extension to CLDC)• java.lang, java.util, java.io

MIDP 2.0 (JSR118) adds the following (Nov 2002) – builds on top of MIDP 1.0 (applications using MIDP 1.0 can run in MIDP 2.0):• javax.microedition.lcdui.game – for programming games (Sprite, GameCanvas)• javax.microedition.pki – for secure network connections• javax.microedition.media, javax.microedition.media.control - offers playback of sound•

• java.

Page 31: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Profiles

CLDC: MIDP for Palm is available from Sun:

• can convert MIDP applications (a pair of JAD/JAR files) to PRC (for Palm devices)

MIDP for Palm 1.0 requires hardware with:• Palm OS 3.5 +• 4MB of memory• 590 KB + of storage for MIDP for Palm on Palm + storage for application(s) – install MIDP.prc on your Palm with HotSync - should add JavaTM HQ icon

• can work on POSE (Palm OS Emulator for PC)

Page 32: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Installation, Removal of Software on Mobile Devices

Vendor provides AMS (Application Management System) that supports software: installation running removal upgrade

Page 33: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

What is a MIDlet?

MIDlet is an application running on MIDP a group if MIDlets is called a MIDlet suite A user application on MIDP (MIDlet) must extend class MIDlet and

implement: startApp() destroyApp() pauseApp()

The aforementioned methods indicate possible MIDlet states: active, paused, destroyed. The methods are called when the MIDlet changes its state appropriately

Methods notifyPaused, notifyDestroyed, and resumeRequest can change the state of the MIDlet from the MIDlet code

Page 34: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

What is a MIDlet?

Development cycle for MIDlet:

Install required software (power user mode :) ): J2SE 1.4.2+ J2ME Wireless Toolkit (supports CLDC 1.0/1.1, MIDP 2.0) any editor e.g. vi, emacs

Edit the source code of the MIDlet e.g. Hello.java - see next pages compile, package the application in ktoolbar (Build)

select device to run the application on

run the application (Run)

Page 35: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

What is a MIDlet?

Edit the source code of the MIDlet e.g. Hello.java:

import javax.microedition.lcdui.*; import javax.microedition.midlet.*;

public class HelloMIDlet extends MIDlet implements CommandListener {

private Form m; private Command cShow;

public HelloMIDlet() {

m = new Form("HelloMIDlet");

m.append(new StringItem(null, "Hello, MIDP!"));

m.addCommand(new Command("Exit", Command.EXIT, 0));

m.addCommand(cShow=new Command("Show", Command.SCREEN, 1));

m.setCommandListener(this); }

public void startApp() {

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

System.out.println("Start");

}

}

Page 36: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

What is a MIDlet?

Edit the source code of the MIDlet e.g. Hello.java:

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) {

if (c==cShow) {

m.append(new StringItem(null, "\nShow ..."));

return;

}

notifyDestroyed();

}

}

Page 37: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

JSR and JCP

Configuration or profile has been developed as a JSR (Java Specification Request – with a particular number)

JSR handled by a group of experts until a final version has been completed

all developed within JCP (Java Community Process)

Page 38: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

J2ME Literature

Java Development on PDAs: Building Applications for Pocket PC and Palm Devices by Daryl Wilding-McBride

J2ME in a Nutshell (O'Reilly Java) by Kim Topley

For starters: http://developers.sun.com/techtopics/mobility/midp/articles/wtoolkit/

Introduction to Mobility Java Technology:http://developers.sun.com/techtopics/mobility/getstart/

Create MIDlets (also from command line, without ktoolbar, 5 part tutorial)http://today.java.net/pub/a/today/2005/02/09/j2me1.html

Free J2ME resources:http://www.j2meolympus.com/freebooks/freej2mebooks.jsp

Web Services for J2ME:

http://www-128.ibm.com/developerworks/wireless/library/wi-jsr/

Page 39: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Java ME Literature

Servlets in action for J2ME:http://developers.sun.com/techtopics/mobility/midp/articles/servlets/

Example applications for mobile:

http://developers.sun.com/techtopics/mobility/allsamples/

Other books:

Enterprise J2ME: Developing Mobile Java Applications by Michael Juntao Yuan

Beginning J2ME: From Novice to Professional, Third Edition (Novice to Professional) by Sing Li, Jonathan Knudsen

Page 40: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Programming Mobile DevicesJava ME User Interface

Page 41: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Guidelines

Think about functionality rather than layout – can you visualize all e.g. Office icons on a handheld device? what about the input method – keyboard, hand writing do not ask the user to enter much data (easier on a Palm, disaster

on a mobile phone) think about the minimum requirements regarding the screen – go

back to the MIDP specification (resolution, color depth)

shall we implement all applications for such low-end criteria (screen etc.)?

what about more powerful devices with thousands of colors, 320x320 or larger resolution etc. - find out the device at runtime

in general think what you want to present rather than how it will be presented (what happens if you put e.g. 10 commands in the menu – see later slides)

Page 42: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Display

first import:

import javax.microedition.lcdui.*;import javax.microedition.midlet.*;

use the Display class to show items on the screen first get the current display do it in startApp only, not in the constructor – the application may

behave badly then Display.getDisplay(this)

the display will allow you to show objects that derive from Displayable on the screen, you can switch between them at runtime – see the provided example

Display.getDisplay(this).setCurrent(...)

Page 43: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Display

two versions of parameters for setCurrent: setCurrent(Displayable) setCurrent(Alert,Displayable) – in this version a message (Alert) is

shown first (can block for a definite period of time or wait for user input), then the displayable will be shown on the screen

programmer can use setCurrent in startApp and later in handling the user input e.g. to display various data in response to the user input

There are a few classes available that inherit from Displayable – one of them is Form (shown in the example before – look at it), there are others – see next screen

Page 44: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Form, TextBox, List, Alert

for standard, non-drawing actions:

Page 45: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Canvas

for drawing the canvas there are classes:

Canvas inherits from Displayable resides in javax.microedition.lcdui (what we have included)

GameCanvas inherits from Canvas resides in javax.microedition.lcdui.game

especially regarding Canvas, the programmer can detect the device capabilities at runtime to create a more sophisticated interface, drawing etc.

for drawing the canvas there are classes:

Page 46: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Display

some methods available in:

Display Displayable getCurrent() boolean isColor() int numColors() setCurrent(...) boolean flashBacklight(int duration) boolean vibrate(int duration)

int getBestImageHeight(int imageType) int getBestImageWidth(int imageType)

getDisplay(MIDlet) – used in the example

Page 47: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Displayable

some methods available in:

Displayable int getHeight() int getWidth() String getTitle() void setTitle(String) Ticker getTicker() - see the example for this lecture void setTicker(Ticker t)

boolean isShown() - remember – you can switch between Displayables (in fact classes that inherit from Displayable)

void addCommand(Command) – add a command (can be handled later)

void removeCommand(Command) void setCommandListener(CommandListener) – see example

Page 48: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using Alert

How to use an Alert instance?

it is a component that displays a message to the user and waits for some defined period of time or user input, in the example for this lecture:

d=Display.getDisplay(this); d.setCurrent(m); // display an alert Alert a=new Alert ("Message","Starting ...",null,null); a.setTimeout(2500); // 2.5 secs d.setCurrent(a,m);

two constructors: Alert(String title) Alert(String title,String textToDisplay,Image image,AlertType type) the latter two can be null

Page 49: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Alert, AlertType

the following options are available in AlertType (static fields of type AlertType): CONFIRMATION ERROR INFO WARNING ALARM

in AlertType there is method: boolean playSound(Display) Some methods available in Alert:

int getTimeout() void setTimeout(int) – see example, in milliseconds int getDefaultTimeout() AlertType getType() void setType(AlertType) String getString()• void setString(String)

Page 50: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using Alert

Some methods available in Alert: Image getImage() setImage(Image)

Gauge getIndicator() setIndicator(Gauge) – what is this?

an Alert can block waiting for the user's response if the programmer specifies:

alert.setTimeout(Alert.FOREVER)

the programmer can either handle the command which closes the Alert (DISMISS_COMMAND) or let the MIDP do it

Page 51: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Commands

As an example of Displayable, we have learned about Alert (very simple Displayable), now for a change learn how commands can be handled in a MIDlet

Command represents an action the user can perform i.e. invoking an action, such an action can be handled in CommandListener

As shown before, there are methods in Displayable that refer to Commands: void addCommand(Command) – add a command (can ba handled

later) void removeCommand(Command) void setCommandListener(CommandListener) – see example

First, it is a good idea to create a Command instance and e.g. store a reference to it in a MIDlet field

Page 52: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Adding Commands

How a command is created in the example? Commands are added to a form which inherits from Displayable (this is

done in the constructor of the MIDlet)

m = new Form("HelloMIDlet");m.append(new StringItem(null, "Hello, MIDP!"));m.addCommand(new Command("Exit", Command.EXIT, 0))m.addCommand(cShow=new Command("Ping", Command.SCREEN, 1));m.addCommand(cShow1=new Command("Enter URL to ping", Command.SCREEN, 1));m.addCommand(cShow2=new Command("Show progress", Command.SCREEN, 1));m.addCommand(cShow3=new Command("Show", Command.SCREEN, 1));m.setCommandListener(this);

a CommandListener is set for the Form – this is the MIDlet itself – look at the beginning of the class:

Page 53: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Handling Commands

public class HelloMIDlet extends MIDlet implements CommandListener,Runnable {

CommandListener is defined as follows:public interface CommandListener { public void commandAction(Command,Displayable);}

This means that the MIDlet implements this method to handle commands – see example below – handle the cShow2 command – display something and return, otherwise terminate application: public void commandAction(Command c, Displayable s) { if (c==cShow2) {

// now get the counter value and show progress m.append(new StringItem(null,(new

Integer(getCounter())).toString())); return; } notifyDestroyed(); }

Page 54: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using TextBox

in the real application, you may want to create more instances of classes that inherit from Displayable – will be discussed next – in the meantime the example creates a TextBox in the constructor and assigns a command listener to it – the MIDlet itself:

tbd=new TextBox("Enter URL to ping","http://beesycluster2.eti.pg.gda.pl",50,TextField.URL);

tbd.addCommand(ctbdExit=new Command("OK",Command.OK,0)); tbd.setCommandListener(this);

above only one command is added to this Displayable, this is to quit this displayable, the handler code looks as follows – basically changes the current Displayable to m (Form):

public void commandAction(Command c, Displayable s) {... if (c==ctbdExit) { d.setCurrent(m); ... return; }

Page 55: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

TextBox, Command

This means that in response to another command the current Displayable is changed to the TextBox:

if (c==cShow1) { d.setCurrent(tbd); return; }

More about creating commands: Command(String label,int type,int priority) Command(String shortLabel,String longLabel,int type, int priority)

priority defines the precedence for showing commands on the screen when there are more commands defined

on mobile phones two commands will be shown in parallel, if there are more commands, some of them will be put into menu (those with lower priorities – higher numbers) – see example

Page 56: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Command Types

The following types of commands are available (static int fields in class Command) – the implementation can use this to set a proper label etc. - a hint to MIDP how to treat the command: BACK CANCEL EXIT HELP ITEM OK SCREEN STOP

more methods are available: int getCommandType() String getLabel() String getLongLabel() int getPriority()

Page 57: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Ticker

Ticker is a text scrolled to and fro on the display the example uses a ticker and changes its value after the user has

entered something into the TextBox:

in startApp() t=new Ticker("Enter URL to ping ..."); m.setTicker(t); // refers to the Form

now in command handler (exiting from the TextBox) set a new text for the Ticker (get it from the TextBox – discussed later):

if (c==ctbdExit) { d.setCurrent(m); // change the text in the ticker for Displayable m t.setString("Trying to ping "+tbd.getString()+ " now ..."); return;

}

Page 58: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using TextBox

TextBox allows the user to enter a text – see the example:

in constructor:

tbd=new TextBox("Enter URL to ping","http://beesycluster2.eti.pg.gda.pl",50,TextField.URL);

tbd.addCommand(ctbdExit=new Command("OK",Command.OK,0)); tbd.setCommandListener(this);

and handling of the command is in commandAction():

if (c==ctbdExit) { d.setCurrent(m); // change the text in the ticker for Displayable m

t.setString("Trying to ping "+tbd.getString()+ " now ..."); return; }

Page 59: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

TextBox

The constructor fo the TextBox is as follows: TextBox(String title, String text, int maxSize, int options)

options include (options are in TextField – see example): URL EMAILADDR PHONENUMBER DECIMAL ANY NUMERIC SENSITIVE (MIDP should not store it) PASSWORD (type password in a mobile phone!!!!!) UNEDITABLE others

Page 60: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

TextBox Methods

TextBox includes methods: int getMaxSize() void insert(String,int position) void setTicker(Ticker) int size() int getChars(char[]) void setChars(char[],int offset,int length) void setInitialInputMode(String characterSet) String getString() void setString() int setMaxSize(int) others

Page 61: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Form

Form inherits from Screen and can store items (see the example how items are appended):

Form m=new Form(“Hello”); // creates an empty Form

then a StringItem is appended and some Commands added:

m.append(new StringItem(null, "Hello, MIDP!")); m.addCommand(new Command("Exit", Command.EXIT, 0)); m.addCommand(cShow=new Command("Ping",

Command.SCREEN, 1)); m.addCommand(cShow1=new Command("Enter URL to ping",

Command.SCREEN, 1)); m.addCommand(cShow2=new Command("Show progress",

Command.SCREEN, 1)); m.addCommand(cShow3=new Command("Show",

Command.SCREEN, 1)); m.setCommandListener(this);

Page 62: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

DateField

DateField handles dates and time and can be appended to the form:

DateField(String label,int mode) DateField(Stringlabel,int mode,TimeZone)

modes can be DateField.TIME, DateField.DATE, DateField.DATE_TIME

DateField dd=new DateField(“date”,DateField.DATE_TIME);df.setDate(new Date());m.append(df);

Page 63: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

StringItem

StringItem just displays text on the form

StringItem(String label,String text) StringItem(String label,String text, int mode)

methods include: Font getFont(); void setFont(Font) String getText(); void setText(String) setPreferredSize(int width,int height)

example – append StringItem to the Form:

m.append(new StringItem(null, "Hello, MIDP!"));

Page 64: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

TextField

TextField extends StringItem with the possibility to edit text, the user can do it

TextField(String label,String text,int maxSize,int options) – same options like in TextBox

methods include: void setString(String)

•String getString()int getMaxSize()void insert(String,int position)int size()int getChars(char[])void setChars(char[],int offset,int length)void setInitialInputMode(String characterSet)int setMaxSize(int)others

Page 65: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Gauge

Gauge represents a value in the given range

Gauge(String label,boolean interactive,int maxVal,int initialVal)

mathods include: int getMaxValue() int getValue() boolean isInteractive() void setLabel() void setValue() void setPreferredSize(int width,int height) others

Page 66: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

ChoiceGroup

ChoiceGroup – when you need to obtain a selection made by the user (either one or more items selected)

ChoiceGroup(String label,int type) ChoiceGroup(String label,int type,String[] elements,Image[] elements)

type can be ChoiceGroup.MULTIPLE, ChoiceGroup.EXCLUSIVE, others.

example:String[] elements={“a”,”b”};ChoiceGroup cg=new ChoiceGroup(“options”,ChoiceGroup.MULTIPLE,elements,null);...boolean[] choices=new boolean[cg.size()];cg.getSelectedFlags(choices);// now check// can invoke cg.getString(element_index)

Page 67: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

List

List is a Screen, similar to ChoiceGroup

analogous constructors, same methods (both implement interface Choice)

same usage

Page 68: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Threads in J2ME

the main thread handling events should not spend much time handling events, for long or undeterministic actions, the MIDlet should use threads

in the example for this lecture, we want to ping a BeesyCluster server

GUI elements allow to enter the URL etc. but for pinging we create and run another thread, not to block the interface and then check progress

for the time being, pinging/contacting is just a loop that updates a counter that is later read by the main thread – we will learn about networking later

Page 69: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

HelloMIDlet, Runnable Interface

MIDlet implements interface Runnable for this to work:

public class HelloMIDlet extends MIDlet implements CommandListener,Runnable

the other thread code is as follows: public void run() { // for pinging

// for now just iterate over time heretry {for (int i=0;i<100;i++) { setCounter(i); Thread.sleep(3000);}

} catch (InterruptedException e) { System.out.println("Exception");

} }

Page 70: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Starting Threads in MIDlet

the other thread is run by a command:

if (c==cShow) { m.append(new StringItem(null, "\nStarting a thread for pinging

now ...")); (new Thread(this)).start(); return;

}

now another command checks the progress (now the counter value) –

test the example:

if (c==cShow2) { // now get the counter value and show progress m.append(new StringItem(null,(new

Integer(getCounter())).toString())); return;

}

Page 71: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

synchronized for Threads

update/read of counter is synchronized:

public synchronized void setCounter(int c) { counter=c; }

public synchronized int getCounter() {

return counter; }

find other uses of threads in MIDlets

Page 72: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

How to Create MIDlet?

MIDlet development cycle - also read: Create MIDlets (also from command line, without ktoolbar, 5 part

tutorial)http://today.java.net/pub/a/today/2005/02/09/j2me1.html

First option: code the MIDlet in an editor of your choice, then use ktoolbar to build and run the application on the selected device (you can choose devices in ktoolbar – test it for the example for this lecture)

Second option: learn the steps the hard way: code as in the first option

Page 73: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Compile and Build MIDlet on your own (without ktoolbar)

pczarnul@wolf:~$ cd ~/WTK2.2/apps/ pczarnul@wolf:~/WTK2.2/apps$ mkdir Hellotestbuild pczarnul@wolf:~/WTK2.2/apps$ cp HelloSuite/src/HelloMIDlet.java

Hellotestbuild/ pczarnul@wolf:~/WTK2.2/apps$

our MIDlet is in HelloMIDlet.java

now try to compile it using CDLC, MIDP and the standard javac compiler (will need to specify the bootclasspath)

pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild$ javac -bootclasspath ../../lib/cldcapi11.jar:../../lib/midpapi20.jar HelloMIDlet.java

pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild$

Page 74: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Compile and Build MIDlet on your own (without ktoolbar)

preverify:

pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild$ preverify -classpath ../../lib/cldcapi11.jar:../../lib/midpapi20.jar HelloMIDlet

pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild$

create a manifest file: pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild$ emacs

output/Manifest.mf & [1] 10799 pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild$ and edit:

MIDlet-Name: HelloMIDlet MIDlet-Version: 0.0.1 MIDlet-Vendor: Pawel Czarnul

Page 75: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Compile and Build MIDlet on your own (without ktoolbar)

now create a jar file:pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild$ cd output/

pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild/output$ ls HelloMIDlet.class Manifest.mf pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild/output$ jar cvfm

HelloMIDlet.jar Manifest.mf . added manifest adding: HelloMIDlet.class(in = 4016) (out= 1909)(deflated 52%) adding: Manifest.mf(in = 75) (out= 61)(deflated 18%) pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild/output$

Page 76: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Compile and Build MIDlet on your own (without ktoolbar)

now create a jad file: pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild/output$ emacs

HelloMIDlet.jad & [1] 10988 pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild/output$ ls -l

HelloMIDlet.jar -rw-r--r-- 1 pczarnul pczarnul 2583 2005-10-19 11:50 HelloMIDlet.jar pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild/output$ and edit: MIDlet-1: HelloMIDlet, , HelloMIDlet MIDlet-Name: HelloMIDlet MIDlet-Version: 0.0.1 MIDlet-Vendor: Pawel Czarnul MIDlet-Jar-URL: HelloMIDlet.jar MIDlet-Jar-Size: 2583 MicroEdition-Profile: MIDP-2.0 MicroEdition-Configuration: CLDC-1.1

Page 77: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Run Custom-built MIDlet

run it:

pczarnul@wolf:~/WTK2.2/apps/Hellotestbuild/output$ emulator -Xdescriptor HelloMIDlet.jad

Running with storage root DefaultColorPhone

NOTE: Manifest.mf should end with a new line, otherwise the attribute in the last line is not detected – had to rerun jar packaging and changed the jar size in *jad file (ran correctly then)

Page 78: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Programming Mobile DevicesJava ME

Network Access

Page 79: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Generic Connection Framework

CLDC provides Generic Connection Framework that includes interface Connection and many child interfaces, in particular for:

stream communication datagram communication (connectionless)

making a connection requires using one of the static methods of Connector class which returns a Connection i.e.:

String url=”http://www.wp.pl”

HttpConnection hc=(HttpConnection)Connector.open(url);

...

Page 80: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Connection

All Connection based interfaces and class Connector are included in package javax.microedition.io

class Connector includes the following statix methods:

Connection open(String s); Connection open(String s,int mode); Connection open(String s,int mode,boolean timeouts); DataInputStream openDataInputStream(String s); DataOutputStream ... InputStream openInputStream(String s); OutputStream ...

and includes static fields: int READ int READ_WRITE– int WRITE

Page 81: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

HttpConnection

Connection to HttpConnection - diagram

Page 82: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Sample Networking MIDlet

sample code to download a web page via HTTP can look as follows:

HttpConnection hc=null;String url=”http://www.wp.pl”;String sresult=null;

try{ hc=(HttpConnection)Connector.open(url); DataInputStream is=hc.openDataInputStream(); byte[] result=new byte [(int)hc.getLength()]; is.readFully(result); sresult=new String(result);} catch (Exception e) {

display a message informing about en error – note that this code should execute in another thread}if (hc!=null) hc.close();

Page 83: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Parameters: GET, POST

a bit more complex HTTP: what are the ways parameters can ba passed to the server?

GET and POST – how to handle this in a MIDlet?

first: MIDP 2.0 requires both HTTP and HTTPS (HttpsConnection, very easy to use)

what is the way HTTP works?

HTTP uses requests from the client which are passed to the server which responds by sending some response (note the doGet and doPost methods in servlets – what are the parameters?)

the data passed in two directions includes headers and content:

Page 84: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Parameter Encoding

what data is included in headers?

length of the response, type of data, what else?

if you pass parameters via HTTP, what is the way parameters are encoded?

[a-z], [A-Z], digits, “.”, “*”, “_” - do not change “ “ is replaced with “+” others are converted by representing lower 8 bits by %...

how to pass data via GET? how to pass data via POST?

how the server (e.g. servlet) can process the data?

Page 85: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Access Servlets in Tomcat – Pass Parameters

Learn by example:

we will try to setup a sample web application that allows the user to enter comments, their firstname, lastname and email which are then recorded in a database

and retrieved upon request

normally, the client would use a Web browser to display the page for entering data which would display a form which would then be passed using the POST method to the same servlet, if parameters are set then the data is written to the database

the example uses Tomcat and two servlets – see a separate section on this application

Page 86: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Steps

what is our task?

we will code and run a client using J2ME to access the aforementioned Web application, to store comments in the database and then retrieve results

first: run Tomcat and see the way the system works by invoking the two servlets (for storing entries and retrieving them)

Page 87: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Passing Parameters with GET

GET: invoke the servlet using GET, no parameters are given:

String url=”http://localhost:8080/..../InsertComment”

in GET, parameters are appended to the url using the rules given before

try to append parameters for GET using this method (for servlet InsertComment):

String url=”.../InsertComment?firstname=Pawel&lastname=Czarnul&[email protected]&text=I+like+it”;

see the result and discuss it in GET, there may be issues with long parameters using GET

Page 88: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Passing Parameters with POST

now try to code input parameters using the POST method

in POST parameters are put into the body of the message, encoded as before

the code is more complicated this time since appropriate headers must be set:

String parameters=”firstname=Pawel&lastname=Czarnul&[email protected]&text=I+like+it”;

String url=”http://localhost:8080/.../InsertComment” hc=(HttpConnection)Connector.open(url); hc.setRequestMethod(HttpConnection.POST); hc.setRequestProperty(“Content-Type”,”application/x-www-form-urlenco

ded:); hc.setRequestProperty(“Content-Length”,Integer.toString(parameters.le

ngth()));

Page 89: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Passing Parameters with POST

OutputStream=hc.openOutputStream(); out.write(parameters.getBytes()); ... //now read what the server has sent back

...

see (using the standard browser) whether the J2ME client has updated the database (the data has been written down)

Page 90: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

HTTPS

what about secure communication?

HTTPS

HTTPS is required by MIDP 2.0 and using it is very simple

HTTPS runs on top of SSL or TLS

HttpsConnection interface implements HttpConnection and adds two public methods:

SecurityInfo getSecurityInfo(); int getPort();

using HTTPS is simple, just replace HttpConnection with HttpsConnection and http with https:

Page 91: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Https MIDlet

try to access BeesyCluster via HTTPS

HttpsConnection hc=null;String url=”https://beesycluster2.eti.pg.gda.pl:7000/ek/AS_LogIn”;String sresult=null;

try{ hc=(HttpsConnection)Connector.open(url); DataInputStream is=hc.openDataInputStream(); byte[] result=new byte [(int)hc.getLength()]; is.readFully(result); sresult=new String(result);} catch (Exception e) {

display a message informing about en error – note that this code should execute in another thread}if (hc!=null) hc.close();

Page 92: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

HttpsConnection

modify the code above and check the two methods available in HttpsConnection – see what they return

getPort() - the port being used

SecurityInfo (interface in javax.microedition.io) gives details regarding the secure channel, versions etc.:

what is our task?

we will code and run a client using J2ME to access the aforementioned Web application, to store comments in the database and then retrieve results

first: run Tomcat and see the way the system works by invoking the two servlets (for storing entries and retrieving them)

***

Page 93: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Methods in HttpConnection

methods available in HttpConnection

String getHeaderField(String name) String getHeaderField(int) String getHost() int getPort() String getProtocol() String getQuery() String getRequestMethod() String getRequestProperty(String name) int getResponseCode() String getResponseMessage() String getURL() void setRequestMethod(String method) void setRequestProperty(String name,String value)

Page 94: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Datagrams in J2ME

datagrams – not required by MIDP

connectionless

communication is based on sending and receiving datagrams

String url=”....”; DatagramConnection c=(DatagramConnection)Connector.open(url);

interface DatagramConnection includes methods: Datagram newDatagram(int size) Datagram newDatagram(int size,String addr) Datagram newDatagram(byte[] buffer,int size) Datagram newDatagram(byte[] buffer,int size,String address) void send(Datagram datagram)– void receive(Datagram datagram)

Page 95: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Datagrams in J2ME

Datagram includes methods:

void setData(byte[] buffer,int offset,int length) void setLength(int length) void setAddress(String address) void reset() int getLength() byte[] getData() String getAddress()

sending should be preceded by preparation of a datagram, packing data into it

sending and receiving is executed by invoking send() and receive() respectively

Page 96: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Cookies and Session Handling in MIDlets

cookies and session – how to use them in J2ME?

identification of session can be done using a cookie

the client should check whether a cookie is sent in the response from the server, store it and send it back later

check and store a cookie:

HttpConnection c=......

InputStream is=c.openInputStream();

String cookie=c.getHeaderField(“Set-cookie”); if (cookie!=null) { String cookieValue=cookie.substring(0,cookie.indexOf(';'));– } - store the value of the cookie in the MIDlet

*********** what is our task?

we will code and run a client using J2ME to access the aforementioned Web application, to store comments in the database and then retrieve results

first: run Tomcat and see the way the system works by invoking the two servlets (for storing entries and retrieving them)

***

Page 97: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Cookies and Session Handling in MIDlets

now, before sending a request to the server, we can set the cookie in the following way:

HttpConnection c=(HttpConnection)Connector.open.(“....”);

c.setRequestProperty(“cookie”,cookieValue);

.... open...InputStream ... ...

check whether it works with a simple servlet

Page 98: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

MIDlet HTTP Examples

Analyze the following examples:

HelloSuite3 – simple GET request/response

HelloSuite4 – passing parameters to a servlet using GET

HelloSuite5 – passing parameters using POST

HelloSuite6 – communication with a servlet reading parameters, setting a cookie and reading it in the J2ME client

HelloSuite7 - HTTPS

Page 99: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

MIDlet HTTP Examples

Test other versions of the code:

networking code in the main thread – what can happen (SHOULD NOT CODE THIS WAY)

invoking other methods available – reading about protocols, etc.

Page 100: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Programming Mobile DevicesJava ME

Network Access

Page 101: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Basics of Networking

We already know the basics of networking in GCF, including streams, HTTP (POST, GET), how to pass data to a servlet, process it in the servlet, implement session tracking using cookies etc.

This can be found also in:

http://developers.sun.com/techtopics/mobility/midp/articles/network/

http://developers.sun.com/techtopics/mobility/midp/articles/servlets/

Now recall some basic rules for nice network programming:

do not lock the command thread with networking (as we saw last time the emulator stopped the application)

the user should have some visual feedback while the application is connecting to a network (recall our example, the networking thread was connecting, it was possible to launch a command to see progress – but how to do this automatically - TIMER!)

Page 102: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Interface Coding Rules in Networking MIDlets

command actions must return as soon as possible (a concept known in desktop/windows programming as well), also recall signal handling in operating systems or message handling in PVM (all are restricted, basically should set a flag that an event has happened and return to the user)

otherwise the user will be frustrated!

what if the user clicks “Ping” in out application multiple times, many threads may be spawned, how to control this?

the application could lock the user to a message screen until communication is finished – then the user will not create many threads

as in our example before, the main class could listen to commands to two or more forms, including the “wait message” form and simply switch between the “wait message” form and the main one (we did it for text editing). This way, the user could interrupt the networking thread – as soon as they click the connection is terminated and a new one can be started (again no two or more networking threads)

Page 103: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Coding Rules in Networking MIDlets

http://developers.sun.com/techtopics/mobility/midp/articles/threading/

also moves the networking thread to another class (it contains a reference to the MIDlet to updated the interface)

another issue – reuse threads in a mobile application (not to create threads many times – how to do this? remember threads must be managed by commands issued by the user through the interface)

also how to use a timer to update the interface?

MIDP offers classes Timer and TimerTask that can be used to invoke messages at specified points of time:

Page 104: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Timer

public class Timer ... {

Timer()

void cancel(); void schedule(TimerTask task,long delay); void schedule(TimerTask task,Date); void schedule(TimerTask task,long delay, long period); void schedule(TimerTask task,Date firstDate,long period); void scheduleAtFixedRate(TimerTask task,long delay,long period); void scheduleAtFixedRate(TimerTask task,Date firstDate,long period);

and the TimerTask class:

TimerTask(); boolean cancel(); void run(); long scheduledExecutionTime();

Page 105: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Timer, TimerTask

this way an instance of TimerTask class can be created and then driven by a Timer – at specified intervals can update the interface

also see tutorial at:

http://developers.sun.com/techtopics/mobility/midp/articles/threading/

Page 106: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Session Handling by URL Rewriting

recall how to handle sessions in MIDlets:

one way is to use cookies – i.e. to detect proper fields in an HTTP header, then remember the value in a cookie and send it back to the servlet – we have done it using the example servlet from Tomcat, i.e. set proper parameters for a servlet, then it generated a cookie that the MIDlet read and could store (and send to the servlet later)

another way is to use URL rewriting i.e. append the session id to the URL

see this at:

http://developers.sun.com/techtopics/mobility/midp/articles/sessions/

Page 107: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Networking Through a Proxy server use HTTP with a proxy for more complex networking options

why? it may not be possible to implement all protocols, data packaging etc. on a mobile device – due to many reasons like storage required for such clients including run-time storage. also it may be possible but can consume too much memory for certain data – imagine unpacking an XML tree, browsing it and adding elements in a mobile device

instead can implement a proxy and connect to it using HTTP,

you can get access to a variety of more advanced libraries available on servers, desktop computers, it is possible to create middleware on the server-side (having same interface but using various technologies behind – Web Services, CORBA, RMI others and accessing from one MIDlet without any changes)

HTTP is supported by MIDP (MIDP must support HTTP), thus is portable across a variety of mobile devices, HTTP can use TCP/IP or WAPsee examples for sending an email, connecting using RMI at:http://developers.sun.com/techtopics/mobility/midp/articles/socketRMI/

Web Service proxy in book: ****

use HTTP with a proxy for more complex networking options

why? it may not be possible to implement all protocols, data packaging etc. on a mobile device – due to many reasons like storage required for such clients including run-time storage. also it may be possible but can consume too much memory for certain data – imagine unpacking an XML tree, browsing it and adding elements in a mobile device

instead can implement a proxy and connect to it using HTTP,

you can get access to a variety of more advanced libraries available on servers, desktop computers, it is possible to create middleware on the server-side (having same interface but using various technologies behind – Web Services, CORBA, RMI others and accessing from one MIDlet without any changes)

HTTP is supported by MIDP (MIDP must support HTTP), thus is portable across a variety of mobile devices, HTTP can use TCP/IP or WAPsee examples for sending an email, connecting using RMI at:

Web Service proxy in book: ****

Page 108: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

GCF Features

Generic Connection Framework is available in profiles based on both CLDC (i.e. MIDP – the idea was to define a set of classes and interfaces for resource limited devices) but also in CDC based profiles e.g. FoundationProfile etc., there is also GCF for J2SE

supports stream and packet oriented communication

supports a connection factory (Connector.open)

URL-based connection initialization

for packet based communication GCF provides DatagramConnection

for streams many interfaces (see the hierarchy) with StreamConnection being both an InputConnection and OutputConnection

it is possible to wait for stream connection asynchronously (StreamConnectionNotifier)

Page 109: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

GCF Features

Generic Connection Framework supports URL connection initialization through:

conn-type://user:password@host:port/url;parameters

details can be found in RFC 2396, also at:

http://developers.sun.com/techtopics/mobility/midp/articles/genericframework/

now explore (apart from http and https) socket, serversocket and datagram for communication

http://developers.sun.com/techtopics/mobility/midp/articles/genericframework/gives proper connection interfaces for given connection types

note which are required (http) by the profile you are using! In particular MIDP 2.0 provides many connection types (interfaces), vendors do not have to support e.g. datagrams

Page 110: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Connections in GCF

socket conection in GCF will be analogous to that of HTTP exercised before, the URL will change, then one can open InputStream

opening and closing connections of various types will be analogous, see proper examples at:

http://developers.sun.com/techtopics/mobility/midp/articles/genericframework/

Page 111: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Socket and Datagram Examples practical aspects of socket and datagram connections – added as

optional in MIDP 2.0 (i.e. vendors do not have to support them)

try { Connector.open("protocol:address;parameters");} catch (ConnectionNotFoundExeption e) {

// handle errors}

use socket connections for various application like sending email via SMTP, telnetting, fetching data from a server listening on ..., mobile devices can also listen for incoming connections using ServerSocketConnection

as before, the heavy stuff could be implemented on a proxy server (via HTTP to a servlet)

see examples at:http://developers.sun.com/techtopics/mobility/midp/articles/midp2network/

Page 112: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Push Registry – Concepts and API

Push Registry allows to set up initiation of MIDlets either in response to:• an incoming connection• a delay

It is possible to set it programatically or in a descriptor

It is possible to register for several connections and timer alarms

The API is available from javax.microedition.io.PushRegistry

Registration in PushRegistry by calling:• registerAlarm() - registers an alarm based on a timer• registerConnection() - registers a connection which will spawn the

MIDlet

Page 113: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Push Registry – Concepts and API

listConnections() - lists either all connections registered for the MIDlet (if false is given as an argument or only those with data available – if true given for input)• Returns an array of Strings (String[])

After a connection has been registered and if the MIDlet is not active, then the Application Management System (AMS) spawns the MIDlet if a connection occurs. • The MIDlet should list connections then and process it(them)

A MIDlet can open a server side connection and register it then. The AMS will invoke the MIDlet after it has been terminated(destroyed)

The URL for server side connections do not list the server names, just port numbers e.g.: • datagram://:6000• socket://:3200• sms://:XXXX

Page 114: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Push Registry - Invoking MIDlet upon Connection

registration in a descriptor by setting:

MIDlet-Push-1: socket://:80, MyMIDlet, *

* denotes that no connections are filtered (it is possible to restrict this to a range of IP addresses)

More entries like above are possible (with successive numbers)

Note that another entry in the descriptor should allow the MIDlet to access the type of connection and list PushRegistry:

MIDlet-Permissions: javax.microedition.io.PushRegistry, *****server*** (depending on the connection type)

Page 115: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Push Registry – Concepts and API

An alarm can be registered using method:• PushRegistry.registerAlarm(fullClassName, startTime)

Page 116: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using Threads Efficiently for Networking MIDlets

study thread's API in MIDP to know how to use threads efficiently for network applications

analysis and example can be found at:

http://developers.sun.com/techtopics/mobility/midp/articles/threading2/

Page 117: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Cyclic Actions in MIDlet

A timer is a class that registers a task to be invoked every X seconds

The task should extend class TimerTask and implement necessary actions in method run()

Then method Timer.schedule(task,0,cycleIntervalInMiliseconds)

creates the timer

Page 118: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Location based Services API and Applications

Page 119: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Location based Services

Defined in JSR 179, supported e.g. by some smartphones

Returns location data transparently to the user (irrespective of the actual method used for finding the location)

The user can specify required precision

The application can call blocking methods or register a listener to receive location data periodically

Supports landmarks

Implementation can use various means to obtain location data

Page 120: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Location based Services

Standard methods used to find out the location:• GPS• Cell phone network – like cell id• Others – like querying in the nearby environment (by Bluetooth, data

available in the local network)

API – important classes and methods, requires CLDC 1.1 (because of floating point support):• Coordinates• QualifiedCoordinates (Coordinates + accuracy)• lProvider=LocationProvider.getInstance(Criteria)• Location=lProvider.getLocation(timeoutInSeconds)• Coordinates=Location.get*Coordinates()

• Landmark,• Orientiation

Page 121: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Location based Services

Defined in JSR 179, supported e.g. by some smartphones

Returns location data transparently to the user (irrespective of the actual method used for finding the location)

The user can specify required precision

The application can call blocking methods or register a listener to receive location data periodically

Supports landmarks

Implementation can use various means to obtain location data

Page 122: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Programming Mobile Devices Web Services Accessed from Mobile Devices

Page 123: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Patterns, Styles and Uses in Web Services

possible patterns: RPC asynchronous one-way

possible styles: RPC document

possible uses: SOAP encoded literal

Page 124: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Web Service API

possible solutions include:

client libraries for calling Web Services directly – available free of charge as of this moment:

kSOAP wingfoot allows to build a call dynamically as is also possible for e.g. Java clients

(see labs for Internet technologies)

JSR172 – the application and stubs are loaded into the memory of the device

the stub connects to the JSR172 runtime on the device, the runtime connects to a web server, this communicates with a SOAP engine (e.g. AXIS) and finally the method is invoked on the server

stubs are static i.e. must be generated before the application starts – similar to the “standard” Java clients (see labs for Internet technologies)

Page 125: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

JSR172 – Web Services in J2ME

covers:

calling Web Services – i.e. the client side does not support server functions (offering services)

handling XML data

document/literal style/use – it is now possible to integrate with services offered by AXIS 1.3+

more transparent to the programmer (just instantiate a stub and call a method on it) compared to WS libraries such as kSOAP, wingfoot

however potential problems during e.g. service deployment on the popular AXIS – must be careful with the service description in the WSDD file – otherwise error during connections from J2ME clients can occur

Page 126: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using kSOAP in MIDlets

kSOAP is a library for clients in Java to call Web Services example how to use kSOAP to run the Calculator.jws Web Service

installed in AXIS download kSOAP from the Internet and install file ksoap-midp.zip into

the lib directory of the project (possibly created by ktoolbar when the project was created)

copy Calculator.jws to jakarta-tomcat*/webapps/axis – Calculator.jws includes:

public class Calculator { public int add(int i1, int i2) { return i1 + i2; } public int subtract(int i1, int i2) { return i1 - i2; } }

start Tomcat

Page 127: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using kSOAP in MIDlets

the code for this example is: ZTI-7-WS-kSOAP

now code a client using kSOAP – in a separate thread:

first import:

import org.ksoap.*; import org.ksoap.transport.*; import org.kxml.*; import org.kxml.io.*; import org.kxml.parser.*;

Page 128: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using kSOAP in MIDlets

now code a client using kSOAP – in a separate thread: then code method invocation: Object result = null; String serviceUrl = "http://localhost:8080/axis/Calculator.jws"; try { transport = new HttpTransport( serviceUrl, "add" ); transport.debug = true; request = new

SoapObject("http://localhost:8080/axis/Calculator.jws", "add"); request.addProperty( "in1", new Integer(2111) ); request.addProperty( "in2", new Integer(378) ); result = transport.call( request ); } catch( Exception e ) { e.printStackTrace(); System.out.println( "Request: \n" + transport.requestDump ); System.out.println( "Response: \n" +transport.responseDump ; result = null; } System.out.println(result);

Page 129: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using wingfoot in MIDlets

wingfoot is a library for clients in Java to call Web Services example how to use wingfoot to run the Calculator.jws Web Service

installed in AXIS download wingfoot from the Internet and install file kvmwsoap_1.06.jar

into the lib directory of the project (possibly created by ktoolbar when the project was created)

copy Calculator.jws to jakarta-tomcat*/webapps/axis – Calculator.jws includes:

public class Calculator { public int add(int i1, int i2) { return i1 + i2; } public int subtract(int i1, int i2) { return i1 - i2; } }

start Tomcat

Page 130: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using wingfoot in MIDlets

the code for this example is: ZTI-7-WS-wingfoot

now code a client using wingfoot – in a separate thread:

first import:

import com.wingfoot.soap.*; import com.wingfoot.soap.transport.*;

Page 131: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Using wingfoot in MIDlets

now code a client using wingfoot – in a separate thread: then code method invocation: try { Envelope requestEnvelope=new Envelope(); requestEnvelope.setBody("in1", new Integer(2111)); requestEnvelope.setBody("in2", new Integer(311)); Call theCall = new Call(requestEnvelope); theCall.setMethodName("add"); theCall.setTargetObjectURI("Calculator"); HTTPTransport transport = new

HTTPTransport("http://localhost:8080/axis/Calculator.jws",null); transport.getResponse(true); Envelope responseEnvelope = theCall.invoke(transport); System.out.println(responseEnvelope.getParameter(0)); } catch (Exception e) { System.out.println("Calling failed with "); e.printStackTrace(); }

Page 132: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communicating from MIDlet with AXIS using JSR172

the code is available in ZTI-7-WS-JSR172 first the service will be deployed using a WSDD file not as .jws let our service be (CalculatorAdder.java) public class CalculatorAdder { public int add(int i1) { return i1 + 24; } public String echo() { return "kkokok"; } public int subtract(int i3) { return 100 - i3; }– }

Page 133: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communicating from MIDlet with AXIS using JSR172

compile it (you need to have the following set):

export AXIS_HOME=/usr/local/axis-1_4 export AXIS_LIB=$AXIS_HOME/lib export AXISCLASSPATH=$AXIS_LIB/axis.jar:$AXIS_LIB/axis_ant.jar:

$AXIS_LIB/commons-discovery-0.2.jar:$AXIS_LIB/commons-logging-1.0.4.jar:$AXIS_LIB/jaxrpc.jar:$AXIS_LIB/saaj.jar:$AXIS_LIB/log4j-1.2.8.jar:$AXIS_LIB/xml-apis.jar:$AXIS_LIB/xercesImpl.jar:$AXIS_LIB/wsdl4j-1.5.1.jar

export CLASSPATH=$CLASSPATH:$AXISCLASSPATH

the example was tested using Tomcat 4.1.18 (should not matter), AXIS 1.3 and JSDK 1.5

Page 134: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communicating from MIDlet with AXIS using JSR172

compile it by:

javac CalculatorAdder.java

and copy to directory:

jakarta-tomcat-4.1.18/webapps/axis/WEB-INF/classes/

now start Tomcat and deploy the service by calling:

java org.apache.axis.client.AdminClient deploy.wsdd

Page 135: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communicating from MIDlet with AXIS using JSR172

deploy.wsdd is as follows (be very careful here as otherwise the service will deploy successfully, the stub will be generated, the client will compile but will fail when calling the service):

<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"> <service name="CalculatorAdder" provider="java:RPC"

style="document" use="literal"> <parameter name="schemaQualified"

value="http://localhost:8080/axis/services/CalculatorAdder"/> <parameter name="wsdlServicePort" value="CalculatorAdder"/> <parameter name="className" value="CalculatorAdder"/> <parameter name="wsdlPortType" value="CalculatorAdder"/> <parameter name="typeMappingVersion" value="1.2"/> <parameter name="allowedMethods" value="echo"/> <parameter name="scope" value="Session"/> </service></deployment>

Page 136: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communicating from MIDlet with AXIS using JSR172

now the service should be available in the list of deployed services at:

http://localhost:8080/axis/servlet/AxisServlet

now AXIS should generate WSDL for the service at:

http://localhost:8080/axis/services/CalculatorAdder?wsdl

At this point create a new MIDlet (again calling the service in a separate thread), check support for JSR172 and generate stubs first by:

in ktoolbar – Project – StubGenerator type: http://localhost:8080/axis/services/CalculatorAdder?wsdl for WSDL file

name or URL and wscalcadder for an output package – a new directory will be

created in the src directory

Page 137: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Communicating from MIDlet with AXIS using JSR172

after the stub has been generated successfully edit the client code which is very simple in this case:

import wscalcadder.*;

instantiate the stub call the required method:

try { CalculatorAdder_Stub stub; stub=new CalculatorAdder_Stub(); System.out.println(stub.echo()); } catch (Exception e) { System.out.println("Error calling Web Service using JSR 172"); e.printStackTrace(); }

Page 138: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

BluetoothAPI

Page 139: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

radio communication using 2.45 GHz

devices form network dynamically ad hoc when they get close to each other

devices form a hierarchy with a master and up to 7 slaves

master can be a slave in another hierarchy – multi hierarchical structure

API for Bluetooth is included in JSR 82 (optional)

JSR 82 requires at least CLDC 1.0

Page 140: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

there are concepts of:

devices – being parts of the network

services – which may be exposed by devices, found and used by others

thus each device may act as a client and as a server

or act as both

each device may expose one or more services which are identified by a Universally Unique Identifier (UUID)

in general, unless the client does not care which device the service comes from, it is necessary to find devices and then services exposed by them

Page 141: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

to get started the MIDlet needs to obtain information on the device it is running on – this can be done using methods in class LocalDevice e.g.:

setDiscoverable(DiscoveryAgent.GIAC) – to make myself discoverable by others

getDiscoverable() to find out whether others can discover

getFriendlyName() returns a nice name (String) for this device

String getBluetoothAddress() returns the address for this device

Page 142: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

LocalDevice.getLocalDevice().getDiscoveryAgent() can be used to obtain a discovery agent used further in querying – will be used on the client side

while LocaDevice.getLocalDevice() will return LocalDevice on which the server side will set the discoverable flag etc.

to make a service available, the server needs to perform the following steps:

String url=”btspp://localhost: <UUID>;name=”+name+”;<parameter>=”+<paramname>;

LocalDevice ld=LocalDevice.getLocaDevice(); ld.setDiscoverable(DiscoveryAgent.GIAC);

StreamConnectionNotifier scn=(StreamConnectionNotifier) Connector.open(url);

Page 143: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

parameters may contain:

encrypt= authorize= authenticate=

now if there were no exceptions thrown then just accept and open connections (just like socket programming)

StreamConnection sc=scn.acceptAndOpen();

and read (possibly in another thread) the content from the stream i.e.

DataInputStream dis=openDataInputStream(); dis.read*();

Page 144: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

in fact after calling open() a ServiceRecord is registered and associated with the given service.

It is possible to fetch this record by calling:

ServiceRecord ld.getRecord(scn);

the client has two options for finding services:

1. easy without discovering devices first – just query for services

2. query for available devices first and then look for available services exposed on each of them

Page 145: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

before discovering devices/services first fetch a DiscoveryAgent

DiscoveryAgent da=ld.getDiscoveryAgent();

now in 1 just look for available services i.e.invoke selectService on da:

String selectService(UUID serviceid,int securitymode,boolean masterflag)

masterflag indicates whether the device is a master securitymode defines the mode – fields available in ServiceRecord and

security features may not be supported by the implementation(s):

AUTHENTICATE_NOENCRYPT AUTHENTICATE_ENCRYPT NOAUTHENTICATE_NOENCRYPT

Page 146: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

then the string returned by selectService can be used to open a StreamConnection with the given service i.e.

StreamConnection scs=(StreamConnection)Connector.open(stringreturnedbyselectService);

to write data to the service just open a stream and write data i.e.

DataOutputStream dos=scs.OpenDataOutputStream();

dos.write*();

Page 147: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

2. In this mode devices are discovered first and then services found on them i.e.

get a reference to a DiscoveryAgent register a listener to wait for information on devices nearby in the handler remember the devices another method in the listener will notify the search for devices has

finished

search for services in a similar manner – listener and two methods

Page 148: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

DiscoveryAgent allows to call

startInquiry(int accessmode,DiscoveryListener dl)

which starts looking for available devices

the listener should implement the following methods:

deviceDiscovered(RemoteDevice rd,DeviceClass dc) which allows to remember the device

and

inquiryCompleted(int finishedFlag) where finishedFlag can be INQUIRY_COMPLETED or

INQUIRY_TERMINATED – DiscoveryListener fields

Page 149: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Bluetooth

alternatively it is possible to start the search and then fetch information on available devices via method retrieveDevices() in DiscoveryAgent (after a sleep)

services can be found in a similar manner i.e. call the following on da:

searchServices(int[] attributes,UUID[] ids,RemoteDevice rd,DiscoverListener dl);

with the following methods available in the listener implementation:

servicesDiscovered(int transaction,ServiceRecord[] srs); serviceSearchCompleted(int transaction,int code);

there may be several transactions pending in parallel (on several devices)

Page 150: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Wireless Messaging APIAPI

Page 151: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Wireless Messaging API (WMA)

Defines support for sending SMS and MMS messages between mobile devices

The device can act as a server (in which case can send and receive messages) or client (in which case sends messages)

Core interfaces used: Message TextMessage BinaryMessage MultipartMessage

Each message has an address and a timestamp

Page 152: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Wireless Messaging API (WMA)

MultipartMessage for sending MMS messages TextMessage, BinaryMessage for sending SMS messages

For SMS messages there are methods for packing and unpacking data:

void setPayloadData(String/byte[]) for TextMessage/BinaryMessage String/byte[] getPayloadData() for TextMessage/BinaryMessage

The MMS message consists of: Headers Body (consists of one or more message parts)

Page 153: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Wireless Messaging API (WMA)

MMS – most important methods: void setSubject(String subject); String getSubject(); boolean addAddress(String type, String address); void setAddress(String address); String getAddress(); void setHeader(String headerField, String headerValue); String getHeader(String headerField);

void addMessagePart(MessagePart messagePart) MessagePart getMessagePart(String contentID); MessagePart[] getMessageParts();

void setStartContentId(String contentID);– String getStartContentId();

Page 154: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Wireless Messaging API (WMA)

Each message is created using: Message newMessage(String type, address) on the Message interface

Each message can be partitioned if it is too large – safely up to 3 segments

Method int numberOfSegments(Message message)

Returns the number of segments – the application can notify the user about that e.g. higher costs

Page 155: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Wireless Messaging API (WMA)

Sending and receiving messages can be done by Methods send() and receive()

void send(Message message) Message receive()

on Message

It is recommended to register a listener which allows launching method notifyIncomingMessage(Connection) asynchronously

void setMessageListener(MessageListener messageListener)

Page 156: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File AccessAPI

Page 157: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

optional – defined within JSR 75

allows to read/write filesystems represented by e.g. additional memory cards in the devices like:

SD CF MS

and others – currently up to several Gbs e.g. SDHC up to 8GBs

each card is then represented as a separate file system with names specific for the device

data in RecordStores is safe from read/write operations offered by JSR 75

Page 158: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

JSR 75 requires at least CLDC 1.0 and uses the GCF standard i.e. obtaining a connection using

Connector.open

and opening streams for reading/writing data

specifically one can obtain a FileConnection as follows:

FileConnection fc=(FileConnection)Connector.open(“file:///RootName/filename”,Connector.READ_WRITE)

for opening the file for reading/writing. Other variations include READ and WRITE

Page 159: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

then the client can use the fc to open streams e.g.

openDataInputStream() openDataOutputStream()

or open standard streams

openInputStream() openOutputStream(long offset) openOutputStream()

Check if JSR75's File API is implemented by checking if the following is set

System.getProperty(''microedition.io.file.FileConnection.version'')

Page 160: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

Connection is obtained either for a file or a directory and the programmer can check it by calling:

boolean isDirectory()

several file/directory attributes can be checked:

boolean canRead(), setReadable(boolean) boolean canWrite(), setWritable(boolean)

boolean isHidden(), setHidden(boolean)

Page 161: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

the client can create a file with the WRITE flag and subsequently by method (Connector.open() must be called with the file name of the file to be created)

create()

mkdir() can be used to create a directory

while boolean exists() can be used to check whether the file/directory exists

there are also methods to rename: rename(String)

and delete – delete() - following Connector.open() with Connector.WRITE

Page 162: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

the client can fetch the name of the file by calling:

String getName()

String getPath() to get the full path

and the whole URL by calling

String getURL()

Page 163: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

Furthermore, it is possible to check the sizes of the filesystem/files

by calling

long directorySize() - size of the directory with all the files and subdirectories

long fileSize()

and regarding the file system:

long usedSize()

long availableSize()

Page 164: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

It is further possible to listen for mounting or removing file systems e.g. because of adding new or removing memory cards on the device

FileSystemRegistry allows to do that by calling:

addFileSystemListener(FileSystemListener fsl)

removeFileSystemListener(FileSystemListener fsl)

with the method:

rootChanged(int state,String root)

with ROOT_ADDED or ROOT_REMOVED

Root names can be implementation specific

Page 165: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

File API

the client can browse existing file systems and files/directories in the following way:

FileSystemRegistry.listRoots() which returns an Enumeration with a list of names (Strings)

then an open FileConnection offers:

Enumeration list(String filter,boolean whetherHiddenFlag) Enumeration list()

to get a list of files and directories

this allows to visit all files in a hierarchy (setFileConnection(String dirName) resets the connection for a specific directory as returned by method list()

Page 166: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

PIM API

Allows the midlet ro read and write PIM information stored on PDAs such as:

Contacts Todos Events

PIM support is optional and is defined within JSR 75

The main class is PIM and PIM PIM.getInstance() allows to fetch the singleton

openPIMList(int listType,int mode) allows to fetch a list – PIMList

Type is defined by fields in PIM:

TODO_LIST, EVENT_LIST, CONTACT_LIST

Page 167: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

PIM API

Mode can be READ_ONLY, WRITE_ONLY, READ_WRITE

The list returned should be cast to: ContactList, EventList or ToDoList

Each list has elements: PIMItems

PIMItem can be one of the following: Contact, Event or ToDo

Method Enumeration items() can return those elements.

It is possible to perform a search based on string-based fields using items(String pattern) or a template with some fields set using

items(PIMItem template)

Page 168: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

PIM API

There are several standard fields for each of those items

Furthermore each field can have one or more values – thus has an index parameter set

Each field has a data type associated with it

There are methods to set the values for each data type such as:

setInt(int field,int index,int attributes, int value) setString(int field,int index,int attributes, String value) setBinary(int field,int index,int attributes, byte[] value,int offset, int

length)

Similar methods are available for reading i.e. getInt(...) etc.

Page 169: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

PIM API

On each of the lists e.g. EventList it is possible to create an element such as:

createEvent() or createContact() for ContactList and then add elements using methods equivalent to setInt(...), etc. starting with add i.e.

AddInt(...) etc.

commit() stores the item

removeEvent(), removeContact() remove the item from the storage

Page 170: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Other important JSRs

Page 171: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Other important JSRs – APIs supported for a 2009 smartphone

JSR 139 Connected, Limited Device Configuration (CLDC) 1.1

JSR 118 MIDP 2.1

JSR 248 Mobile Service Architecture Subset for CLDC

JSR 75 FileConnection and PIM API

JSR 82 Java APIs for Bluetooth 1.1

JSR 135 Mobile Media API 1.1

JSR 172 J2ME Web Services Specification

JSR 177 Security and Trust Services API for J2ME

JSR 179 Location API for J2ME 1.1

JSR 184 Mobile 3D Graphics API for J2ME 1.1

JSR 205 Wireless Messaging API 2.0

JSR 226 Scalable 2D Vector Graphics API for J2ME 1.1

JSR 234 Advanced Multimedia Supplements 1.1

JSR 256 Mobile Sensor API

Page 172: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Sensor API

Defined by JSR 256

Allows to access and read data from sensors installed on a mobile device or attache to it e.g. an accelerometer but also sensors for measurement of light, temperature, etc. (sensor can be defined as a source of measurement data)

System.getProperty("microedition.sensor.version") allows to check support for the API

It is possible to install a listener and read data asynchronously

or read data from the sensor(s) synchronously

API available in javax.microedition.sensor

Page 173: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Sensor API

The application should open a connection with a sensor like in GCF using Connector.open()• SensorConnection is returned

Synchronous reads are performed using getData() methods - two versions available:• Data[] getData(int sizeOfBuffer):

– The number of returned objects is equal to the number of channels

– Each Data object should contain the number of values equal to sizeOfBuffer

• Data[] getData(int sizeOfBuffer, long periodForBuffering,boolean shouldTimestampBeSet, boolean shouldUncertaintyBeSet,boolean shouldValidityBeSet)

– periodForBuffering in milliseconds

Page 174: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Sensor API

Asynchronous reads require registration of a listener – DataListener• setDataListener(DataListener listener, int sizeOfBuffer)• A long version with parameters such as the second version of

getData() - the first parameter is the listener• The listener should implement method dataReceived()

Assuming the frequency of getting data is X Hz then the number of Data objects generated per second = X/sizeOfBuffer

Each channel can have a different data type associated with it – there are several methods for fetching the data e.g. getIntValues(), getDoubleValues(), getObjectValues()• It is possible to fetch the type of channel as follows:

data.getChannelInfo().getDataType() Uncertainty corresponds to the error of measurement Timestamp denotes the time when the measurement was taken

Page 175: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Mobile Sensor API

Channels depend on the sensor e.g. a sensor may return 3 coordinates: x, y and z as separate channels

The URL starts with:

sensor:<value_measured> - e.g. „acceleration”• Optional:

– model=<model_name>– location=<location>– contextType=<type>

It is possible to register launching of a midlet is response to a value of a certain channel exceeding a certain value – specified in the URL as .......&limit=20&op=ge means value>=20

or that it is in the given range e.g.: ....&lowerLimit=2&lowerOp=ge&upperLimit=8&upperOp=le

Page 176: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Security and Trust Services API

Defined within JSR 177

Consists of two parts:• Communication API – for request/response communication with

smart cards – communication as in GCF – allows communication using:

– Java Card JCRMI protocol– APDU – Application Protocol Data Unit

– In general there is an application on the card (can be created using an applet using javacard.framework.Applet) that processes commands from the client side – can implement e.g. a wallet using a PIN – communication can use APDU

• Security API– Public Key Infrastructure Signature Service API– CRYPTO Cryptographic API

Page 177: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Programming Mobile Devices Optimizations

(applicable to various programmingplatforms and APIs)

Page 178: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Possible Optimizations

do not create too many objects – especially in loops

handle OutOfMemoryError – often the emulator will not give an error while the real device will - e.g.

HelloSuite3 with downloading 10000 bytes will be OK in the emulator on the PC while will give java.lang.OutOfMemoryError on the real Palm

how to allocate memory in MIDlets? Might allocate all memory when the MIDlet starts – the easy way.

may free some memory when there is not enough and e.g. restrict features or resolution etc.

Page 179: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Possible Optimizations

optimize latency as in standard programming – refers to networking – send, download

data in batches rather than single bytes

also in general in I/O operations

use finally blocks – to exit gracefully, close connections etc. - often exception handling does not exit fully gracefully

in general finally will be executed no matter how the try block/method has executed

analyze String and StringBuffer operations – how to avoid strings being copied and created multiple times? - watch for String concatenations

Page 180: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Possible Optimizations

partition code into classes wisely – classes not used will not consume memory

obfuscators will reduce the class sizes

create responsive interfaces (threads, progress bars etc., handling all possible errors )

Page 181: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

PhonegapDevelopment of applicationsfor various mobile platforms

Page 182: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap - basics

Free and open source framework for development of applications for various mobile platforms such as:• IOS• Android• Windows Phone• Bada• Symbian

For the list of supported features look at: http://en.wikipedia.org/wiki/PhoneGap

The core technologies used by Phonegap include:• HTML5 and CSS for visual rendering• Javascript for application logic

Can be extended with plugins for some native code

Page 183: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap - basics

Supported features and functions include:• Geolocation• Accelerometer• Camera• Compass• Files• Media • Network• Storage• Notifications – alerts etc.• Contacts

Because of the general approach, Phonegap applications may be slightly slower than native solutions

Page 184: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

HTML5

What is important/interesting in HTML5?• Canvas• Media elements such as video, audio• Some new semantic/structural elements in HTML5• Geolocation http://www.w3schools.com/html/html5_geolocation.asp • WebStorage http://www.w3schools.com/html/html5_webstorage.asp • New semantic elements such as header, nav, section, figure, article

etc.• Web worker i.e. Javascript running in the background

http://www.w3schools.com/html/html5_webworkers.aspcreation of an object, termination

• Server sent events (SSE)- one-way messages sent from the server http://www.w3schools.com/html/html5_serversentevents.asp

create an EventSource and register a function for handling the onmessage event that can read the data from the server

Page 185: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap – tutorials and how-tos

There do exist various tutorials and how-tos – some recommended ones include:• Phonegap from scratch – application template, basic device APIs –

how to invoke, basic examples, handling tweets, maps, camera etc.http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch-app-template/

• How to create a HelloWorld application in Phonegap for Android?

http://mobile.tutsplus.com/tutorials/phonegap/creating-an-android-hello-world-application-with-phonegap/?search_index=9

• How to fetch data over the network from a Phonegap application using jQuery for cross-domain access?http://samcroft.co.uk/2010/loading-data-into-a-phonegap-app/

• Various tutorials:

http://phonegap.com/blog/network/

Page 186: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap – selected basic APIs

The basic structure of a Phonegap application includes:• phonegap.js – a file to be included in the application

<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>

from the root view that is included in file:• index.html – contains the startup screen visible to the user

<body onload="initialization();" > can be used to initialize some variables or display information to the user

function invocations can be easily connected to components such as buttons etc. e.g.:

let us assume the following in the body section:<input type="text" name="argument0" id="argument0" />

<a href="#" class="btn" onclick="handler();">Handle input</a> •

Page 187: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap – basic APIs

Then the script section may include handling of the button click e.g.:

<script type="text/javascript" charset="utf-8">

var handler = function() {

var name = document.getElementById("argument0").value;

navigator.notification.alert("User provided argument" + argument0);

}

</script>

Standard CSS can be used to change the view of the application i.e. styles and consequently the look of particular HTML components

Page 188: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap – basic APIs

Thus it is possible to use the Javascript solutions e.g. for networking such as using XMLHttpRequest:

An example for using asynchronous calls in Javascript:

request=new XMLHttpRequest(); // good for latest IE, Firefox etc. request.onreadystatechange=function() { if (request.readyState==4 && request.status==200) {

document.getElementById("result").innerHTML=request.responseText; } } request.open("GET","URL",true); request.send();

Page 189: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap – basic APIs

Alternatively libraries such as jQuery can be used for communication:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

...

$.get("URL",function(data,status){

alert("Data received: " + data + "\nStatus of the call: " + status);

});

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get http://api.jquery.com/jQuery.get/ Asynchronous calls in http://api.jquery.com/jQuery.ajax/

Page 190: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap - APIsAccelerator – exemplary code:

<script type="text/javascript" charset="utf-8" src="PhoneGap.js"></script>

… <script> ... function loaded(){ navigator.accelerometer.getCurrentAcceleration(gotResult,

gotError); } function gotResult(accel){ alert('In X: ' + accel.x + ' ' + 'in Y: ' + accel.y + ' ' + 'in Z: ' + accel.z + ' ' + 'taken at: ' + accel.timestamp + ' '); } function gotError(){ alert("Error"); } </script>

Page 191: Internet Mobile Services - Pawel Czarnul Home Page

© 2002-2013 Pawel Czarnul http://pczarnul.eti.pg.gda.pl email: [email protected]

Phonegap - APIsCamera – exemplary code:

<script type="text/javascript" charset="utf-8" src="PhoneGap.js"></script>

navigator.camera.getPicture( onSuccess, onError, [ options ] ).

Options can include quality, target size (width, height) etc.

Getting location can be obtained using the following API:•

navigator.geolocation.getCurrentPosition(onSuccess, onError);

Then coordinates can be obtained within onSuccess: function onSuccess(position) { position.coords.{latitude,longitude,altitude, altitudeAccuracy}

position.timstamp }