Está en la página 1de 17

Manual de desarrollo de

aplicaciones en 12ME

Versin del documento: 1.0
Fecha del documento: 17 de Marzo de 2002
2
ndice

INDICE....................................................................................................................................................... 2
1. INTRODUCCIN............................................................................................................................. 3
1.1.1. Instolocion e inicio oe hireless 1oolkit ............................................................................... 3
1.1.2. Creor nuevo provecto........................................................................................................... !
1.1.3. Desorrollo oel progromo ..................................................................................................... 5
1.1.4. Compilocion v oepurocion................................................................................................... 5
2. REFERENCIAS................................................................................................................................. 5
3. ANEXOS............................................................................................................................................. 6
3.1. ANEXO A: EJEMPLOS DE APLICACIONES J2ME............................................................................. 6
3.1.1. Eiemplo 1. Jisor oe imogenes ............................................................................................. 6
3.1.2. Eiemplo 2. Alormo............................................................................................................. 10
3.1.3. Eiemplo 3. 1imer ............................................................................................................... 1!
3
1. Introduccin
Los pasos a seguir para crear una aplicacin Java para nuestro terminal Java-
enabled. Lo primero de todo ser conseguir e instalar los entornos de
desarrollo necesarios para empezar a desarrollar:

- J2SDK 1.3 (o superior)

Proporciona la base sobre la que se instalan el resto de
aplicaciones.

- J2ME Wireless Toolkit 1.0.1 (o superior)

Ofrece un entorno de compilacin, depuracin y ejecucin para la creacin de
MIDlets bajo la plataforma J2ME.

Una vez instalados todos estos componentes comenzaremos el proceso de
desarrollo. Para ello se seguirn los siguientes pasos:

1.1.1. InstaIacin e inicio de WireIess TooIkit

Nota: Durante la instalacin de este programa se preguntar al usuario entre
dos tipos de instalacin: Integrated y Stand Alone.

- La primera permitir a aquellos usuarios de Forte for Java crear aplicaciones (MIDlets) desde
dicho entorno, para lo cual deber estar instalado ya el programa.
- La segunda opcin no incluye esta posibilidad y ser el usuario el que edite el cdigo fuente
con el programa que desee.

Una vez instalado correctamente este software de desarrollo se
instalar en nuestro men Inicio un acceso directo al programa. Para
iniciarlo nos bastar con ejecutar el icono kToolbar que ejecutar el
programa principal del Wireless Toolkit.
Nota: En algunos sistemas operativos como Windows NT o
Windows 2000 puede que no se cree este acceso al programa. En
este caso bastar con ejecutar el fichero ktoolbar.bat del directorio
bin de la aplicacin.

4
1.1.2. Crear nuevo proyecto

Para iniciar el desarrollo de un nuevo proyecto pulsaremos el botn New
Project de la pantalla principal de la aplicacin.

Durante la creacin de un nuevo proyecto deberemos incluir el nombre del
proyecto y de la clase principal.

Adems aparecer una pantalla de preferencias donde se debern configurar
opciones del MIDlet

5
Como resultado de la creacin del nuevo proyecto se crearn una serie de
directorios a partir del directorio j2mewt/apps que son:

bin: Contiene los ficheros resultantes de la compilacin y verificacin del
cdigo.
res: Contiene los recursos que se van a utilizar, por ejemplo, imgenes,
ficheros de datos, etc
src: Contiene el cdigo fuente de las clases que componen la aplicacin.
Todos los ficheros *.java deben encontrarse en este directorio.
cIasses y tmpcIasses: Directorios secundarios con clases temporales
de la aplicacin.

1.1.3. DesarroIIo deI programa

La aplicacin se podr desarrollar con cualquier editor de textos, la nica
limitacin es que los ficheros residan en los directorios antes mencionados.
Para crear una aplicacin el programador deber ceirse al API ofrecido por el
entorno MIDP de J2ME.
(Debido a la extensin de este API se recomienda consultar la versin HTML
del mismo para ms informacin).

1.1.4. CompiIacin y depuracin

La fase de compilacin se deber efectuar bajo el entorno del Wireless Toolkit.
Este entorno ofrece una serie de posibilidades de depuracin y emulacin que
dependen de la versin instalada.

Una vez creados los ficheros fuentes y colocados en el directorio src
anteriormente comentado se pulsar el botn Build de la pantalla principal. En
ese momento se realiza la compilacin, preverificacin de clases y
empaquetamiento de todos los recursos (clases, imgenes, datos, etc..)
necesarios para la ejecucin. Los ficheros resultantes son dos: fichero.jar y
fichero.jad.
El primero es propiamente el fichero que contiene la aplicacin en s. El
segundo contiene la definicin de los datos existentes en el anterior fichero.
2. Referencias

En los siguientes links encontrar numerosa informacin sobre J2ME:

x http://wireless.java.sun.com
6
x http://www.java.sun.com
x http://www.corej2me.com
x http://www.cswl.com
x http://www.billday.com

3. Anexos
3.1. Anexo A: EjempIos de apIicaciones J2ME

Las siguientes aplicaciones son un ejemplo de las facilidades que permite
Java para dispositivos mviles:

3.1.1. EjempIo 1: Visor de imgenes

La siguiente aplicacin consiste en un visor de imgenes en formato PNG.
Estas imgenes las obtiene de la URL que le especifiquemos, haciendo una
conexin y descargando la imagen para visualizarla.

El cdigo fuente de esta aplicacin es el siguiente:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
/*--------------------------------------------------
* Main class definition
*-------------------------------------------------*/
public class pngViewer extends MIDlet implements CommandListener
{
private Display display;
private TextBox tbxMain;
private Form frmViewPng;
private Command cmdExit;
private Command cmdView;
private Command cmdBack;
/*--------------------------------------------------
* Constructor for the class.
*-------------------------------------------------*/
public pngViewer()
7
{
display = Display.getDisplay(this);
// Create the Main textbox with a maximum of 50 characters
tbxMain = new TextBox("Enter png url",
"http://www.corej2me.com/scratch/spin.png", 50, 0);
// Create commands and add to textbox
cmdView = new Command("View", Command.SCREEN, 1);
cmdExit = new Command("Exit", Command.SCREEN, 1);
tbxMain.addCommand(cmdView );
tbxMain.addCommand(cmdExit);
// Set up a listener to "capture" button presses
tbxMain.setCommandListener(this);
// ---------------------------------------
// Create the form that will hold the png image
frmViewPng = new Form("Png Image");
// Create commands and add to form
cmdBack = new Command("Back", Command.BACK, 1);
frmViewPng.addCommand(cmdBack);
// Set up a listener to "capture" button presses
frmViewPng.setCommandListener(this);
}
/*--------------------------------------------------
* Called by the Application Manager on the device
* to start the MIDlet.
*-------------------------------------------------*/
public void startApp()
{
// Display the Main textbox
display.setCurrent(tbxMain);
}
/*--------------------------------------------------
* A required method.
* Does nothing in this MIDlet
*-------------------------------------------------*/
public void pauseApp()
{
}
/*--------------------------------------------------
* A required method.
* Does nothing in this MIDlet
8
*-------------------------------------------------*/
public void destroyApp(boolean unconditional)
{
}
/*--------------------------------------------------
* Process events
*-------------------------------------------------*/
public void commandAction(Command c, Displayable s)
{
// If the Command button pressed was "Exit"
if (c == cmdExit) {
destroyApp(false);
notifyDestroyed();
} else if (c == cmdView) { // If the Command button pressed was "View"
// Remove anything that may be on the form
if (frmViewPng.size() > 0)
for (int i = 0; i < frmViewPng.size(); i++)
frmViewPng.delete(i);
// Get the image from the web and append to the form
Image img;
if ((img = getImage(tbxMain.getString())) != null)
frmViewPng.append(img);
// Display the form with the image
display.setCurrent(frmViewPng);
} else if (c == cmdBack) { // If the Command button pressed was "Back"
display.setCurrent(tbxMain);
}
}
/*--------------------------------------------------
* Open an http connection and download a png file
* into a byte array.
*-------------------------------------------------*/
private Image getImage(String imageStr)
{
try
{
HttpConnection conn = (HttpConnection) Connector.open(imageStr);
// Check to see if we successfully opened the connection
int response = conn.getResponseCode();
9
if(conn.getResponseCode() == HttpConnection.HTTP_OK )
{
int length = (int) conn.getLength();
if (length > 0)
{
byte imageData[] = new byte[length];
InputStream in = conn.openInputStream();
// Read the png into an array
in.read(imageData);
// Create the image from the byte array
return Image.createImage(imageData, 0, length);
}
}
else
{
frmViewPng.append("Error getting png");
}
}
catch (IOException e)
{
frmViewPng.append("IO Error");
}
return null;
}
}
De la ejecucin de esta aplicacin se obtiene una serie de pantallas como
estas:

10
3.1.2. EjempIo 2: AIarma
Esta aplicacin consiste en una simple alarma programable que emite un
pitido al llegar la hora fijada.

El cdigo fuente de esta aplicacin es el siguiente:

import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Timer;
import java.util.TimerTask;
public class alarm extends MIDlet implements ItemStateListener,
CommandListener
{
private Display display; // Reference to display object
private Form frmMain; // The main form
private Command cmdalarm; // Start the timer
private Command cmdReset; // Reset to current date/time
private Command cmdExit; // Exit the MIDlet
private DateField dtfalarmTime; // How long to sleep
private int dateIndex; // Index of the DateField on the Form
private Date currentTime; // Current time...changes when pressing reset
private Timer timerMaster; // The timer - keeps track of system time
private alarmTimer timerSlave; // Called by the timer
private boolean dateOK = false; // Was the user input valid?
public alarm()
{
display = Display.getDisplay(this);
// The main form
frmMain = new Form("When to sound the alarm:");
// Save today's date
currentTime = new Date();
// DateField with todays date as a default
dtfalarmTime = new DateField("", DateField.DATE_TIME);
dtfalarmTime.setDate(currentTime);
// All the commands/buttons
cmdalarm = new Command("Sleep", Command.SCREEN, 1);
cmdReset = new Command("Reset", Command.SCREEN, 1);
cmdExit = new Command("Exit", Command.EXIT, 1);
11
// Add to form and listen for events
dateIndex = frmMain.append(dtfalarmTime);
frmMain.addCommand(cmdalarm);
frmMain.addCommand(cmdReset);
frmMain.addCommand(cmdExit);
frmMain.setCommandListener(this);
frmMain.setItemStateListener(this);
}
public void startApp ()
{
display.setCurrent(frmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void itemStateChanged(Item item)
{
if (item == dtfalarmTime)
{
// If the user selected date and/or time that is earlier
// than today, set a flag. We are using getTime()
// method of the Date class, which returns the # of
// milliseconds since January 1, 1970
if (dtfalarmTime.getDate().getTime() < currentTime.getTime())
dateOK = false;
else
dateOK = true;
}
}
public void commandAction(Command c, Displayable s)
{
if (c == cmdalarm)
{
if (dateOK == false)
{
Alert alr = new Alert("Unable to set alarm", "Please choose another date
and time.", null, null);
alr.setTimeout(Alert.FOREVER);
alr.setType(AlertType.ERROR);
display.setCurrent(alr);
}
else
{
// Create a new timer
12
timerMaster = new Timer();
alarmTimer timerSlave = new alarmTimer();
// Amount of time to delay
long amount = dtfalarmTime.getDate().getTime() - currentTime.getTime();
timerMaster.schedule(timerSlave,amount);
// Remove the commands
frmMain.removeCommand(cmdalarm);
frmMain.removeCommand(cmdReset);
// Remove the DateField
frmMain.delete(dateIndex);
// Change the Form message
frmMain.setTitle("Sleeping...");
}
}
else if (c == cmdReset)
{
// Reset to the current date/time
dtfalarmTime.setDate(currentTime = new Date());
}
else if (c == cmdExit)
{
destroyApp(false);
notifyDestroyed();
}
}
// Handle the timer task
private class alarmTimer extends TimerTask
{
public final void run()
{
Alert alr = new Alert("Time to wake up!");
alr.setTimeout(Alert.FOREVER);
alr.setType(AlertType.ALARM);
AlertType.ERROR.playSound(display);
display.setCurrent(alr);
// Cancel this timer task
cancel();
}
}
}
13
De la ejecucin de esta aplicacin se obtiene una serie de pantallas como
estas:

14

3.1.3. EjempIo 3: Timer
Esta aplicacin consiste en un contador grfico. Mediante dos barras de
tareas que se desplazan (incremento/decremento) se visualiza un
transcurso temporal.

El cdigo fuente de esta aplicacin es el siguiente:

import java.lang.*;
import java.io.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* A simple class that shows an example of using a Timer and
* a TimerTask.
*
* This MIDlet creates two gauges. One gauge gaugeOne,
* sets elements from low to high. The other, gaugeTwo,
* set elements from high to low. In effect, this has
* gaugeOne "going up", and gaugeTwo "going down."
*
* The two timers fire at different intervals.
*
* There are two commands on our form:
*
* OK: toggles whether the times are active or not.
* EXIT: exits the MIDlet.
*/
public class TimerMIDlet extends MIDlet implements CommandListener {
// number of elements in gauge
final private static int GAUGE_MAX = 10;
private boolean timersRunning; // tracks state of timers
private Display myDisplay; // handle to the display
private Gauge gaugeOne; // "going up" gauge
private Gauge gaugeTwo; // "going down" gauge
private Form myScreen; // form on which to
// place gauges
15
private Command cmdOK; // OK command
private Command cmdExit; // EXIT command
private Timer timer;
private MyTimerTask timerTaskOne;
private MyTimerTask timerTaskTwo;
/**
* Internal class that provides a TimerTask.
*/
private class MyTimerTask extends TimerTask {
private Gauge myGauge; // reference to gauge
private boolean goUp; // if true, go up
private int num; // number of times called
/**
* Public constructor: stores "direction" and a reference to
* a gauge.
*/
public MyTimerTask(Gauge g, boolean up) {
myGauge = g;
goUp = up;
}
/**
* As the timer fires, this method is invoked. Set gauge
* based on goUp
*/
public void run() {
num++;
myGauge.setValue(goUp ?
GAUGE_MAX -(num % GAUGE_MAX) :
num % GAUGE_MAX);
}
}
/**
* Public constructor: gets handle to display,
* creates form, gauges, and commands.
*/
public TimerMIDlet() {
myDisplay = Display.getDisplay(this);
myScreen = new Form("TimerMIDlet");
gaugeOne = new Gauge("Up Gauge",
false,
GAUGE_MAX,
0);
myScreen.append(gaugeOne);
gaugeTwo = new Gauge("Down Gauge",
16
false,
GAUGE_MAX,
GAUGE_MAX);
myScreen.append(gaugeTwo);
cmdOK = new Command("OK", Command.OK, 1);
cmdExit = new Command("Exit", Command.EXIT, 1);
myScreen.addCommand(cmdOK);
myScreen.addCommand(cmdExit);
myScreen.setCommandListener(this);
}
/**
* Changes the state of timers to/from active to/from
* not-active.
*/
private void flipFlop() {
if (timersRunning) {
timerTaskOne.cancel();
timerTaskTwo.cancel();
timer.cancel();
timersRunning = false;
} else {
timer = new Timer();
timerTaskOne = new MyTimerTask(gaugeOne, false);
timerTaskTwo = new MyTimerTask(gaugeTwo, true);
timer.schedule(timerTaskOne, 0, 1000);
timer.schedule(timerTaskTwo, 0, 1500);
timersRunning = true;
}
}
/**
* Called by the system to start our MIDlet.
* @exception MIDletStateChangeException
*/
protected void startApp() throws MIDletStateChangeException {
myDisplay.setCurrent(myScreen);
flipFlop();
}
/**
* Called by the system to pause our MIDlet.
* No actions required by our MIDLet.
*/
protected void pauseApp() {}
/**
* Called by the system to end our MIDlet.
17
* No actions required by our MIDLet.
*/
protected void destroyApp(boolean unconditional) {}
/***
* Respond to command selections. Process two commands:
*
* OK: flip flop the timers to/from active
* EXIT: exit this MIDlet
*
*/
public void commandAction(Command c, Displayable d) {
if (c == cmdOK) {
flipFlop();
} else if (c == cmdExit) {
destroyApp(false);
notifyDestroyed();
}
}
}
De la ejecucin de esta aplicacin se obtiene una serie de pantallas como
estas:

También podría gustarte