Recherche :

Développement mobile avec Netbeans 6.1 : Réalisez votre propre client mail

Netbeans est un environnement particulièrement bien adapté au développement d’applications pour mobile. Découvrons à travers ce tutoriel les différentes fonctionnalités offertes par l’outil à travers la réalisation d’une application mobile simple : un client mail pour compte POP3.

Nous traiterons des technologies :
- Java, J2ME
- Socket
- POP3

1. : Création du projet

- La première étape consiste à créer l’application MIDP (Mobile Information Device Profile).

- Après avoir cliqué sur le bouton « Next », l’interface vous propose de renseigner le nom de votre application.

Nota : Les autres écrans ne requièrent pas de modifications particulières de votre part. Vous pouvez cliquer sur « Next » puis « Finish » jusqu'à la fin de l’assistant.

2. Préparation de l’interface

Vous êtes à présent sur l’éditeur de flux. Il s’agit d’un outil très pratique utilisé pour définir la cinétique de l’application : nous retrouvons les différents écrans ainsi que les conditions de passage entre ces différents écrans.

Voyons à présent comment utiliser cet éditeur pour insérer très simplement un écran d’accueil :
• Dans la palette, sélectionnez un « splash screen » et glissez-le dans la zone d’édition.
• Redéfinissez les liens de façon à ce que ce nouvel écran soit intercalé entre le démarrage et le premier formulaire (form dans notre cas)

3.

Voilà ce que vous devez obtenir :

Nota : pour créer un lien, il convient de cliquer sur l’état (ex : started) et tirer le lien vers l’écran de destination.

4.

Il convient maintenant de préciser le contenu du « splash screen » :
• Dans la fenêtre des Propriétés, sélectionnez l’image à afficher
• Cocher « Full Screen »

5. envoi et réception des données par socket

La prochaine étape consiste à écrire le code pour la lecture et l’écriture des sockets pour l’accès au compte mail POP3 :
- Créer l’objet SocketConnection en paramétrant le constructeur avec l’adresse du compte POP3

sc = (SocketConnection) Connector.open("socket://pop3.XXXX.fr:110");
is = sc.openInputStream();
os = sc.openOutputStream();

- Implémenter à présent les fonctions de lecture / écriture

Lecture :
public StringBuffer recupererString(InputStream is) {
StringBuffer sb = new StringBuffer();
int c = 0;
try {
while ((c = is.read()) != 10) {
sb.append((char) c);
}
} catch (Exception e) {
sb.append("Erreur");
}
return sb;
}

Ecriture :
public void envoyerString(OutputStream os, String s) throws IOException {
try {
os.write(s.getBytes());
} catch (IOException ex) {
ex.printStackTrace();
}
os.flush();
}

Ces fonctions sont simples : il s’agit de lire ou d’écrire des chaînes de caractères.

- Il nous reste plus qu’à coder l’échange des transactions avec le compte POP3 :

// lecture du message d'accueil
sbFinal.append("\n" + recupererString(is));
// envoi identifiant: login
envoyerString(os, "USER vincent.perdereau@test.net\n");
// récupération message OK, saisie Mot de passe
sbFinal.append("\n" + recupererString(is));
// envoi mot de passe
envoyerString(os, "PASS xxxx\n");
// récupération message OK
sbFinal.append("\n" + recupererString(is));
// nombre de messages ?
envoyerString(os, "LIST\n");
sbFinal.append("\n" + recupererString(is));

Notre exemple se limite ici à déterminer le nombre de messages présents dans la boite aux lettres. N’hésitez pas à aller plus loin et venir présenter le fruit de vos travaux sur le forum de Programmez !

6. test & déploiement de l’application

- Appuyer sur Lancement pour tester l’application

- Pour déployer l’application sur votre mobile, il vous suffit de copier le fichier .jar situé dans le répertoire ‘dist’ de votre projet.

7.

8. Code complet

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package hello;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import org.netbeans.microedition.lcdui.SplashScreen;

/**
* @author vincent
*/
public class HelloMIDlet extends MIDlet implements CommandListener {

private boolean midletPaused = false;

// private Command exitCommand;
private Image image1;
private Image image;
private SplashScreen splashScreen;
private Form form;
private StringItem stringItem;
//

/**
* The HelloMIDlet constructor.
*/
public HelloMIDlet() {
}

// //

// /**
* Initilizes the application.
* It is called only once when the MIDlet is started. The method is called before the startMIDlet method.
*/
private void initialize() {
// write pre-initialize user code here
// write post-initialize user code here
}
//

// /**
* Performs an action assigned to the Mobile Device - MIDlet Started point.
*/
public void startMIDlet() {
// write pre-action user code here
switchDisplayable(null, getSplashScreen());
// write post-action user code here
}
//

// /**
* Performs an action assigned to the Mobile Device - MIDlet Resumed point.
*/
public void resumeMIDlet() {
// write pre-action user code here
// write post-action user code here
}
//

// /**
* Switches a current displayable in a display. The display instance is taken from getDisplay method. This method is used by all actions in the design for switching displayable.
* @param alert the Alert which is temporarily set to the display; if null, then nextDisplayable is set immediately
* @param nextDisplayable the Displayable to be set
*/
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
// write pre-switch user code here
Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
// write post-switch user code here
}
//

// /**
* Called by a system to indicated that a command has been invoked on a particular displayable.
* @param command the Command that was invoked
* @param displayable the Displayable where the command was invoked
*/
public void commandAction(Command command, Displayable displayable) {
// write pre-action user code here
if (displayable == form) {
if (command == exitCommand) {
// write pre-action user code here
exitMIDlet();
// write post-action user code here
}
} else if (displayable == splashScreen) {
if (command == SplashScreen.DISMISS_COMMAND) {
// write pre-action user code here
switchDisplayable(null, getForm());
// write post-action user code here
}
}
// write post-action user code here
}
//

// /**
* Returns an initiliazed instance of exitCommand component.
* @return the initialized component instance
*/
public Command getExitCommand() {
if (exitCommand == null) {
// write pre-init user code here
exitCommand = new Command("Exit", Command.EXIT, 0);
// write post-init user code here
}
return exitCommand;
}
//

// /**
* Returns an initiliazed instance of form component.
* @return the initialized component instance
*/
public Form getForm() {
if (form == null) {
// write pre-init user code here
form = new Form("Webmail - Programmez!", new Item[] { getStringItem() });
form.addCommand(getExitCommand());
form.setCommandListener(this);
// write post-init user code here
}
return form;
}
//

public StringBuffer recupererString(InputStream is) {
StringBuffer sb = new StringBuffer();
int c = 0;
try {
while ((c = is.read()) != 10) {
sb.append((char) c);
}
} catch (Exception e) {
sb.append("Erreur");
}
return sb;
}

public void envoyerString(OutputStream os, String s) throws IOException {
try {
os.write(s.getBytes());
} catch (IOException ex) {
ex.printStackTrace();
}
os.flush();
}
public String Connexion() {
SocketConnection sc;
InputStream is;
OutputStream os;
StringBuffer sbFinal = new StringBuffer();

try {
sc = (SocketConnection) Connector.open("socket://pop3.xxxxx.fr:110");
is = sc.openInputStream();
os = sc.openOutputStream();

// lecture du message d'accueil
sbFinal.append("\n" + recupererString(is));
// envoi identifiant: login
envoyerString(os, "USER xxxxxxxx\n");
// récupération message OK, saisie Mot de passe
sbFinal.append("\n" + recupererString(is));
// envoi mot de passe
envoyerString(os, "PASS xxxxxxx*\n");
// récupération message OK
sbFinal.append("\n" + recupererString(is));
// nombre de messages ?
envoyerString(os, "LIST\n");
sbFinal.append("\n" + recupererString(is));

return "" + sbFinal;

//return sb.toString();
} catch (Exception e) {
return "erreur";
}
}
// /**
* Returns an initiliazed instance of stringItem component.
* @return the initialized component instance
*/
public StringItem getStringItem() {
if (stringItem == null) {
// write pre-init user code here
stringItem = new StringItem("Dialogue POP3", "");
// write post-init user code here
stringItem.setText(Connexion());
}
return stringItem;
}
//

// /**
* Returns an initiliazed instance of splashScreen component.
* @return the initialized component instance
*/
public SplashScreen getSplashScreen() {
if (splashScreen == null) {
// write pre-init user code here
splashScreen = new SplashScreen(getDisplay());
splashScreen.setTitle("splashScreen");
splashScreen.setCommandListener(this);
splashScreen.setFullScreenMode(true);
splashScreen.setTimeout(2000);
// write post-init user code here
}
return splashScreen;
}
//

// /**
* Returns an initiliazed instance of image component.
* @return the initialized component instance
*/
public Image getImage() {
if (image == null) {
// write pre-init user code here
try {
image = Image.createImage("/logo_programmez.jpg");
} catch (java.io.IOException e) {
e.printStackTrace();
}
// write post-init user code here
}
return image;
}
//

// /**
* Returns an initiliazed instance of image1 component.
* @return the initialized component instance
*/
public Image getImage1() {
if (image1 == null) {
// write pre-init user code here
image1 = Image.createImage(1, 1);
// write post-init user code here
}
return image1;
}
//

/**
* Returns a display instance.
* @return the display instance.
*/
public Display getDisplay () {
return Display.getDisplay(this);
}

/**
* Exits MIDlet.
*/
public void exitMIDlet() {
switchDisplayable (null, null);
destroyApp(true);
notifyDestroyed();
}

/**
* Called when MIDlet is started.
* Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
*/
public void startApp() {
if (midletPaused) {
resumeMIDlet ();
} else {
initialize ();
startMIDlet ();
}
midletPaused = false;
}

/**
* Called when MIDlet is paused.
*/
public void pauseApp() {
midletPaused = true;
}

/**
* Called to signal the MIDlet to terminate.
* @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
*/
public void destroyApp(boolean unconditional) {
}

}

Programmez! n° 133
Le numéro 133 de Programmez! est disponible en kiosque.





Proposer un tutoriel
Vous souhaitez partagez vos connaissances avec les membres de Programmez! Publiez vos tutoriels.

L'auteur
vincentperdereau (Vincent PERDEREAU)
Vincent Perdereau
vincent.perdereau@ads-com.fr
Chef de projet / Société ads-COM



De A à Z
Programmez.com - 2010 - Tous droits réservés
Développement - WEB - ASP - PHP - C++ - Delphi - Java - Magazines - Ressources - Forum - Télécharger - Video - Emploi - Campus - .Net - Tutoriels

Le portail du décideur informatique en entreprise : Solutions & Logiciels