Taller sobre programación de dispositivos móviles con Java impartido en el IX Congreso Internacional de Sistemas Computacionales del Tecnológico de Monterrey campus Guadalajara.
Red Dorsal Nacional de Fibra Óptica y Redes Regionales del Perú
200710 - Java para dispositivos móviles
1. /**
* Java
* para Dispositivos Móviles
*/
public class {
public static void main (String [] a) {
MCs. Javier González Sánchez;
javiergs@itesm.mx;
ITESM, campus Guadalajara;
}
}
3. agenda[ 1 Dispositivos móviles
]= ”);
• SMS (Short Service Message Service). Mensajes de máximo 160
caracteres
• WAP y WML. Web de baja fiabilidad, velocidad y alto costo.
• GPRS (General Packet Radio Service) transferencia de datos
multimedia con cualidades aceptables.
• MMS (Multimedia Message Service)
• J2ME (Java 2 micro-edition) entorno de desarrollo
Archivos JAR y JAD
• Symbian: sistema operativo: Nokia, sony-ericsson, Motorola
Archivos SIS
javiergs@itesm.mx
5. agenda[ 2 historia de Java
]=“ ”;
Diciembre 1990:
• Green Project, Oak, Duke …
http://today.java.net/jag/old/green/
Octubre 2004:
• Portafolio de productos basados en la red y con la
filosofía de que el mismo software debe ser ejecutable
en diferentes dispositivos y/o sistemas.
• J2SE = base de la tecnología Java
• J2EE = entorno empresarial, redes, acceso a datos
• J2ME = entornos limitados
javiergs@itesm.mx
7. agenda[ 2 J2ME.MIDlets
]= (“ Mobile Java ”);
Java 2 Micro Edition
• Omite el soporte a operaciones con punto flotante y los tipos
de datos que manejan esa información
• Limita el número de Exception disponibles para control de
Errores
• Para dispositivos con Configuración CLDC (Connected Limited
Device Configuration): PDAs y teléfonos móviles. Y el caso
particular de teléfonos móviles el perfil MIDP (Móvil
Information Device Profile)
• Maquina Virtual minimizada (K Virtual Machine)
javiergs@itesm.mx
8. agenda[ 2 J2ME.MIDlets
]= (“ Mobile Java ”);
MIDlet:
• programa capaz de ejecutarse en un dispositivo móvil.
Herramientas de trabajo:
• J2ME Wireless Toolkit 2.5
[http://java.sun.com/j2me/download.html ]
• J2SE SDK es necesario como base.
javiergs@itesm.mx
10. agenda[ 3 programación
]=“ ”;
• Variables, Tipos de dato, Operadores
• Clases, Objetos
• Atributos, Métodos
• Paquetes, APIs
• Herencia, Sobrecarga, Sobreescritura
• Estructuras de control
• Excepciones
• Estructuras de Datos: arreglos
javiergs@itesm.mx
11. agenda[ 3 modelar el mundo real ”;
]=“
Clase = molde Objeto = cosa
herencia se usar Son hijos de
se tienen
atributos se usan
metodos atributos
metodos tienen
javiergs@itesm.mx
12. agenda[ 3]=“ a trabajar … ”;
class Coche {
int velocidad;
void acelerar( int nuevaVelocidad) {
velocidad = nuevaVelocidad;
}
void frenar() {
velocidad = 0;
}
}
class Mundo {
public static void main (String [] arg) {
Coche miCoche = new Coche();
miCoche.acelerar(100);
miCoche.frenar();
}
}
javiergs@itesm.mx
13. agenda[ 3]=“ y se puede complicar … ”;
class Coche extends Bicicleta{
int velocidad;
void acelerar( int nuevaVelocidad) {
velocidad = nuevaVelocidad;
}
void frenar() {
velocidad = 0;
}
}
class Mundo {
public static void main (String [] arg) {
Coche miCoche = new Coche();
miCoche.acelerar(100);
miCoche.frenar();
}
}
javiergs@itesm.mx
17. agenda[ 4 J2ME.MIDlets
]= (“ Mobile Java ”);
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloWorld extends MIDlet implements CommandListener {
private Command exitCommand;
private Display display;
private Form screen;
public HelloWorld() {
// Obtenemos el objeto Display del midlet.
display = Display.getDisplay(this);
// Creamos el comando Salir.
exitCommand = new Command("Salir", Command.EXIT,2);
// Creamos la pantalla principal (un formulario)
screen = new Form("HelloWorld");
// Creamos y añadimos la cadena de texto a la pantalla
StringItem saludo = new StringItem("","Hola Mundo...");
screen.append(saludo);
// Añadimos el comando Salir e indicamos que clase lo manejará
screen.addCommand(exitCommand);
screen.setCommandListener(this);
}
javiergs@itesm.mx
18. agenda[ 4 J2ME.MIDlets
]= (“ Mobile Java ”);
public void startApp() throws MIDletStateChangeException {
// Seleccionamos la pantalla a mostrar
display.setCurrent(screen);
}
public void pauseApp() {
}
public void destroyApp(boolean incondicional) {
}
public void commandAction(Command c, Displayable s) {
// Salir
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
javiergs@itesm.mx
19. agenda[ 4 Opciones
]= ”);
Sony-ericsson SDK
Archivo.jar
Nokia Suite
Archivo.jad etc.
javiergs@itesm.mx
26. agenda[ 4 MIDlets
]= (“ Screen ”);
Las clases que heredan de Screen pueden aparecer en pantalla
Solo una a la vez
Heredan:
• String getTitle() // devuelve el título de la pantalla
• void setTitle(String s) // establece el título de la pantalla
• Ticker getTicker() // Devuelve el ticker de la pantalla
• void setTicker(Ticker ticker) // Establece el ticker de la pantalla
Podemos generar varios objetos e intercalarlos
display.setCurrent(objeto);
javiergs@itesm.mx
27. agenda[ 4 MIDlets
]= (“ Alert ”);
Permite mostrar una pantalla de texto hasta que se produzca un
comando de tipo OK. Se utiliza para mostrar mensajes de error y
Avisos
Alert (
String título, String texto_alerta,
Image imagen_alerta, //null para no utilizar imagen
AlertType tipo_alerta); //ALARM, CONFIRMATION, ERROR, INFO, WARNING
Ejemplo:
Alert alerta;
alerta = new Alert ("Error","El dato no es válido", null,AlertType.ERROR);
display.setCurrent(alerta);
alerta.setTimeout(Alert.FOREVER);
// tiempo en ms o establecer permante
javiergs@itesm.mx
28. agenda[ 4 MIDlets
]= (“ List ”);
Crear listas de elementos seleccionables
List (
String título,
int tipo_lista, // EXCLUSIVE, IMPLICIT, MULTIPLE
String[] elementos,
image[] imágenes)
Ejemplo:
String[] ciudades = {"Málaga", "Madrid", "Melilla"};
List lista = new List ("Seleccione ciudad", List.EXCLUSIVE, ciudades,
null);
..
Lista.getString ( lista.getSelectedIndex() );
javiergs@itesm.mx
29. agenda[ 4 MIDlets
]= (“ TextBox ”);
Permite introducir y editar texto a pantalla completa
TextBox (
String título,
String texto, // texto inicial a desplegar
int tamaño_max, // en caracteres
int limitación) // ANY, EMAILADDR, NUMERIC, PASSWORD, PHONENUMBER, URL
Ejemplo:
TextBox texto = new TextBox ("Mensaje", "", 256, TextField.ANY);
javiergs@itesm.mx
30. agenda[ 4 MIDlets
]= (“ Form ”);
Es un contenedor, aglutina una serie de elementos visuales
Ejemplo:
StringItem saludo = new StringItem("","Hola Mundo...");
Form screen.append(saludo);
javiergs@itesm.mx
39. agenda[ 4 juegos
]= ”);
(1)
Movimiento
Animación
Colisión
Una clase que represente al avión y
permita su manipulación
javiergs@itesm.mx
40. agenda[ 4 teclado
]= ”);
// Lectura del Teclado: keyPressed(), keyReleased() y keyRepeated().
public void keyPressed(int keyCode) {
int action = getGameAction(keyCode);
switch (action) {
case FIRE:
// Disparar
break;
case LEFT:
// Mover a la izquierda
break;
case RIGHT:
// Mover a la derecha
break;
case UP:
// Mover hacia arriba
break;
case DOWN:
// Mover hacia abajo
break;
}
}
javiergs@itesm.mx
41. agenda[ 4 hilos
]= ”);
public void run() {
iniciar();
while (true) {
// Actualizar fondo de pantalla
doScroll();
// Actualizar posición del jugador
computePlayer();
// Actualizar pantalla
repaint();
serviceRepaints();
try {
Thread.sleep(sleepTime); Y el teclado
} catch (InterruptedException e) { }
Con sus
Pseudo- listeners
}
}
javiergs@itesm.mx
43. agenda[ 4 MIDlets
]= (“ red ”);
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.GET);
c.setRequestProperty("IF-Modified-Since", "10 Nov 2000 17:29:12 GMT");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/
CLDC-1.0");
c.setRequestProperty("Content-Language", "es-ES");
is = c.openInputStream();
int ch, i, j;
// leer los datos desde la URL
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
// mostrar noticias en la pantalla
t = new TextBox("Noticias en barrapunto.com", salida.toString(), 1024,
0);
javiergs@itesm.mx
46. out.println(“ Referencias ”);
mucho
public interface J2 {
por http://java.sun.com;
http://www.java.com;
aprender http://java.net
&& }
seguir
trabajando public interface J2ME extends J2 {
http://java.sun.con/j2me/
}
public interface Otros extends J2 {
http://www.symbian.com/
http://developer.sonyericsson.com/
}
javiergs@itesm.mx
47. out.println(“ Para divertirse ”);
A jugar!
public interface Nintendo en tu celular {
http://www.ba-k.com/
index.php?/archives/
710-Vnes-1.20-JUEGA-NINTENDO-EN-TU-CELULAR.html;
}
public interface VNES for J2ME {
http://www.vampent.com/vnes.htm;
}
javiergs@itesm.mx