Sunteți pe pagina 1din 44

1

Java ME
Zaki BRAHMI
Equipe Ecri, Laboratoire RIADI (Universit de la Manouba, Tunisie) zakibrahmi@{yahoo.fr, gmail.com}

Prsentation

Java ME = Java Micro Edition Anciennement appel J2ME (Java Plateform Micro Edition) Site : http://www.oracle.com/technetwork/java/javame/index.html Framework Java destin dans les applications embarques :

tlphonie mobile, automobile, PDA, lectromnager ,

N en 1999, de la volont de Sun de structurer ses diffrentes plateformes :

Java Card, PersonnalJava et EmbeddedJava

Prsentation

Java ME

Difficult davoir un seul environnement uniforme pour tous les appareils lectroniques :

gnralement, ils possdent des spcifications matrielles diffrentes Une configuration :

Solution de SUN :

une plateforme minimale pour des appareils de mme puissance. Elle est constitue de la machine virtuelle et des librairies bas bas-niveau niveaux. Il existe actuellement deux types de configurations : CDC et CLDC

Un profile : ensemble dAPI qui sapplique une gamme plus troite dappareils.

Il est ncessaire pour fournir un environnement de fonctionnement complet pour un type d'appareil donn.

Configuration

Spcifications pour un ensemble de priphriques ayant des caractristiques similaires comme :


Le type et la quantit mmoire disponible Le type de processeur (vitesse, etc.) Le type de rseau disponible pour ce priphrique

La plate-forme Java ME offre deux types de configurations :

Connected Limited Device Configuration (CLDC) : S'adresse aux appareils bnficiant de ressources trs limites Utilise une Kilobyte Virtual Machine (KVM) Connected Device Configuration (CDC) :

Saddresse aux appareils mobiles plus volus comme les smart phones et les boitiers TV (set-top box ) Priphriques ayant 2Mo ou plus de mmoire

Profile

Est un complment une configuration. Apporte des classes supplmentaires pour un domaine ou un march spcifique Deux type de profiles

au dessus de CLDC :

MIDP (Mobile Information Device Profile) : des composants d'IHM, la partie rseau PDA Profile : Ecran plus puissant, IHM plus riche Foundation Profile : Profil le plus basique sur CDC, Pas d'APIs graphiques, Cibles (Imprimante rseau, Routeurs, etc) RMI Profile

au dessus de CDC :

Rsum

MIDP

Trois grandes versions :


MIDP 1.0 (JSR 37 - 2000) MIDP 2.0 (JSR 118 - 2002) MIDP 3.0 (JSR 271 - 2009) Gestion de lapplication : javax.microedition.midlet

Packages :

Interface utilisateur: javax.microedition.lcdui, javax.microedition.lcdui.game Audiojavax.microedition.media : javax.microedition.media.control Rseau : javax.microedition.io Connexions scuriss : javax.microedition.pki Core : java.io, java.lang, java.util Stockage persistent : javax.microedition.rms

MIDP : Les MIDlets

Package javax.microedition

La classe de base de toute application MIDP. Toutes les applications MIDP hritent de la classe abstraite javax.microedition.MIDlet

Trois mthodes sont appeles pour prendre en charge le cycle de vie de la MIDlet :

startApp() pauseApp() destroyApp()

10

MIDP : Les MIDlets


import javax.microedition.midlet.MIDlet; public class MonMIDlet extends MIDlet { Public MonMIDlet() { super(); } protected void destroyApp( destroyApp(boolean unconditional) unconditional) { !"D" Auto#$enerated met%od stub } protected void pauseApp() pauseApp() { !"D" Auto#$enerated met%od stub } protected void startApp() startApp() { !"D" Auto#$enerated met%od stub }

11

MIDP 2.0 IHM : Les com osants gra !i"ues


Package javax.microedition.lcdui Deux sortes d'API pour la construction d'IHM :


Bas-niveau : Canvas, Game API Haut-niveau : Screen


Displayable

Canvas

Screen

GameCanvas

Alert

Form

List

TextBox

Afficher l'cran quelque chose :


Display display = Display.getDisplay(Midlet m); display.setCurrent(Displayable nextDisplayable);

12

La classe Dis la#

Offre les possibilits suivante :

obtenir des informations sur les proprits daffichage de lappareil (support de la couleur, niveaux alpha, ) demander laffichage dobjets lcran ou accder aux objets affichs.

Method Summary void callSerially(Runnable r) Causes the Runnable object r to have its run() method called later, serialized with the event stream, soon after completion of the repaint cycle. Displayable getCurrent() Gets the current Displayable object for this MIDlet. static Display getDisplay(MIDlet m) ; Gets the Display object that is unique to this MIDlet. boolean int isColor(); Gets information about color support of the device. numColors() Gets the number of colors (if isColor() is true) or graylevels (if isColor() is false) that can be represented on the device. setCurrent(Alert alert, Displayable nextDisplayable) Requests that this Alert be made current, and that nextDisplayable be made current after the Alert is dismissed. setCurrent(Displayable nextDisplayable) Requests that a different Displayable object be made visible on the display.

void

void

13

E$em le

Alert est un Displayable


Un alerte est Messages lintention de lutilisateur

On rcupre l'cran cran physique d'affichage par la mthode statique getDisplay(). On positionne un cran cr dans un composant graphique dans l'cran rel avec la mthode setCurrent()

14

%creen et &lertes

Screen : Cest la classe de Base de tous les interfaces de haut niveau. Alertes :

Messages lintention de lutilisateur Peut tre :


Limites en temps (affich pendant un certains laps de temps fix en ms) Modales (Visibles tant quune action utilisateur na pas t ralise)

Constructor Summary Alert(java.lang.String title) Constructs a new, empty Alert object with the given title. Alert(java.lang.String title, java.lang.String alertText, Image alertImage, AlertType alertType) Constructs a new Alert object with the given title, content string and image, and alert type.

15

%creen et &lertes
Method Summary void addCommand(Command cmd) Similar to Displayable.addCommand(javax.microedition.lcdui.Command), however when the application first adds a command to an Alert, DISMISS_COMMAND is implicitly removed. Gets the default time for showing an Alert. int getDefaultTimeout() ; int getHeight() Gets the height in pixels of the displayable area available for placing Image, String, and Gauge items in the Alert. Image getImage() ; Gets the Image used in the Alert. Gauge getIndicator() ; Gets the activity indicator for this Alert. java.lang.String getString() ; Gets the text string used in the Alert.

int getTimeout() ; Gets the time this Alert will be shown. void removeCommand(Command cmd) Similar to Displayable.removeCommand(javax.microedition.lcdui.Command), however when the application removes the last command from an Alert, DISMISS_COMMAND is implicitly added. void setCommandListener(CommandListener l) The same as Displayable.setCommandListener(javax.microedition.lcdui.CommandListener) but with the following additional semantics. void setImage(Image img) ; Sets the Image used in the Alert. void setString(java.lang.String str) ; Sets the text string used in the Alert. void setTimeout(int time) ; Set the time for which the Alert is to be shown.

16

'orm

Une Form est un Screen, elle occupe tout l'cran. On met des Item dans une Form qui sont :

Champs de texte (TextField), label (StringItem) DateField (TextField pour saisir des dates), Gauge, ChoiceGroup, ImageItem

17

'orm

Deux constructeurs :

Form(String title) et Form(String title, Item[] items) public void append(Item unItem) public void append(Image uneImage) public void append(String uneChaine)

On ajoute des Item dans une Form grce la mthode :

Pour les ImageItem et les StringItem, on peut utiliser les mthodes


Une Form possde au moins la taille de l'cran. Elle peut avoir plus et dans ce cas un mcanisme de scrolling est construit automatiquement

18

E$em le
protected void startApp() { if (!started) { display = Display.getDisplay(this); Form form = new Form(" tem !ayo"t"); form.append("#ello"); form.append("$orld"); form.append(new %tring tem("le!a&el"' "le(e)te")); form.append(new (e)tField("*ame"' +,on-o"r"' ./' (e)tField.A*0)); form.append("Address"); form.append(new (e)tField(n"ll' n"ll' ./' (e)tField.A*0)); display.set1"rrent(form); started = tr"e; 2 2

19

List

Hrite directement de Screen et Implmente l'interface Choice Elle occupe tout l'cran. Elle possde 2 constructeurs :
Constructor Summary List(java.lang.String title, int listType) Creates a new, empty List, specifying its title and the type of the list. List(java.lang.String title, int listType, java.lang.String[] stringElements, Image[] imageElements) Creates a new List, specifying its title, the type of the List, and an array of Strings and Images to be used as its initial contents.

Les listes sont soit :


List.MULTIPLE : slection multiple List.EXCLUSIVE : slection simple List.IMPLICIT : slection simple et confirmation

20

E$em le ()*2+
public class ListImplicit extends MIDlet implements CommandListener { private Display display; Alert alert;

private List list = new List("Menu:", List.IMPLICIT);


private Command exit = new Command("Exit", Command.EXIT, 1); public ListImplicit() { display = Display.getDisplay(this); list.append("New", null); list.append("Open", null); list.addCommand(exit); list.setCommandListener(this); } public void startApp() { display.setCurrent(list); } . public void commandAction(Command command, Displayable displayable) { if (command == List.SELECT_COMMAND) { String selection = list.getString(list.getSelectedIndex()); alert = new Alert("Option Selected", selection, null, null); alert.setTimeout(Alert.FOREVER); alert.setType(AlertType.INFO); display.setCurrent(alert); } else if (command == exit) { destroyApp(false); notifyDestroyed(); } } }

21

E$em le (2*2+
lsPrefs = new List("Preferences", List.MULTIPLE); lsPrefs.append("JAVA", null); lsPrefs.append("C", null); lsPrefs.append("JME", null); boolean selected[] = new boolean[lsPrefs.size()];

lsPrefs.getSelectedFlags(selected); // les lments slectionns


for (int i = 0; i < lsPrefs.size(); i++) System.out.println(lsPrefs.getString(i) + (selected[i] ? ": selected" : ": not selected"));

22

,e$t-o$

Hrite directement de la classe Screen Permet d'afficher un champ de texte, ditable par l'utilisateur Constructeur :

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


TextField.ANY allows any type of input supported by the device TextField.NUMERIC restricts to only integers TextField.DECIMAL allows numbers with fractional parts TextField.PHONENUMBER requires a telephone number TextField.EMAILADDR requires an email address TextField.URL requires a web address

Exemple :

TextBox tb= new TextBox("MonText", "ecrire un test ici",1000,TextField.ANY); TextBox(Email,64,TextField.ANY | TextField.PASSWORD);

23

C!oice.rou

Constructeur :

ChoiceGroup choiceObj = new ChoiceGroup(StringTitle, Choice.Type); Type peut tre :


Choice.EXCLUSIVE, Choice.IMPLICIT, Choice.MULTIPLE, Choice.POPUP, Choice.TEXT_WRAP_DEFAULT, Choice.TEXT_WRAP_OFF, and Choice.TEXT_WRAP_ON.

24

E$em le
p"&lic class 1hec3,o)4)emple e)tends 5 Dlet { private Display display; private Form form; private ChoiceGroup element; p"&lic 1hec3,o)4)emple() { form = new Form("(echnologies"); element = new ChoiceGroup("Choisir un lment", Choice.MULTI L!"; 6. 2 p"&lic void startApp() { display = Display.getDisplay(this); element.append("7A8A"' n"ll); element.append("7/54"' n"ll); element.append("7/44"' n"ll); element.append("7%F"' n"ll); form.append(element); display.set1"rrent(form); 2

25

E$em le

boolean get[] = new boolean[element.size()]; element.getSelectedFlags(get); for (int i = 0; i < get.length; i++) { if (get[i]) { message[i]= new StringItem("les choix: ", element.getString(i)); form.append(message[i]); } ou for(int i=0;i<element.size();i++) { if(element.isSelected(i)) { System.out.println("u selected :" + element.getString(i); }

26

Interaction avec l/utilisateur : Comman0

Permet d'interagir avec l'utilisateur via :

button, un menu ou tout autre interface

Un objet de la classe Command est un "bouton MIDP" que l'utilisateur va pouvoir actionner l'aide des touches clavier. La commande est ajoute un objet Displayable Constructeur : Command (String label, int type, int priority) Diffrents types de Command existent :

BACK, CANCEL, EXIT, HELP, ITEM, OK, SCREEN et STOP

La commande est plac sur l'cran en fonction de la priorit. Fonctionnement :


couter les commandes : implmenter l'interface CommandListener Implmenter les actions void commandAction (Command c, Displayable d)

27

E$em le )
import #ava$.microe%ition.lc%ui.&; import #ava$.microe%ition.mi%let.MI'let; pu(lic class Comman%MI'let e$ten%s MI'let) private *orm +orm; private 'ispla, %ispla,; private Comman% screen, (ac-, cancel, o-, help, stop, e$it, item; pu(lic Comman%MI'let(") screen = new Comman%(".creen", Comman%..C/!!0, 1"; (ac- = new Comman%("2ac-", Comman%.23C4, 5"; cancel = new Comman%("Cancel", Comman%.C30C!L, 6"; o- = new Comman%("7-", Comman%.74, 8"; help = new Comman%("9elp", Comman%.9!L , :"; stop = new Comman%(".top", Comman%..T7 , ;"; e$it = new Comman%("!$it", Comman%.!<IT, ="; item = new Comman%("Item", Comman%.IT!M, >"; ?

28

E$em le 2 ()*2+
import #ava$.microe%ition.mi%let.&; import #ava$.microe%ition.lc%ui.&; pu(lic class 9elloMi%let e$ten%s MI'let implements Comman%Listener ) private *orm hello*orm; 'ispla, %ispl,; private .trin@Item hello.trin@Item; private Comman% e$itComman%; pu(lic 9elloMi%let(" )%ispl, = 'ispla,.@et'ispla,(this"; hello*orm = new *orm(A2on#ourB"; e$itComman% = new Comman%("!$it", man%.!<IT, 1" hello*orm.a%%Comman%(e$itComman%"; hello*orm.setComman%Listener(this"; protecte% voi% start3pp(" throws MI'let.tateChan@e!$ception ) CC T7'7 3utoD@enerate% metho% stu( %ispla,.setCurrent(hello*orm"; } ?

29

E$em le (2*2+
pu(lic voi% comman%3ction(Comman% comman%, 'ispla,a(le %ispla,a(le" ) i+ (%ispla,a(le == hello*orm" ) i+ (comman% == e$itComman%" e$itMI'let("; ? ? pu(lic voi% e$itMI'let(" ) @et'ispla,(".setCurrent(null"; %estro,3pp(true"; noti+,'estro,e%("; ? ?

30

Image
1. Constructeurs :
Image createImage(String name) ImageItem(String label, Image img, int layout, String altText) ou ImageItem(String label, Image img, int layout, String altText, int appMode )

2. Affichage sur une Form:

Form f = new Form("Images"); ... // Create an image Image img = Image.createImage("/isitCom.png"); // Lajouter une form f.append(new ImageItem(null, img, ImageItem.LAYOUT_CENTER, null));

Peut tre : Item.HYPERLINK ou Item.BUTTON

31

MM&PI
Fonctionnalits multimdia :
clips audio et video, MIDI, animations, manipulation , dimages

Package : Mobile Media API (MMAPI)


javax.microedition.media

4 classes principales pour utiliser l'API :


- Manager, Player, Control, Datasource

DataSource :
Soccupe des protocoles et synchronisation. Il est transparent en ce qui concerne la faon de lire (un fichier, par streaming, etc.), et en ce qui concerne le moyen de transport (http, streming, etc.)

32

MM&PI : Manager
La classe Manager contient uniquement des mthodes statiques : La mthode Manager.createPlayer cr un player avec un DataSource associ, pour lui fournir les donnes. La source de donnes peut tre construite partir d'un flux (InputStream) ou d'un " URI-style locator ".
URI-style locator file:///c:/nokia/Images/Image001.jpg http://adresseweb.com/fichier.wav capture://image capture://video capture://audio Source de donnes Un simple fichier Une adresse web Capturer une photo depuis l'appareil photo Capturer une vido Enregistrer du son

33

MM&PI : Controle
Package : javax.microedition.media.control
Interface Summary
FramePositioningControl GUIControl MetaDataControl MIDIControl PitchControl RateControl RecordControl StopTimeControl TempoControl ToneControl VideoControl VolumeControl is the interface to control precise positioning to a video frame for Players. GUIControl extends Control and is defined for controls that provide GUI functionalities. MetaDataControl is used to retrieve metadata information included within the media streams. MIDIControl provides access to MIDI rendering and transmitting devices. PitchControl raises or lowers the playback pitch of audio without changing the playback speed. RateControl controls the playback rate of a Player. RecordControl controls the recording of media from a Player. StopTimeControl allows one to specify a preset stop time for a Player. TempoControl controls the tempo, in musical terms, of a song. ToneControl is the interface to enable playback of a user-defined monotonic tone sequence. VideoControl controls the display of video. VolumeControl is an interface for manipulating the audio volume of a Player.

34

E$em le
Form f = new Form("vid9o Form"); :: 1r9e la form principale Display.getDisplay(this).set1"rrent(f); :: Affiche la form la,er p = Mana@er.create la,er("captureECCvi%eo""; p.reali;e(); :: nitialise le player 8ideo1ontrol vc = (Fi%eoControl"p.@etControl("Fi%eoControl""; if (vc != n"ll) { tem it = ( tem)vc.init'ispla,Mo%e(8ideo1ontrol.U.!GGUIG /IMITIF!' n"ll); f.append(it); :: <a-o"te l=item > la form. p.start(); :: Affiche la vid9o dans l=item. 2
java.lang.Object initDisplayMode(int mode, java.lang.Object arg) Initialiser le mode de la faon dont la vido est affiche. Cette mthode doit tre appele avant que la vido sera affiche. Mode peut tre : USE_GUI_PRIMITIVE (hrit de GUIControl), USE_DIRECT_VIDEO (ne peut tre utilis quavec LCDUI support)

35

E$em le
javax.microedition.lcdui.Canvas canvas; try{ Player p=Manager.createPlayer("http://mymachine/abc.mpg"); p.realize(); VideoControl vc; if ((vc =(VideoControl)p.getControl("VideoControl")) != null) { vc.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, canvas); vc.setVisible(true); } p.start(); } catch (MediaException pe) { } Remarque : Il est obligatoire de crer un canvas lorsque on utilise USE_DIRECT_VIDEO

36

Messaging

Wireless Messaging API

javax.wireless.messaging

Permet denvoyer et de recevoir des messages SMS Bas sur le GCF (Generic Connection Framewor).

Il sagit dune sous-interface de Connection : MessageConnection. Par Connector.open (String url), on obtient un objet qui implmente cette interface.

Spcification :

http://www.oracle.com/technetwork/java/wma2-137168.html http://www.inf.unibz.it/~ricci/MS/Material/wma-1_1-mr-spec.pdf

37

Messaging
Envo#er un message : try { String adr = sms://+21623454500; sms://+21623454500; MessageConne tion onn = !MessageConne tion"Conne tor#o$en!adr"; %e&tMessage msg=!%e&tMessage" onn#ne'Message!MessageConne tion#%()%*M(SS+,( %()%*M(SS+,("; msg#set-ay.oad%e&t!/e..o 0or.d1"; onn#send!msg"; 2 at 3 !(& e$tion e" {###2

38

Messaging
Application serveur qui attend un message envoy au port 5432 et le rpond :

.trin@ a%%r = AsmsECC:865B; Messa@eConnection conn = ( (Messa@eConnection Messa@eConnection" " Connector.open Connector.open( (a%%r a%%r"; "; Messa@e ms@ = null; while (some!$itCon%ition" ) CC attente %e la reception %Hun messa@e ms@ = conn.receive conn.receive("; ("; CC messa@e reIu i+ (ms@ instanceo+Te$tMessa@e" ) Te$tMessa@e tms@ = (Te$tMessa@e"ms@; .trin@ receive%Te$t = tms@.@et a,loa%Te$t("; CC rponse avec lHentJte A/eceive%EB tms@.set a,loa%Te$t(A/eceive%EB K receive%Te$t"; conn.sen%( conn.sen% (tms@ tms@"; "; ? else ) CC messa@e reIu est (inaire ... ? ?? catch (!$ception e" ) ...?

tr, )

39

Rseau
l'API de J2EE ddie au rseau, aux entres / sorties et au stockage est trop lourde pour lutiliser dans le contexte des terminaux CLDC. Elle est remplace dans la CLDC par le GCF (Generic Connection Framework).

Le GCF assure une plus grande cohrence entre les diffrents types d'entres / sorties tout en amliorant la portabilit des applications. Package : javax.microedition.io Classe : Connector.open("<protocole>://<adresse>:<parametres>"); Exemples :

pour lire un fichier : Connector.open ("file://monfichier.txt"); Tlcharger la page google.fr : Connector.open ("http://www.yahoo.fr");

40

La classe Connection

41

Protocoles 0e communication our mo1iles

Les fournisseurs de rseau pour mobiles ne fournissent pas toujours de connection socket ou TCP

Oui dans les mulateurs Mais cela peut exister :

sur les PDA en payant (trs) cher

Le protocole support est HTTP

42

Le rotocole H,,P

Dans MIDP, le seul protocole rellement support est HTTP Car en gnral, les mobiles n'ont pas de communication directe "l'internet (TCP)" rappel : HTTP est un protocole requte rponse Il suffit d'indiquer l'URL et chaque getXXX() rcupre immdiatement la rponse.

43

E$em le
9ttpConnection hc = null; Input.tream in = null; .trin@ url = "httpECClocalhostE>L>LCmi%pChits"; tr, ) hc = (9ttpConnection"Connector.open(url"; in = hc.openInput.tream("; int contentLen@th = (int"hc.@etLen@th("; (,teMN raw = new (,teMcontentLen@thN; int len@th = in.rea%(raw"; in.close("; hc.close("; CC *ermer la conne$ion CC traite la rponse .trin@ s = new .trin@(raw, L, len@th"; ... ?catch (I7!$ception ioe" ) ... ?

44

-i1liogra !ie

http://www.oracle.com/technetwork/java/javame/javamobile/overvie w/getstarted/index.html Et dautre cours

j2me_wireless_toolkit-2_1-windows eclipseme.feature_1.7.9_site

S-ar putea să vă placă și