1
Java ME
Zaki BRAHMI
Equipe Ecri, Laboratoire RIADI (Universit de la Manouba, Tunisie) zakibrahmi@{[Link], [Link]}
Prsentation
Java ME = Java Micro Edition Anciennement appel J2ME (Java Plateform Micro Edition) Site : [Link] 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 : [Link]
Packages :
Interface utilisateur: [Link], [Link] [Link] : [Link] Rseau : [Link] Connexions scuriss : [Link] Core : [Link], [Link], [Link] Stockage persistent : [Link]
MIDP : Les MIDlets
Package [Link]
La classe de base de toute application MIDP. Toutes les applications MIDP hritent de la classe abstraite [Link]
Trois mthodes sont appeles pour prendre en charge le cycle de vie de la MIDlet :
startApp() pauseApp() destroyApp()
10
MIDP : Les MIDlets
import [Link]; 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 [Link] 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 = [Link](Midlet m); [Link](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([Link] title) Constructs a new, empty Alert object with the given title. Alert([Link] title, [Link] 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 [Link]([Link]), 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. [Link] 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 [Link]([Link]), however when the application removes the last command from an Alert, DISMISS_COMMAND is implicitly added. void setCommandListener(CommandListener l) The same as [Link]([Link]) but with the following additional semantics. void setImage(Image img) ; Sets the Image used in the Alert. void setString([Link] 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 = [Link](this); Form form = new Form(" tem !ayo"t"); [Link]("#ello"); [Link]("$orld"); [Link](new %tring tem("le!a&el"' "le(e)te")); [Link](new (e)tField("*ame"' +,on-o"r"' ./' (e)tField.A*0)); [Link]("Address"); [Link](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([Link] title, int listType) Creates a new, empty List, specifying its title and the type of the list. List([Link] title, int listType, [Link][] 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 :
[Link] : slection multiple [Link] : slection simple [Link] : 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:", [Link]);
private Command exit = new Command("Exit", [Link], 1); public ListImplicit() { display = [Link](this); [Link]("New", null); [Link]("Open", null); [Link](exit); [Link](this); } public void startApp() { [Link](list); } . public void commandAction(Command command, Displayable displayable) { if (command == List.SELECT_COMMAND) { String selection = [Link]([Link]()); alert = new Alert("Option Selected", selection, null, null); [Link]([Link]); [Link]([Link]); [Link](alert); } else if (command == exit) { destroyApp(false); notifyDestroyed(); } } }
21
E$em le (2*2+
lsPrefs = new List("Preferences", [Link]); [Link]("JAVA", null); [Link]("C", null); [Link]("JME", null); boolean selected[] = new boolean[[Link]()];
[Link](selected); // les lments slectionns
for (int i = 0; i < [Link](); i++) [Link]([Link](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)
[Link] allows any type of input supported by the device [Link] restricts to only integers [Link] allows numbers with fractional parts [Link] requires a telephone number [Link] requires an email address [Link] requires a web address
Exemple :
TextBox tb= new TextBox("MonText", "ecrire un test ici",1000,[Link]); TextBox(Email,64,[Link] | [Link]);
23
C![Link]
Constructeur :
ChoiceGroup choiceObj = new ChoiceGroup(StringTitle, [Link]); Type peut tre :
[Link], [Link], [Link], [Link], 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", [Link] L!"; 6. 2 p"&lic void startApp() { display = [Link](this); [Link]("7A8A"' n"ll); [Link]("7/54"' n"ll); [Link]("7/44"' n"ll); [Link]("7%F"' n"ll); [Link](element); display.set1"rrent(form); 2
25
E$em le
boolean get[] = new boolean[[Link]()]; [Link](get); for (int i = 0; i < [Link]; i++) { if (get[i]) { message[i]= new StringItem("les choix: ", [Link](i)); [Link](message[i]); } ou for(int i=0;i<[Link]();i++) { if([Link](i)) { [Link]("u selected :" + [Link](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%[Link]%ui.&; import #ava$.microe%[Link]%[Link]'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%[Link]%let.&; import #ava$.microe%[Link]%ui.&; pu(lic class 9elloMi%let e$ten%s MI'let implements Comman%Listener ) private *orm hello*orm; 'ispla, %ispl,; private .trin@Item [Link]@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*[Link]%Listener(this"; protecte% voi% start3pp(" throws MI'[Link]@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 = [Link]("/[Link]"); // Lajouter une form [Link](new ImageItem(null, img, ImageItem.LAYOUT_CENTER, null));
Peut tre : [Link] ou [Link]
31
MM&PI
Fonctionnalits multimdia :
clips audio et video, MIDI, animations, manipulation , dimages
Package : Mobile Media API (MMAPI)
[Link]
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 [Link] 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 [Link] [Link] 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 : [Link]
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 [Link](this).set1"rrent(f); :: Affiche la form la,er p = Mana@[Link] la,er("captureECCvi%eo""; [Link];e(); :: nitialise le player 8ideo1ontrol vc = (Fi%eoControl"p.@etControl("Fi%eoControl""; if (vc != n"ll) { tem it = ( tem)[Link]'ispla,Mo%e(8ideo1ontrol.U.!GGUIG /IMITIF!' n"ll); [Link](it); :: <a-o"te l=item > la form. [Link](); :: Affiche la vid9o dans l=item. 2
[Link] initDisplayMode(int mode, [Link] 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
[Link] canvas; try{ Player p=[Link]("[Link] [Link](); VideoControl vc; if ((vc =(VideoControl)[Link]("VideoControl")) != null) { [Link](VideoControl.USE_DIRECT_VIDEO, canvas); [Link](true); } [Link](); } catch (MediaException pe) { } Remarque : Il est obligatoire de crer un canvas lorsque on utilise USE_DIRECT_VIDEO
36
Messaging
Wireless Messaging API
[Link]
Permet denvoyer et de recevoir des messages SMS Bas sur le GCF (Generic Connection Framewor).
Il sagit dune sous-interface de Connection : MessageConnection. Par [Link] (String url), on obtient un objet qui implmente cette interface.
Spcification :
[Link] [Link]
37
Messaging
Envo#er un message : try { String adr = [Link] [Link] 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#[Link]%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" " [Link] [Link]( (a%%r a%%r"; "; Messa@e ms@ = null; while (some!$itCon%ition" ) CC attente %e la reception %Hun messa@e ms@ = [Link] [Link]("; ("; 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 [email protected] a,loa%Te$t(A/eceive%EB K receive%Te$t"; [Link]%( [Link]% (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 : [Link] Classe : [Link]("<protocole>://<adresse>:<parametres>"); Exemples :
pour lire un fichier : [Link] ("[Link] Tlcharger la page [Link] : [Link] ("[Link]
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; [Link] in = null; .trin@ url = "httpECClocalhostE>L>LCmi%pChits"; tr, ) hc = (9ttpConnection"[Link](url"; in = [Link]("; int contentLen@th = (int"hc.@etLen@th("; (,teMN raw = new (,teMcontentLen@thN; int len@th = [Link]%(raw"; [Link]("; [Link]("; CC *ermer la conne$ion CC traite la rponse .trin@ s = new .trin@(raw, L, len@th"; ... ?catch (I7!$ception ioe" ) ... ?
44
-i1liogra !ie
[Link] w/getstarted/[Link] Et dautre cours
j2me_wireless_toolkit-2_1-windows eclipseme.feature_1.7.9_site