You are on page 1of 120

BlackBerry Java Application Multimedia

Versin: 5.0

Gua de desarrollo

Publicado: 2010-06-04 SWD-741609-0604105706-005

Contenido
1 Trabajo con archivos multimedia en una aplicacin de dispositivo BlackBerry................................................................ Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia.......................................................................... Crear una aplicacin de dispositivo BlackBerry que reproduzca archivos multimedia.................................................. Cdigo de ejemplo: reproduccin de archivos multimedia desde un URI...................................................................... Cdigo de ejemplo: reproducir una secuencia de tonos................................................................................................... Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia desde un flujo de entrada.................... Crear una aplicacin de dispositivo BlackBerry que reproduzca contenido multimedia............................................... Crear una aplicacin de dispositivo BlackBerry que reproduzca un vdeo en un campo de la interfaz de usuario .................................................................................................................................................................................................. Crear una aplicacin de dispositivo BlackBerry que tome una fotografa utilizando la cmara.................................. Crear una aplicacin de dispositivo BlackBerry que enve audio a un dispositivo con Bluetooth................................ Crear una aplicacin Gestor de contenido que reproduzca multimedia......................................................................... Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia....................................... Especificacin de las caractersticas de una aplicacin de dispositivo BlackBerry que reproduce multimedia.................. Consultar las caractersticas de reproduccin multimedia con las que es compatible una aplicacin de dispositivo BlackBerry............................................................................................................................................................................... Especificar los parmetros de reproduccin de vdeo dentro de una aplicacin de dispositivo BlackBerry............... Especificar el volumen que una aplicacin de dispositivo BlackBerry utiliza para reproducir archivos multimedia .................................................................................................................................................................................................. Respuesta a la entrada del usuario............................................................................................................................................... Recibir una notificacin cuando un usuario pulsa una tecla multimedia en un dispositivo BlackBerry...................... Responder cuando un usuario de dispositivo BlackBerry pulsa una tecla de volumen................................................. Responder cuando cambie el estado de un objeto Player................................................................................................. Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry............................................................. Archivo de reproduccin de vdeo RIMM............................................................................................................................ Formato de vdeo propio de RIM (archivo de reproduccin RIMM)................................................................................. Bfer y reproduccin de contenido multimedia................................................................................................................. Cdigo de ejemplo: reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry................... Cdigo de ejemplo: lectura de datos desde un bfer........................................................................................................ Cdigo de ejemplo: reproduccin de archivos multimedia desde un archivo en el dispositivo BlackBerry................ Cdigo de ejemplo: anlisis de un archivo de reproduccin de vdeo RIMM................................................................. Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry.................................................... Grabar audio en una aplicacin de dispositivo BlackBerry............................................................................................... 5 5 6 6 7 8 9 9 10 11 12 14 19 19 19 20 20 20 21 21 22 22 23 25 27 28 30 31 35 35

Cdigo de ejemplo: registro de audio desde un objeto Player......................................................................................... Grabar vdeo con la aplicacin de grabacin de vdeo de BlackBerry............................................................................. Utilizar la API multimedia para grabar vdeo...................................................................................................................... Cdigo de ejemplo: uso de la API multimedia para grabar vdeo.................................................................................... Reproducir archivos multimedia en la aplicacin multimedia del dispositivo BlackBerry..................................................... Iniciar la aplicacin multimedia con o sin contenido......................................................................................................... Reproducir audio en BlackBerry Browser............................................................................................................................ Reproducir un vdeo en BlackBerry Browser....................................................................................................................... 2 Trabajo con imgenes de la aplicacin Cmara..................................................................................................................... Iniciar la cmara desde una aplicacin del dispositivo BlackBerry........................................................................................... Crear una aplicacin Gestor de contenido que reproduzca multimedia.................................................................................. Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia................................................ Recibir una notificacin de los eventos del sistema de archivos.............................................................................................. Detectar cundo se agrega o elimina una imagen en el sistema de archivos del dispositivo BlackBerry........................... Recuperar una imagen................................................................................................................................................................... Mover una imagen dentro del mismo directorio del sistema de archivos................................................................................ Mover una imagen a un directorio diferente del sistema de archivos...................................................................................... Eliminar una imagen del sistema de archivos............................................................................................................................. 3 Dibujar y posicionar imgenes.................................................................................................................................................. Posicionar una imagen................................................................................................................................................................... Comprobar que el dispositivo BlackBerry es compatible con una pantalla en color.............................................................. Recuperar el nmero de colores con los que es compatible la pantalla del dispositivo BlackBerry..................................... Configurar la transparencia del pxel en el rea de trabajo...................................................................................................... Consultar las operaciones de malla con las que es compatible la aplicacin de dispositivo BlackBerry............................. Dibujar una ruta sombreada y con relleno................................................................................................................................... Cdigo de ejemplo: dibujo de una ruta que pase del azul al rojo en la pantalla de un dispositivo BlackBerry.................. Activar o desactivar un estilo de dibujo....................................................................................................................................... Determinar si se ha configurado un estilo de dibujo.................................................................................................................. Cdigo de ejemplo: determinacin de si el estilo de dibujo especificado est activado....................................................... Utilizar una imagen de mapa de bits monocromticos como marca....................................................................................... Cdigo de ejemplo: demostracin del uso de una imagen de mapa de bits monocromticos como marca....................... Crear una imagen de mapa de bits utilizando otra imagen de mapa de bits.......................................................................... Crear una imagen de mapa de bits que contenga contenido con tamao modificado de otra imagen de mapa de bits ...........................................................................................................................................................................................................

37 38 38 40 51 51 52 52 53 53 53 55 60 60 61 62 62 63 65 65 66 66 67 67 67 68 68 68 69 69 70 70 71

Duplicar una imagen de mapa de bits......................................................................................................................................... Crear una imagen de mapa de bits que contenga parte del contenido de otra imagen de mapa de bits........................... Dibujar una imagen en una imagen de mapa de bits vaca...................................................................................................... Filtros de interpolacin................................................................................................................................................................... 4 Visualizacin de imgenes......................................................................................................................................................... Visualizacin de una imagen acercndola, alejndola y desplazndola.................................................................................. Mostrar una imagen acercndola, alejndola y desplazndola................................................................................................ Cdigo de ejemplo: visualizacin de una imagen acercndola, alejndola y desplazndola................................................ Visualizacin de una fila de imgenes para realizar desplazamientos..................................................................................... Mostrar una fila de imgenes para realizar desplazamientos................................................................................................... Cdigo de ejemplo: visualizacin de una fila de imgenes para realizar desplazamientos.................................................. 5 Uso de imgenes sin procesar................................................................................................................................................... Recuperar los datos de la imagen sin procesar........................................................................................................................... Almacenar datos sin procesar de la imagen................................................................................................................................ Comparar dos imgenes sin procesar.......................................................................................................................................... Comparar dos imgenes de mapa de bits para comprobar si son diferentes.......................................................................... 6 Uso de imgenes cifradas.......................................................................................................................................................... Acceder a una imagen cifrada a travs de un flujo de entrada................................................................................................. Cifrar una imagen........................................................................................................................................................................... Mostrar una imagen cifrada.......................................................................................................................................................... Especificar el modo de descodificacin de una imagen............................................................................................................. Especificar el tamao de la pantalla de una imagen cifrada..................................................................................................... 7 Uso de contenido SVG en una aplicacin del dispositivo BlackBerry................................................................................. Descargar contenido SVG.............................................................................................................................................................. Reproducir contenido multimedia enriquecido........................................................................................................................... Escuchar eventos al descargar un archivo .pme......................................................................................................................... Responder a eventos al descargar un archivo .pme................................................................................................................... Cdigo de ejemplo: respuesta a eventos cuando una aplicacin de dispositivo BlackBerry descarga contenido SVG ........................................................................................................................................................................................................... Descargar y reproducir un archivo .pme...................................................................................................................................... Reproducir contenido SVG............................................................................................................................................................ Acceder a contenido SVG a travs de una conexin con la que no es compatible MediaManager.....................................

71 71 72 72 73 73 73 74 74 74 76 78 78 78 78 79 80 80 80 81 81 81 82 82 82 83 84 85 87 88 89

Cdigo de ejemplo: implementacin de un marco de conector personalizado......................................................................

90

8 Creacin de grficos 2D y 3D con JSR-239............................................................................................................................. 92 Paquetes para la compatibilidad con JSR-239............................................................................................................................ 92 Cdigo de ejemplo: representacin de un tringulo 2D en varios colores.............................................................................. 93 Cdigo de ejemplo: dibujo de un cubo en 3D..................................................................................................................... 98 Cdigo de ejemplo: dibujo de un cubo en 3D............................................................................................................................. 104 Utilidades de matemticas 3D...................................................................................................................................................... 110 Cdigo de ejemplo: uso de aritmtica de punto fijo.......................................................................................................... 110 9 Glosario......................................................................................................................................................................................... 10 Comentarios................................................................................................................................................................................. 11 Historial de revisin del documento......................................................................................................................................... 12 Aviso legal..................................................................................................................................................................................... 112 114 115 116

Gua de desarrollo

Trabajo con archivos multimedia en una aplicacin de dispositivo BlackBerry

Trabajo con archivos multimedia en una aplicacin de dispositivo BlackBerry

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia


Puede crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia en BlackBerry Browser o en la aplicacin Multimedia en un dispositivo BlackBerry. La aplicacin multimedia del dispositivo BlackBerry tambin puede crearse para reproducir audio, vdeo y contenido SVG binario. Asimismo, la aplicacin del dispositivo BlackBerry tambin puede crearse para grabar audio y el vdeo y enviar el audio a unos auriculares con Bluetooth. La API del Gestor de contenido tambin se utiliza para proporcionar un modelo de ejecucin para invocar de forma remota las aplicaciones secundarias del dispositivo BlackBerry. CHAPI es un mecanismo ideal para configurar parmetros de invocacin para aplicaciones secundarias del dispositivo BlackBerry. Con CHAPI es posible invocar aplicaciones proporcionando tanto una URL, como tipo de contenido, o el ID de contenido cuando se utiliza uno de los constructores disponibles en la clase javax.microedition.content.Invocation. Nota: CHAPI intentar recuperar una respuesta de invocacin a menos que especifique explcitamente que ninguna respuesta es necesaria. Puede crear una aplicacin de dispositivo BlackBerry para reproducir multimedia que utilice la interfaz Player y javax.microedition.media package. La interfaz Player ha sido implementada por RIM. Proporciona los mtodos necesarios para administrar los distintos estados de una aplicacin de dispositivo BlackBerry que reproduce multimedia y controla la reproduccin de archivos multimedia. Un objeto Player se construye en primer lugar en un estado UNREALIZED. Mientras se encuentra en este estado el objeto es incapaz de hacer cualquier cosa por falta de informacin y recursos. Al invocar realize() desplazar el objeto Player al estado REALIZED. Esto activa al objeto Player para ubicar informacin y obtener as los recursos bsicos para reproducir un archivo multimedia. Al invocar prefetch() desplazar el objeto Player al estado PREFETCHED. En este estado el objeto Player obtiene los recursos necesarios y, a continuacin, "captura" algunos de los archivos multimedia para iniciar inmediatamente la reproduccin tan pronto como Player se haya iniciado. Al invocar start(), Player se desplazar a un estado de inicio STARTED en el que iniciar inmediatamente la reproduccin multimedia. Es posible invocar start() sin invocar realize() y prefetch(). El mtodo start() invocar prefetch(0), que a su vez invocar realize() antes de poder iniciar la reproduccin multimedia. La sencillez de uso de start() segn este patrn podra compensarse a travs del incremento de demoras en el inicio de la reproduccin multimedia. Para obtener ms informacin acerca de los tipos de archivos multimedia con los que es compatible un dispositivo BlackBerry, lea el artculo KB05482 de la base de conocimientos www.blackberry.com/btsc

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

Crear una aplicacin de dispositivo BlackBerry que reproduzca archivos multimedia


1. Importe las clases necesarias.
import javax.microedition.media.Manager; import javax.microedition.media.Player; import java.io.IOException;

2. 3. 4. 5.

Recupere un objeto Player de la clase Manager invocando el mtodo createPlayer(). Invoque Player.realize() con el fin de preparar la aplicacin de dispositivo BlackBerry para obtener los recursos necesarios. Invoque Player.prefetch() para permitir a la aplicacin de dispositivo BlackBerry llevar a cabo acciones que deben tener lugar antes de que el dispositivo BlackBerry pueda reproducir multimedia. Invoque Player.start() para iniciar la reproduccin multimedia.
Player p = Manager.createPlayer("http://www.test.rim.net/abc.wav"); /* * Best practice is to invoke realize(), then prefetch(), then start(). * Following this sequence reduces delays in starting media playback. * * Invoking start() as shown below will cause start() to invoke prefetch(0), * which invokes realize() before media playback is started. */ p.start();

6. 7.

Invoque Player.stop() para detener la reproduccin multimedia. Invoque Player.close() para colocar el objeto Player en un estado CLOSED.

Cdigo de ejemplo: reproduccin de archivos multimedia desde un URI


private void initVideo(String url) { try { _player = javax.microedition.media.Manager.createPlayer(url); _player.realize(); _vc = (VideoControl) _player.getControl("VideoControl"); if (_vc != null) { _videoField = (Field) _vc.initDisplayMode( VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field"); _vc.setVisible(true); } } catch(MediaException pe) { System.out.println(pe.toString()); } catch (IOException ioe) {

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

System.out.println(ioe.toString());

Cdigo de ejemplo: reproducir una secuencia de tonos


ToneControl se utiliza para reproducir una secuencia de notas definida por el usuario con una duracin y ritmo especficos

en un dispositivo BlackBerry.
// "Mary Had A Little Lamb" has "ABAC" structure // Use block to repeat "A" section // Tempos ranging from 20 to 508 beats per minute are divided by 4 // to create a tempo modifier range of 5 to 127. byte tempo_mod = 30; // 120 bpm // Note duration ranges from 128 (1/2 note) to 0 (128th of a note) // with a default resolution of 64. byte duration = 8; // Note length 8 (quaver) = 1/8th of a note duration // Notes are determined from ToneControl.C4 (Middle C), // which has a value of 60 and a frequency of 261.6 Hz. byte C4 = ToneControl.C4; // C note value = 60 (middle C) byte D4 = (byte)(C4 + 2); // D note value = 62 (a whole step) byte E4 = (byte)(C4 + 4); // E note value = 64 (a major third) byte G4 = (byte)(C4 + 7); // G note value = 67 (a fifth) byte rest = ToneControl.SILENCE; // rest byte[] mySequence = { ToneControl.VERSION, 1, // version 1 ToneControl.TEMPO, tempo_mod, // // Start define "A" section ToneControl.BLOCK_START, 0, // // Content of "A" section E4, duration, D4, duration, C4, duration, E4, duration, E4, duration, E4, duration, E4, duration, rest, duration, // // End define "A" section ToneControl.BLOCK_END, 0, // end of block number 0 // // Play "A" section ToneControl.PLAY_BLOCK, 0, // // Play "B" section D4, duration, D4, duration, D4, duration, rest, duration, E4, duration, G4, duration, G4, duration, rest, duration, // // Repeat "A" section ToneControl.PLAY_BLOCK, 0, // // Play "C" section D4, duration, D4, duration, E4, duration, D4, duration, C4, duration

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

}; try{

Player p = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR); p.realize(); ToneControl c = (ToneControl)p.getControl("ToneControl"); c.setSequence(mySequence); p.start(); } catch (IOException ioe) { } } catch (MediaException me) { }

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia desde un flujo de entrada
1. Importe las clases necesarias.
import import import import import import import java.lang.Class; javax.microedition.media.Player; javax.microedition.media.Manager; javax.microedition.rms.RecordStore; java.io.InputStream; java.io.ByteArrayInputStream; net.rim.device.api.media.protocol.ByteArrayInputStreamDataSource;

2.

Cree un objeto ByteArrayInputStream. En este ejemplo, se invoca getResourceAsStream(String) para recuperar el archivo multimedia del archivo de recursos en una ubicacin absoluta.
ByteArrayInputStream stream = (ByteArrayInputStream)this.getClass ().getResourceAsStream("/abc.mp3");

3.

Cree un SourceStream con capacidad de bsqueda creando previamente un ByteArrayInputStreamDataSource y pasando el objeto ByteArrayInputStream.
ByteArrayInputStreamDataSource source = new ByteArrayInputStreamDataSource (stream, "audio/mpeg");

4.

Recupere un objeto Player invocando Manager.createPlayer() y, a continuacin start() para iniciar la reproduccin multimedia.
Player p = Manager.createPlayer(source); p.start();

5.

Tambin puede utilizar un mtodo que no tenga capacidad de bsqueda para reproducir multimedia desde un InputStream tal como se muestra en el siguiente cdigo de ejemplo.
InputStream stream = (InputStream)this.getClass().getResourceAsStream("/abc.mp3"); Player p = Manager.createPlayer(stream, "audio/mpeg"); p.start();

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

Crear una aplicacin de dispositivo BlackBerry que reproduzca contenido multimedia


Los dispositivos BlackBerry con BlackBerry Device Software versin 4.3.0 o posterior compatibles con EVDO sern compatibles con la funcionalidad RTSP 1. Importe las clases necesarias.
import javax.microedition.media.Manager; import javax.microedition.media.Player;

2.

Invoque Manager.createPlayer(String) para reproducir contenido multimedia pasando un parmetro que represente un localizador RTSP.
Player p = Manager.createPlayer("rtsp://streaming.rim com/streaming_video.3gp");

Crear una aplicacin de dispositivo BlackBerry que reproduzca un vdeo en un campo de la interfaz de usuario
1. Importe las clases y las interfaces necesarias.
import import import import net.rim.device.api.ui.Field; javax.microedition.media.Manager; javax.microedition.media.Player; javax.microedition.media.control.VideoControl;

2.

Cree la variables Player, VideoControl y Field.


Player videoPlayer; VideoControl videoControl; Field videoField;

3.

Invoque Manager.createPlayer(String) pasando un parmetro considerado como URI que describa el contenido del vdeo. Almacene una referencia al objeto Player que devuelva la llamada a createPlayer(String).
videoPlayer = Manager createPlayer("file:///SDCard/BlackBerry/videos/soccer1.avi");

4.

Invoque Player.realize() con el fin de permitir a Player obtener la informacin necesaria para obtener recursos multimedia.
videoPlayer.realize();

5.

Invoque Player.getControl() pasando un parmetro que represente la variable Control que desea recuperar. Asigne el objeto devuelto como un objeto VideoControl.
videoControl = (VideoControl)_videoPlayer.getControl ( "javax.microedition.media.control.VideoControl");

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

6.

Invoque VideoControl.initDisplayMode(int mode, Object arg) pasando un parmetro arg y especificando la primitiva de interfaz de usuario que muestra el vdeo para inicializar el modo en el que el objeto videoField muestra el vdeo. Asigne el objeto devuelto como un objeto Field.
videoField = (Field)_videoControl.initDisplayMode ( VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field" );

Tenga en cuenta que initDisplayMode() se puede invocar de diversas maneras para devolver un objeto Field, como se ha mostrado anteriormente, devolver un objeto Item para su uso con MIDlets o bien para mostrar un vdeo en un
Canvas.

Crear una aplicacin de dispositivo BlackBerry que tome una fotografa utilizando la cmara
1. Importe las clases y las interfaces necesarias.
import import import import net.rim.device.api.ui.Field; javax.microedition.media.Manager; javax.microedition.media.Player; javax.microedition.media.control.VideoControl;

2.

Invoque Manager.createPlayer(String) pasando un parmetro considerado como URI que describe el contenido de la imagen.
Player cameraPlayer = Manager.createPlayer( "capture://video?encoding=jpeg" );

3.

Invoque Player.realize() con el fin de permitir a Player obtener la informacin necesaria para obtener recursos multimedia.
cameraPlayer.realize();

4.

Invoque Player.getControl() pasando un parmetro que representa la clase VideoControl. Asigne el objeto devuelto como un objeto VideoControl.
VideoControl videoControl = (VideoControl)cameraPlayer.getControl( "javax.microedition.media.control.VideoControl");

5. 6.

Invoque VideoControl.initDisplayMode(int mode, Object arg) para inicializar el modo que utiliza videoField para mostrar el vdeo. Invoque VideoControl.getSnapshot() para rellenar una matriz de bytes con los datos JPEG para la fotografa tomada con la cmara.
int[] imageByte = videoControl.getSnapshot(null);

El pasar null a getSnapshot () tiene como resultado la captura de una fotografa que utiliza la configuracin predeterminada de la cmara. Puede ajustar el parmetro para getSnapshot() invocando System.getProperty() para determinar qu configuracin est disponible para su uso.

10

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

String encodingString = System.getProperty("video.snapshot.encodings");

Invoque stringToKeywords() para dividir las propiedades en elementos de matriz de String separados.
String[] properties = StringUtilities.stringToKeywords(encodingString);

Hay cuatro propiedades devueltas por System.getProperty() a las que se puede acceder individualmente en la matriz de String devuelta desde stringToKeywords(). Las propiedades son "encoding", "width", "height" y "quality".

Crear una aplicacin de dispositivo BlackBerry que enve audio a un dispositivo con Bluetooth
1. Importe las clases necesarias.
import import import import javax.microedition.media.Control; javax.microedition.media.Manager; javax.microedition.media.Player; net.rim.device.api.media.control.AudioPathControl;

2.

Invoque Manager.createPlayer(String) pasando la ubicacin de un archivo de audio.


Player p = javax.microedition.media.Manager createPlayer("http://mycompany/test.mp3");

3. 4. 5.

Invoque Player.realize() para permitir al objeto Player obtener recursos multimedia.


p.realize();

Invoque Player.prefetch().
p.prefetch();

Invoque Player.getControls() para obtener el AudioPathControl compatible.


AudioPathControl apc = (AudioPathControl)p.getControl( "net.rim.device.api.media.control.AudioPathControl" );

6.

Lleve a cabo una de las siguientes tareas: Tarea Pasos

Enve el audio a un dispositivo con Invoque AudioPathControl.setAudioPath(int) utilizando como Bluetooth que sea compatible con las parmetro el atributo AudioPathControl.AUDIO_PATH_BLUETOOTH llamadas de voz. para enviar audio al dispositivo Bluetooth.
apc.setAudioPath (AudioPathControl.AUDIO_PATH_BLUETOOTH);

11

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

Tarea

Pasos

Enve el audio a un dispositivo Invoque AudioPathControl.setAudioPath(int) utilizando como Bluetooth que sea compatible con un parmetro el atributo AudioPathControl.AUDIO_ BLUETOOTH_A2DP dispositivo con Bluetooth, por ejemplo, para enviar audio al dispositivo Bluetooth. unos auriculares estreo Bluetooth.
apc.setAudioPath(AudioPathControl.AUDIO_ BLUETOOTH_A2DP);

Crear una aplicacin Gestor de contenido que reproduzca multimedia


Este artculo describe el desarrollo de una aplicacin Gestor de contenido que utiliza JSR 211 para permitir a las aplicaciones invocar otras aplicaciones, incluidas las aplicaciones nativas del dispositivo BlackBerry, para gestionar tipos de contenido especficos. Al registrar el gestor de contenido para gestionar tipos de contenido de vdeo o imgenes con la accin SEND, por ejemplo, aparecer un elemento de men siempre que vea un vdeo o imagen en la pantalla de vista previa de la cmara, en el explorador de archivos, etc. Al hacer clic en este men, el elemento de men invocar el gestor de contenido con una accin SEND y un vnculo al vdeo o imagen. 1. Importe las clases necesarias.
import import import import import javax.microedition.content.ContentHandlerServer; javax.microedition.content.RequestListener; javax.microedition.content.Registry; javax.microedition.content.Invocation; javax.microedition.content.ActionNameMap;

2.

Cree una clase que extienda UiApplication e implemente RequestListener.


public final class SendMediaDemo extends UiApplication implements RequestListener {

3.

Gestione el inicio de la aplicacin.


public static void main(String[] args) throws Exception { if(args != null && args.length > 0) { if (args[0].equals("startup")) { // Register ourselves as a content handler on startup register(); } } else { // Create a new instance of the application and make the currently // running thread the application's event dispatching thread. SendMediaDemo app = new SendMediaDemo(); app.enterEventDispatcher(); } }

4.

Registre la aplicacin como un RequestListener.

12

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

public SendMediaDemo() throws ContentHandlerException { // Get access to the ContentHandlerServer for this application and // register as a listener. ContentHandlerServer contentHandlerServer = Registry.getServer(CLASSNAME); contentHandlerServer.setListener(this); }

5.

Cree un mtodo para gestionar el registro del gestor de contenido. Este mtodo utilizar Registry.register() para garantizar que esta aplicacin pueda ser iniciada con opciones de men externas para enviar vdeo e imgenes a esta aplicacin.
private static void register() throws ContentHandlerException { String[] types = {"image/bmp", "image/png", "image/jpeg", "video/3gpp", "video/mp4"}; String[] suffixes = {".bmp", ".png", ".jpg", ".3GP", ".mp4"}; String[] actions = {ContentHandler.ACTION_SEND}; String[] actionNames = {"Send to demo app"}; ActionNameMap[] actionNameMaps = {new ActionNameMap(actions,actionNames,"en")}; // Get access to the registry Registry registry = Registry.getRegistry(CLASSNAME); // Register as a content handler registry.register(CLASSNAME, types, suffixes, actions, actionNameMaps, ID, null); }

6.

Implemente RequestListener.invocationRequestNotify(). Este gestor se invocar cuando otra aplicacin pasa el contenido a esta aplicacin.
public void invocationRequestNotify(ContentHandlerServer server) { Invocation invoc = server.getRequest(false); if(invoc != null) { String type = invoc.getType(); if(type.equals("image/bmp") || type.equals("image/png") || type.equals("image/jpeg")) { byte[] data = getData(invoc.getURL()); displayImage(data); } else if(type.equals("video/3gpp") || type.equals("video/mp4")) { initVideo(invoc.getURL()); if(_videoField != null) { displayVideo(); } } else { System.exit(0); } server.finish(invoc, Invocation.OK); }

13

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia
package com.rim.samples.device.sendmediademo; import java.io.*; import javax.microedition.content.*; import javax.microedition.io.*; import javax.microedition.media.*; import javax.microedition.media.control.*; import javax.microedition.io.file.*; import net.rim.device.api.system.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; public final class SendMediaDemo extends UiApplication implements RequestListener { private static final String ID = "com.rim.samples.device.sendmediademo"; private static final String CLASSNAME = "com.rim.samples.device.sendmediademo.SendMediaDemo"; private Player _player; private Field _videoField; private VideoControl _vc; /** * Entry point for application * @param args Command line arguments */ public static void main(String[] args) { if(args != null && args.length > 0) { if (args[0].equals("startup")) { // Register ourselves as a content handler on startup register(); } } else { // Create a new instance of the application and make the currently // running thread the application's event dispatching thread. SendMediaDemo app = new SendMediaDemo(); app.enterEventDispatcher(); } } /** * Registers this application as a content handler for image files */ private static void register() { String[] types = {"image/bmp", "image/png", "image/jpeg", "video/3gpp", "video/mp4"};

14

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

String[] suffixes = {".bmp", ".png", ".jpg", ".3GP", ".mp4"}; String[] actions = {ContentHandler.ACTION_SEND}; String[] actionNames = {"Send to demo app"}; ActionNameMap[] actionNameMaps = {new ActionNameMap(actions,actionNames,"en")}; // Get access to the registry Registry registry = Registry.getRegistry(CLASSNAME); try { // Register as a content handler registry.register(CLASSNAME, types, suffixes, actions, actionNameMaps, ID, null); } catch (ContentHandlerException che) { System.out.print(che.toString()); } catch (ClassNotFoundException cnfe) { System.out.print(cnfe.toString()); } } // Constructor public SendMediaDemo() { try { // Get access to the ContentHandlerServer for this application and // register as a listener. ContentHandlerServer contentHandlerServer = Registry.getServer(CLASSNAME); contentHandlerServer.setListener(this); } catch(ContentHandlerException che) { System.out.println(che.toString()); } } /** * RequestListener implementation * @param server The content handler server from which to request Invocation objects */ public void invocationRequestNotify(ContentHandlerServer server) { Invocation invoc = server.getRequest(false); if(invoc != null) { String type = invoc.getType(); if(type.equals("image/bmp") || type.equals("image/png") || type.equals("image/jpeg")) {

15

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

} } /** * Sets the size of the video * @param width Width of the video display * @param height Height of the video display */ private void setVideoSize(int width, int height) { try { if (_vc != null) { _vc.setDisplaySize(width, height); } } catch(MediaException pe) { System.out.println(pe.toString()); } } /** * Creates and initializes a video player * @param url The URL of the video file to play */ private void initVideo(String url) { try { _player = javax.microedition.media.Manager.createPlayer(url); _player.realize(); _vc = (VideoControl) _player.getControl("VideoControl"); if (_vc != null) { _videoField = (Field) _vc.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");

} else if(type.equals("video/3gpp") || type.equals("video/mp4")) { initVideo(invoc.getURL()); if(_videoField != null) { displayVideo(); } } else { System.exit(0); } server.finish(invoc, Invocation.OK);

byte[] data = getData(invoc.getURL()); displayImage(data);

16

Gua de desarrollo

Crear una aplicacin de dispositivo BlackBerry que reproduzca multimedia

} /** * Returns a byte array containing data representing the image at the specified URL * @param url The location of the image to display * @return The image data */ private byte[] getData(String url) { byte[] data = new byte[0]; try { FileConnection file = (FileConnection)Connector.open(url); int fileSize = (int)file.fileSize(); data = new byte[fileSize]; InputStream inputStream = file.openInputStream(); inputStream.read(data); } catch(Exception e) { System.out.println(e.toString()); } return data; } /** * Creates a screen and displays the image * @param data The data representing the image to be rendered */ private void displayImage(byte [] data) { // Create image field Bitmap image = Bitmap.createBitmapFromBytes( data, 0, -1, 5); BitmapField imageField = new BitmapField( image, Field.FIELD_HCENTER); // Create and display screen MainScreen screen = new MainScreen(net.rim.device.api.ui.Manager.NO_VERTICAL_SCROLL); screen.setTitle("Send Media Demo"); screen.add(imageField); pushScreen(screen); }

} catch(MediaException pe) { System.out.println(pe.toString()); } catch (IOException ioe) { System.out.println(ioe.toString()); }

_vc.setVisible(true);

17

Gua de desarrollo

/** * Creates a video screen and starts the video player */ private void displayVideo() { // Create and display screen VideoMainScreen screen = new VideoMainScreen(); screen.setTitle("Send Media Demo"); screen.add(_videoField); pushScreen(screen); try { // Start media player _player.start(); } catch(MediaException pe) { System.out.println(pe.toString()); } } /** * A main screen in which to play video files */ final private class VideoMainScreen extends MainScreen { // Constructor VideoMainScreen() { super(net.rim.device.api.ui.Manager.NO_VERTICAL_SCROLL); } /** * @see net.rim.device.api.ui.Manager#sublayout(int,int) */ protected void sublayout(int width, int height) { setVideoSize(Display.getWidth(), Display.getHeight()); super.sublayout(width, height); } /** * @see net.rim.device.api.ui.Screen#onClose() */ public boolean onClose() { _player.close(); return super.onClose(); } }

18

Gua de desarrollo

Especificacin de las caractersticas de una aplicacin de dispositivo BlackBerry que reproduce multimedia

Especificacin de las caractersticas de una aplicacin de dispositivo BlackBerry que reproduce multimedia
Consultar las caractersticas de reproduccin multimedia con las que es compatible una aplicacin de dispositivo BlackBerry
La aplicacin del dispositivo BlackBerry puede consultar una variedad de caractersticas de reproduccin que incluyen el modo de visualizacin de vdeo, la ubicacin del vdeo con respecto al fondo de visualizacin, las coordenadas x e y del vdeo con respecto al objeto UI de visualizacin de vdeo y los niveles de audio.

Especificar los parmetros de reproduccin de vdeo dentro de una aplicacin de dispositivo BlackBerry
1. Importe las clases necesarias.
import javax.microedition.media.Manager; import javax.microedition.media.Player; import javax.microedition.media.control.VideoControl;

2.

Inicialice y prepare una instancia de un objeto Player.


Player player = Manager.createPlayer("file:///SDCard/BlackBerry/videos/myvid.mp4"); player.realize();

3.

Obtenga el control de vdeo.


VideoControl videoControl = (VideoControl) player.getControl("VideoControl"); videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);

4.

Para incrustar el control de vdeo en el fondo especifique las propiedades del control de vdeo.
videoControl.setDisplayLocation(20, 30); videoControl.setDisplaySize(160, 90); videoControl.setVisible(true);

5.

La interfaz VideoControl se implementa para proporcionar a la aplicacin de dispositivo BlackBerry una variedad de caractersticas compatibles con la reproduccin de vdeo. Lleve a cabo una de las siguientes acciones: Controle el modo de visualizacin de vdeo mediante el uso de USE_GUI_PRIMITIVE o USE_DIRECT_VIDEO. Controle la ubicacin del vdeo con respecto al fondo que muestra el vdeo. Acceda a las coordenadas x e y del vdeo con respecto al objeto UI que muestra el vdeo o lo oculta.

19

Gua de desarrollo

Respuesta a la entrada del usuario

Especificar el volumen que una aplicacin de dispositivo BlackBerry utiliza para reproducir archivos multimedia
1. Importe las clases necesarias.
import net.rim.device.api.ui.Screen; import javax.microedition.lcdui.Canvas; import javax.microedition.media.control.VolumeControl;

2.

Especifique el volumen de la aplicacin multimedia.


VolumeControl volume = (VolumeControl) player.getControl("VolumeControl"); volume.setLevel(80);

3.

Lleve a cabo una de las siguientes tareas: Tarea Capturar eventos de teclas de volumen en una aplicacin MIDP. Capturar eventos de teclas de volumen en una aplicacin de dispositivo BlackBerry. Implementar KeyListener para capturar y gestionar eventos de teclas en una aplicacin de dispositivo BlackBerry. Pasos a. b. a. b. Cree una clase que extienda la clase Canvas. Omita el mtodo Canvas.keyPressed(). Cree una clase que extienda la clase Screen. Omita Screen.keyControl(). Cree una clase que implemente KeyListener, as como keyChar(), keyStatus(), keyDown(), keyRepeat() y keyUp(). Utilice keyDown () para procesar las pulsaciones de la teclas de volumen en los dispositivos BlackBerry con teclas multimedia.

Respuesta a la entrada del usuario


Recibir una notificacin cuando un usuario pulsa una tecla multimedia en un dispositivo BlackBerry
Una aplicacin del dispositivo BlackBerry puede suscribirse a los eventos de teclas gracias a la interfaz KeyListener. KeyListener recibe todos los eventos de claves mientras la aplicacin se encuentra en primer trmino y recibe teclas globales no gestionadas mientras la aplicacin se encuentra en segundo plano.

20

Gua de desarrollo

Respuesta a la entrada del usuario

Las teclas multimedia incluyen subir volumen, bajar volumen, adelante, atrs y una tecla combinada que se encarga de silenciar, la reproduccin y la pausa. Algunos dispositivos BlackBerry tienen teclas multimedia dedicadas adicionales, por ejemplo, Keypad.KEY_FORWARD y Keypad.KEY_BACKWARD. La presencia de estas teclas multimedia se puede detectar mediante Keypad.hasMediaKeys(). Algunos dispositivos BlackBerry tambin tienen una tecla "Silencio" mientras que otros tienen una tecla "Altavoz". Ambas de estas teclas se asignan la misma constante de tecla, Keypad.KEY_SPEAKERPHONE. Para determinar si al pulsar la tecla de KEY_SPEAKERPHONE se activar la tecla "Silencio" o la tecla "Altavoz" deber utilizar Keypad.hasMuteKey(). 1. Importe las clases e interfaces necesarias.
import net.rim.device.api.ui.Keypad; import net.rim.device.api.ui.container.MainScreen;

2.

Cree una clase que extienda MainScreen, implemente KeyListener y registre el oyente con addKeyListener().
class KeyListenerDemo extends MainScreen implements KeyListener { public KeyListenerDemo() { addKeyListener(this); } }

Responder cuando un usuario de dispositivo BlackBerry pulsa una tecla de volumen


1. Importe las clases necesarias.
import net.rim.device.api.ui.Screen; import net.rim.device.api.system.Characters;

2. 3. 4.

Cree una clase que extienda la clase Screen. Omita Screen.keyControl().


protected boolean keyControl(char c, int status, int time) {

Identifique la tecla de volumen que ha cambiado el usuario del dispositivo BlackBerry.


if (c == Characters.CONTROL_VOLUME_UP) { } else if (c == Characters.CONTROL_VOLUME_DOWN) { }

Nota: En la clase net.rim.device.api.media.MediaKeyListener, los mtodos keyDown(), keyRepeat() y keyUp() se invocan con Keypad.KEY_VOLUME_UP y Keypad.KEY_VOLUME_DOWN, que demuestran un control granular ms fino en comparacin con el uso de keyChar().

Responder cuando cambie el estado de un objeto Player


1. Importe las clases necesarias.

21

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

import import import import

javax.microedition.media.Player; javax.microedition.media.PlayerListener; javax.microedition.media.MediaException; java.io.IOException;

2.

Invoque addPlayerListener() para escuchar los cambios en el estado del objeto Player.
private void doPlay() throws IOException, MediaException { Player p = Manager.createPlayer("file:///SDCard/BlackBerry/music/theo.mp3"); p.addPlayerListener(this); p.realize(); p.prefetch(); p.start(); }

3.

Omita playerUpdate() para enviar un evento multimedia al PlayerListener registrado.


public void playerUpdate(Player player, final String event, Object eventData) { if (event.equals(VOLUME_CHANGED)) { } else if (event.equals(STARTED )) { } else if (event.equals(STOPPED)) { } else if (event.equals(DURATION_UPDATED)) { } else if (event.equals(END_OF_MEDIA)) { //Add code for actions if the end of media is reached. //Release resources when end of media event is received player.close(); } }

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry


Para transferir los datos desde un origen remoto a una aplicacin de dispositivo BlackBerry, debe almacenar en el bfer el origen y controlar cmo la aplicacin multimedia lee los datos. Extienda DataSource y cree una implementacin personalizada de SourceStream para enviar los datos a la aplicacin multimedia.

Archivo de reproduccin de vdeo RIMM


El formato de vdeo propio de RIM (archivo de reproduccin RIMM) consta de un encabezado, una lista de marcos y un pie de pgina. El archivo tambin cuenta con un descriptor que almacena metadatos adicionales. La ubicacin de este descriptor depende del destino de la grabacin. Si el destino de la grabacin es un archivo, el descriptor se ubica al final del encabezado, antes de la lista de marcos. Si el destino de la grabacin es un flujo, el descriptor se ubica despus de la lista de marcos en el pie de pgina.

22

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

Formato de vdeo propio de RIM (archivo de reproduccin RIMM)


El formato de vdeo propio de RIM consta de un encabezado, una lista de marcos y un pie de pgina. Al analizar este archivo, debe traducir los valores del tipo int o short de little-endian a big-endian. Encabezado Campo Etiqueta de ID versin ubicacin del descriptor descriptor Valor RIMM 0 0 si se graba en un archivo 1 si graba en un flujo Tamao 4B 3B 1B 79 B si se graba en un archivo 0 B si se graba en un flujo

valores del descriptor

Marcos Campo tipo de flujo fotograma clave marco de configuracin tamao duracin datos tipo de flujo fotograma clave marco de configuracin Valor 0 si se trata de un marco de audio 1 si se trata de un marco de vdeo 1 si se trata de un fotograma clave 0 de lo contrario Tamao 1B 1b

1 si se trata de un marco de configuracin 1 b 0 de lo contrario 30 b 2B <tamao> B 1B 1b

tamao de marco en bytes duracin del vdeo, en milisegundos los datos reales del marco 0 si se trata de un marco de audio 1 si se trata de un marco de vdeo 1 si se trata de un fotograma clave 0 de lo contrario

1 si se trata de un marco de configuracin 1 b 0 de lo contrario

23

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

Campo tamao duracin

Valor tamao de marco en bytes duracin del vdeo, en milisegundos

Tamao 30 b 2B

Nota: Los campos para el fotograma clave, el marco de configuracin y el tamao se almacenan en un int de 32 bits con los campos de fotograma clave y de marco de configuracin almacenados en los dos primeros bits. Pie de pgina Campo Descriptor Valor valores del descriptor Tamao 79 bytes si graba en un flujo 0 bytes si graba en un archivo

Descriptor Campo marcos de audio marcos de vdeo fotogramas clave de audio fotogramas clave de vdeo fotogramas de audio por segundo fotogramas de vdeo por segundo tamao de audio tamao de vdeo fotogramas de vdeo por segundo tamao mximo de marco de vdeo duracin del audio duracin del video RESERVADO Valor nmero de marcos de audio nmero de marcos video nmero de fotogramas clave de audio nmero de fotogramas clave de vdeo nmero de fotogramas de audio por segundo (el nmero de fotogramas por segundo cambia + 1) nmero de fotogramas de vdeo por segundo (el nmero de fotogramas por segundo cambia + 1) tamao del flujo de audio en bytes tamao del flujo de vdeo en bytes la velocidad inicial de reproduccin de vdeo, en fotogramas por segundo tamao del marco de vdeo de mayor tamao, en bytes duracin del flujo de audio, en milisegundos duracin del flujo de vdeo, en milisegundos indefinido Tamao 4B 4B 4B 4B 4B 4B 4B 4B 4B 4B 4B 4B 20 B

24

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

Campo ancho altura cdec de vdeo

Valor ancho de vdeo, en pxeles altura de vdeo, en pxeles 2 si el cdec de vdeo es mpeg4 5 si el cdec de vdeo es H.263 6 si el cdec de vdeo es H.264 0 si el cdec de audio es PCM 7 si el cdec de audio es AMR 0xA si el cdec de audio es AAC

Tamao 2B 2B 2B

cdec de audio

1B

Bfer y reproduccin de contenido multimedia


Puede utilizar la API multimedia para crear una clase personalizada que extienda javax.microedition.media.protocol.DataSource para personalizar cmo se leen los datos desde su aplicacin en el reproductor multimedia del dispositivo BlackBerry. DataSource proporciona una implementacin de SourceStream que utiliza SourceStream.read() para transferir datos. 1. Importe las clases y las interfaces necesarias.
import import import import import import import import java.lang.Thread; java.io.InputStream; java.io.OutputStream; javax.microedition.media.protocol.DataSource; javax.microedition.media.protocol.SourceStream; javax.microedition.io.ContentConnection; javax.microedition.io.file.FileConnection; net.rim.device.api.io.SharedInputStream;

2.

Cree una clase personalizada que extienda la clase abstracta


javax.microedition.media.protocol.DataSource. public final class LimitedRateStreamingSource extends DataSource {

3.

Declare los campos de instancia que necesitar para su implementacin de DataSource. Los campos siguientes se han tomado del proyecto de ejemplo bufferedplaybackdemo.
/** The stream connection over which media content is passed */ private ContentConnection _contentConnection; /** An input stream shared between several readers */ private SharedInputStream _readAhead; /** A stream to the buffered resource */ private LimitedRateSourceStream _feedToPlayer; /** The MIME type of the remote media file */ private String _forcedContentType;

25

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

/** The thread which retrieves the remote media file */ private ConnectionThread _loaderThread; /** The local save file into which the remote file is written */ private FileConnection _saveFile; /** A stream for the local save file */ private OutputStream _saveStream;

4.

Cree a un constructor para su clase personalizada.


LimitedRateStreamingSource(String locator) { super(locator); }

5.

Implemente javax.microedition.media.protocol.DataSource.connect(). Este mtodo se utiliza para abrir una conexin con el origen descrito por el localizador e inicia la comunicacin. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
public void connect() throws IOException {

6.

Implemente javax.microedition.media.protocol.DataSource.disconnect(). Este mtodo se utiliza para cerrar la conexin con el origen descrito por el localizador y libera recursos utilizados para mantener la conexin. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
public void disconnect() {

7.

Implemente javax.microedition.media.protocol.DataSource.getContentType(). Este mtodo se utiliza para recuperar un String que describe el tipo de contenido de los archivos multimedia que proporciona el origen. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
public String getContentType() { return _feedToPlayer.getContentDescriptor().getContentType(); }

8.

Implemente javax.microedition.media.protocol.DataSource.getStreams(). Este mtodo se utiliza para recuperar una recopilacin de los flujos que gestiona este origen. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
public SourceStream[] getStreams() { return new SourceStream[] { _feedToPlayer }; }

9.

Implemente javax.microedition.media.protocol.DataSource.start(). Este mtodo se utiliza para iniciar la transferencia de datos y debe llamarse antes de que los datos estn disponibles para la lectura. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
public void start() throws IOException { if (_saveStream != null) { _loaderThread = new ConnectionThread(); _loaderThread.start(); } }

26

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

10. Implemente javax.microedition.media.protocol.DataSource.stop(). Este mtodo se utiliza para detener la transferencia de datos. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
public void stop() throws IOException { // Set the boolean flag to stop the thread _stop = true; }

11.

Cree una clase que implemente javax.microedition.media.protocol.SourceStream. En este ejemplo, una clase interna se utiliza para proporcionar un flujo al recurso multimedia en el bfer. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
private final class LimitedRateSourceStream implements SourceStream {

12. Implemente getSeekType() para saber si los archivos multimedia tienen o no capacidad de bsqueda durante la reproduccin.
public int getSeekType() { return SEEKABLE_TO_START; }

13. Dentro de esta clase interna, implemente javax.microedition.media.protocol.SourceStream.read(). Este mtodo se utiliza para leer los datos del flujo de entrada en una matriz de bytes. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
public int read(byte[] bytes, int off, int len) throws IOException {

14. Dentro de esta clase interna, tambin podra implementar seek(), tell() y close(). Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin. 15. Bloquee la clase interna y cree otra clase interna que extienda java.lang.Thread. Utilice esto al crear un subproceso para descargar el archivo remoto y escribirlo en el archivo local. Consulte el proyecto de ejemplo bufferedplaybackdemo para obtener ms informacin.
private final class ConnectionThread extends Thread {

Cdigo de ejemplo: reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry


/** * A thread which downloads the remote file and writes it to the local file * From bufferedplaybackdemo\LimitedRateStreamingSource.java */ private final class ConnectionThread extends Thread { /** * Download the remote media file, then write it to the local file. */ public void run()

27

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

try {

byte[] data = new byte[READ_CHUNK]; int len = 0; // Until we reach the end of the file while (-1 != (len = _readAhead.read(data))) { _totalRead += len; if (!_bufferingComplete && _totalRead > getStartBuffer()) // We have enough of a buffer to begin playback _bufferingComplete = true; System.out.println("Initial Buffering Complete"); // updateLoadStatus("Buffering Complete");

} System.out.println("Downloading Complete"); System.out.println("Total Read: " + _totalRead); // If the downloaded data is not the same size // as the remote file, something is wrong. if (_totalRead != _contentConnection.getLength()) { System.err.println("* Unable to Download entire file *"); } _downloadComplete = true; _readAhead.setCurrentPosition(0); // Write downloaded data to the local file while (-1 != (len = _readAhead.read(data))) { _saveStream.write(data); } } catch (Exception e) { System.err.println(e.toString()); }

} if (_stop) { // Stop reading return; }

Cdigo de ejemplo: lectura de datos desde un bfer


Una vez la aplicacin multimedia lee todos los datos en el bfer, la aplicacin del dispositivo BlackBerry puede bloquear las solicitudes de lectura que realiza la aplicacin multimedia hasta almacenar ms datos en el bfer. Detenga las operaciones de lectura para garantizar que existe la cantidad especificada de datos de audio en el bfer para su reproduccin.
public // // // // int read(byte[] b, int off, int len) throws IOException { Read from a SharedInputStream that is shared with the same Stream that the ConnectionThread is downloading to. Although both streams handle the same data, each stream has a separate read location.

28

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

// The ConnectionThread works to keep its read location // as far ahead of the current playback position as possible. System.out.println("Read Request for: " + len + " bytes"); // limit bytes read to our readLimit. int readLength = len; if (readLength > getReadLimit()) { readLength = getReadLimit(); } int available; boolean restart_pause = false; for (;;) { /* * A read action is be restricted by the amount of data * available for a read operation. The application needs * to download a specific amount of data before the * application can start to playback audio. * Enough data must be available to perform a full read * operation. In this sample, the application configures * the amount of data that is required to start the playback * of audio and to perform a read operation. The application * uses the ReadLimit value to control the amount of data * the second readerreads during a read operation. * * The application uses the PauseBytes setting to determine * when the second reader has read all the data currently * provided by the first variable reader. When this occurs, * the application pauses until there is enough data in the * buffer for a read operation. * * The application uses the RestartBytes setting to define * when there is enough data in the buffer to perform a * read operation. */ available = _baseSharedStream.available(); if (downloadComplete) { // Ignore all restrictions if downloading is complete System.out.println("Complete, Reading: " + len + " - Available: " + available); return _baseSharedStream.read(b, off, len); } else if (bufferingComplete) { if (restart_pause && available > getRestartBytes()) { //Perform a read operation as there is now enough data in the buffer. System.out.println("Restarting - Available: " + available); restart_pause = false; return _baseSharedStream.read(b, off, readLength); } else if (!restart_pause && (available > getPauseBytes() || available > readLength)) { //Determine if a previous read operation was paused //and if there is enough data in the buffer to perform a read // operation. if (available < getPauseBytes()) { /*

29

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

available);

} System.out.println("Reading: " + readLength + " - Available: " +

* Perform a read operation, setting the * pause flag so that future reads will pause * until enough data for a read operation is * loaded into the buffer */ restart_pause = true;

return _baseSharedStream.read(b, off, readLength); } else if (!restart_pause) { // The buffer does not contain enough data for // a read operation. Pause the read operation // until enough data is loaded into the buffer. restart_pause = true; } } else { // Pause the thread to allow the data to download // before performing another read operation. try { Thread.sleep(100); } catch (Exception e) { System.err.println(e.getMessage()); } }

Cdigo de ejemplo: reproduccin de archivos multimedia desde un archivo en el dispositivo BlackBerry


El siguiente cdigo de ejemplo muestra cmo crear una aplicacin de dispositivo BlackBerry para descargar un archivo multimedia y reproducir los datos desde dicho archivo multimedia. Esto podra reducir la cantidad de tiempo que tarda la aplicacin multimedia del dispositivo BlackBerry en almacenar en el bfer y reproducir los datos multimedia.
public void connect() throws IOException { System.out.println("Loading: " + getLocator()); //Open a connection to the remote file s = (ContentConnection) Connector.open(getLocator(), Connector.READ); //Get the length of the remote file. System.out.println("Size: " + s.getLength()); //Get the name of the remote file. int filenameStart = getLocator().lastIndexOf('/'); int paramStart = getLocator().indexOf(';'); if (paramStart < 0) { paramStart = getLocator().length(); } String filename = getLocator().substring(filenameStart, paramStart); System.out.println("Filename: " + filename);

30

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

//Open a connection to the file on the local file system. saveFile = (FileConnection) Connector.open ("file:///SDCard/blackberry/music" + filename, Connector.READ_WRITE); //If a file with the same name as the remote file doesn't exist //on the local system, download the file again. if (!saveFile.exists()) { saveFile.create(); } //Configure the local file to be readable. saveFile.setReadable(true); //Create a shared input stream using the an input stream //from the local file. SharedInputStream fileStream = SharedInputStream.getSharedInputStream (saveFile.openInputStream()); fileStream.setCurrentPosition(0); //If the file on the local file system is smaller than the remote file, //download the file again. if (saveFile.fileSize() < s.getLength()) { // didn't get it all before, download again saveFile.setWritable(true); saveStream = saveFile.openOutputStream(); readAhead = SharedInputStream.getSharedInputStream(s.openInputStream()); } else { downloadComplete = true; readAhead = fileStream; s.close(); } if (forcedContentType != null) { feedToPlayer = new LimitedRateSourceStream(readAhead, forcedContentType); } else { feedToPlayer = new LimitedRateSourceStream(readAhead, s.getType()); }

Cdigo de ejemplo: anlisis de un archivo de reproduccin de vdeo RIMM


import java.io.*; import java.util.*; import javax.microedition.io.*; import javax.microedition.io.file.*; /** * */ public class KeyFrameOutputStream extends OutputStream { // output locations on the sd card private static final String OUT_DIR = "file:///SDCard/securitycam/"; private static final String OUT_FILE = "output.frames"; // some size constants private static final int HEADER_SIZE = 8; private static final int CHUNK_INFO_SIZE = 7;

31

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

// parsing states private static final int STATE_HEADER = 0; private static final int STATE_CHUNK_INFO = 1; private static final int STATE_DATA = 2; private static final int STATE_WAIT_FOR_NEXT = 3; // member variables private int _state; private int _pos; private boolean _isVideoFrame; private boolean _isKeyFrame; private boolean _isConfigFrame; private boolean _startSaving; private boolean _saveFrame; private int _dataSize; private int _duration; // temp buffer ref private byte[] _buf; private FileConnection _file; private OutputStream _out; private WriteThread _writer; private boolean _reading; public KeyFrameOutputStream() { _state = STATE_HEADER; _pos = 0; } public void open() { _reading = true; try { // create the file connection for our frame destination FileConnection dir = (FileConnection)Connector.open( OUT_DIR ); if( !dir.exists() ) { dir.mkdir(); } dir.close(); _file = (FileConnection)Connector.open( OUT_DIR + OUT_FILE ); if( !_file.exists() ) { _file.create(); } else { _file.truncate( 0L ); } _out = _file.openOutputStream(); } catch ( Exception e ) { } // start the write thread _writer = new WriteThread( _out ); _writer.start(); } public void startClosing() { // shuts down the write thread _reading = false; if( _writer != null ) _writer.stop(); }

32

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

public void write( int b ) throws IOException { if( _reading ) { switch( _state ) { case STATE_HEADER: // read the video stream header _pos++; if( _pos == HEADER_SIZE ) { _state = STATE_CHUNK_INFO; _buf = new byte[CHUNK_INFO_SIZE]; _pos = 0; } break; case STATE_CHUNK_INFO: // parse the information about the next chunk _buf[_pos] = (byte)b; _pos++; if( _pos == CHUNK_INFO_SIZE ) { // 1 indicates video frame, 0 indicates audio _isVideoFrame = (_buf[0] != 0); // key frame and config frame flags are in the top two bits // of the data size value _isKeyFrame = ((_buf[4] & 0x80) != 0); _isConfigFrame = ((_buf[4] & 0x40) != 0); _dataSize = ((int)(_buf[4] & 0x3f) << 24) | ((int)(_buf[3] & 0xff) << 16) | ((int)(_buf[2] & 0xff) << 8) | ((int)(_buf[1] & 0xff)); // duration is stored in the next two bytes _duration = ((int)(_buf[6] & 0xff) << 8) | ((int)(_buf[5] & 0xff)); // we want the config frame to be the first frame in our // output file if( !_startSaving ) { if( _isVideoFrame && _isConfigFrame ) { _startSaving = true; } } // after that only save the key frames _saveFrame = _startSaving && _isVideoFrame && ( _isConfigFrame || _isKeyFrame ); _state = STATE_DATA; if( _saveFrame ) { _buf = new byte[_dataSize]; } _pos = 0; } break; case STATE_DATA: // buffer the frame for writing to file if( _saveFrame ) _buf[_pos] = (byte)b; _pos++; if( _pos == _dataSize ) {

33

Gua de desarrollo

Reproduccin de archivos multimedia en una aplicacin de dispositivo BlackBerry

} public void close() throws IOException { // shut down the write thread and close our file try { _writer.join(); } catch ( InterruptedException ie ) { } _out.close(); _file.close(); } private static final class WriteThread extends Thread { // writes key frames to a file as they are found by our parser private Vector _frames; private boolean _running; private OutputStream _out; public WriteThread( OutputStream out ) { _frames = new Vector(); _running = true; _out = out; } public void run() { for( ;; ) { ByteArray frame = null; synchronized( this ) { if( _frames.size() > 0 ) { frame = (ByteArray)_frames.elementAt( 0 ); if( frame == null ) break; _frames.removeElementAt( 0 ); } else { if( !_running ) break; try { wait(); if( _running ) continue;

} break; case STATE_WAIT_FOR_NEXT: // skip over the chunk footer _pos++; if( _pos == CHUNK_INFO_SIZE ) { _state = STATE_CHUNK_INFO; _buf = new byte[CHUNK_INFO_SIZE]; _pos = 0; } break;

if( _saveFrame ) { _writer.addFrame( _buf ); } _state = STATE_WAIT_FOR_NEXT; _buf = new byte[CHUNK_INFO_SIZE]; _pos = 0;

34

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

} private static final class ByteArray { public byte[] array; public ByteArray( byte[] array ) { this.array = array; } }

} } public synchronized void addFrame( byte[] frame ) { _frames.addElement( new ByteArray( frame ) ); notifyAll(); } public synchronized void stop() { _running = false; notifyAll(); }

} } if( frame == null ) break; try { byte[] bytes = frame.array; _out.write( bytes, 0, bytes.length ); _out.flush(); } catch ( Exception e ) { }

} catch ( InterruptedException ie ) { }

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry


Grabar audio en una aplicacin de dispositivo BlackBerry
Un dispositivo BlackBerry puede grabar audio en cuatro formatos: Adaptive Multi-Rate (AMR), modulacin de cdigo de pulso (PCM) de 8 kHz mono y 16 bits, GSM con dispositivos BlackBerry funcionando en redes GSM y QCP con dispositivos BlackBerry funcionando en redes CDMA. El formato predeterminado de grabacin de audio es AMR. 1. Importe las clases necesarias.
import import import import import java.lang.Thread; javax.microedition.media.Manager; java.io.ByteArrayOutputStream; javax.microedition.media.Player; javax.microedition.media.control.RecordControl;

35

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

2.

En una clase que extienda Thread, cree una variable del tipo Player, una variable del tipo RecordControl para grabar archivos multimedia desde un Player, una variable del tipo ByteArrayOutputStream para el flujo de audio y una variable de matriz de bytes para almacenar datos de OutputStream. Tenga en cuenta que no es necesario que grabe el audio en un subproceso distinto ya que las operaciones de grabacin estn encadenadas por defecto.
final class { private private private private AudioRecorderThread extends Thread Player _player; RecordControl _rcontrol; ByteArrayOutputStream _output; byte _data[];

3. 4.

Cree una clase de un constructor.


AudioRecorderThread(){}

En un bloque try, en su implementacin del mtodo run(), invoque Manager.createPlayer(String locator) utilizando como parmetro un valor que especifique el cifrado a utilizar para grabar audio. Puede utilizar las siguientes Strings de localizador compatibles. AMR: capture://audio o capture://audio?encoding=amr o capture://audio?encoding=audio/
amr

PCM: capture://audio?encoding=pcm o capture://audio?encoding=audio/basic GSM: capture://audio?encoding=gsm o capture://audio?encoding=audio/x-gsm QCP: capture://audio?encoding=audio/qcelp 5. Cree un objeto Player invocando createPlayer() para capturar audio.
public void run() { try { _player = Manager.createPlayer("capture://audio");

6. 7. 8.

Invoque Player.realize().
_player.realize();

Invoque Player.getControl() para obtener los controles para grabar archivos multimedia desde un Player.
_rcontrol = (RecordControl)_player.getControl("RecordControl");

Cree un ByteArrayOutputStream para grabar el flujo de audio. Tenga en cuenta que tambin puede grabar directamente en un archivo especificado por una URL.
_output = new ByteArrayOutputStream();

9.

Invoque RecordControl.setRecordStream() para establecer el flujo de salida en el que la aplicacin del dispositivo BlackBerry grabar los datos.
_rcontrol.setRecordStream(_output);

10. Invoque RecordStore.startRecord() para iniciar la grabacin de audio e iniciar la reproduccin de archivos multimedia desde el Player.

36

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

_rcontrol.startRecord(); _player.start();

11.

En un bloque catch, especifique las acciones a realizar si ocurre una excepcin.


} catch (final Exception e){ //Perform actions }

12. Cree un bloque try en su implementacin del mtodo stop y, a continuacin, invoque RecordControl.commit() para detener la grabacin de audio.
public void stop() { try { _rcontrol.commit()

13. Invoque ByteArrayOutputStream.toByteArray() para escribir los datos de audio desde OutputStream a una matriz de bytes.
_data = _output.toByteArray();

14. Invoque ByteArrayOutputStream.close() y Player.close() para cerrar OutputStream y Player.


_output.close(); _player.close();

15. En un bloque catch, especifique las acciones a realizar si ocurre una excepcin.
} catch (Exception e) { //Perform actions }

Cdigo de ejemplo: registro de audio desde un objeto Player


final class AudioRecorderThread extends Thread { private Player _player; private RecordControl _rcontrol; private ByteArrayOutputStream _output; private byte _data[]; AudioRecorderThread() {} private int getSize() { return (_output != null ? _output.size() : 0); } private byte[] getAudioBuffer() { return _data; } public void run() { try { // Create a Player that records live audio. _player = Manager.createPlayer("capture://audio"); _player.realize(); // Get the RecordControl, configure the record stream,

37

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

} public void stop() { try { //Stop recording, record data from the OutputStream, //close the OutputStream and player. _rcontrol.commit(); _data = _output.toByteArray(); _output.close(); _player.close(); } catch (Exception e) { synchronized (UiApplication.getEventLock()) { Dialog.inform(e.toString()); } }

_rcontrol = (RecordControl)_player.getControl("RecordControl"); //Create a ByteArrayOutputStream to record the audio stream. _output = new ByteArrayOutputStream(); _rcontrol.setRecordStream(_output); _rcontrol.startRecord(); _player.start(); } catch (final Exception e) { UiApplication.getUiApplication().invokeAndWait(new Runnable() { public void run() { Dialog.inform(e.toString()); } }); }

Grabar vdeo con la aplicacin de grabacin de vdeo de BlackBerry


1. Importe las clases necesarias.
import net.rim.blackberry.api.invoke.CameraArguments; import net.rim.blackberry.api.invoke.Invoke;

2.

Cree un objeto CameraArguments.


CameraArguments vidargs = new CameraArguments(CameraArguments.ARG_VIDEO_RECORDER);

3.

Invoque invokeApplication() para iniciar la aplicacin de grabacin de vdeo.


Invoke.invokeApplication( Invoke.APP_TYPE_CAMERA, vidargs );

Utilizar la API multimedia para grabar vdeo


1. Importe las clases necesarias.

38

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

import import import import import import import import

java.io.OutputStream; net.rim.device.api.ui.Field; javax.microedition.io.Connector; javax.microedition.io.file.FileConnection; javax.microedition.media.Manager; javax.microedition.media.Player; javax.microedition.media.control.VideoControl; javax.microedition.media.control.RecordControl;

2.

Extienda MainScreen para crear una pantalla de grabacin de vdeo. Tenga en cuenta que tambin podra utilizar el marco de la interfaz de usuario de RIM o el marco de la interfaz de usuario de MIDP.
private static final class VideoRecordingScreen extends MainScreen {

3.

Cree un reproductor multimedia de video para capturar vdeo. Tenga en cuenta que System.getProperty( "video.encodings" ) se puede utilizar para detectar valores de propiedad de cifrado de vdeo y crear un URI que describa la captura de contenido de video en forma de "capture://video?" + encoding.
Player _player = javax.microedition.media.Manager.createPlayer( "capture://video?encoding=video/3gpp" );

4. 5.

Inicie Player
_player.start();

Obtenga un objeto VideoControl para controlar la colocacin del visor de vdeo y un objeto RecordControl para controlar el estado de grabacin.
VideoControl _vc = (VideoControl)_player.getControl( "VideoControl" ); RecordControl _rc = (RecordControl)_player.getControl( "RecordControl" );

6.

Existen distintas maneras de inicializar el modo de visualizacin de vdeo. La siguiente tcnica muestra cmo gestionar el proceso si desea un Field que represente la regin del visor de vdeo para su uso en la interfaz de usuario del dispositivo BlackBerry.
Field videoField = (Field)_vc.initDisplayMode( VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field" ); add( videoField );

7.

Para grabar un flujo de vdeo. a. Abra un FileConnection en el archivo de reproduccin de vdeo.


FileConnection _fc = (FileConnection)Connector.open( "file:///SDCard/ BlackBerry/videos/mmapi_stream.sbv" );

b.

Cree el archivo de reproduccin si no existe.


if( !_fc.exists() ) { _fc.create(); }

c.

Borre el archivo de reproduccin.

39

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

_fc.truncate( 0 );

d.

Abra OutputStream, asocie el flujo de grabacin con OutputStream e inicie la grabacin de dicho flujo. Al grabar en OutputStream, los datos se escribirn en un formato adecuado que facilita el anlisis de los marcos de audio y vdeo.
OutputStream _out = _fc.openOutputStream(); _rc.setRecordStream( _out ); _rc.startRecord();

e.

Una vez se ha capturado el flujo de vdeo, detenga el proceso y finalice la grabacin, cierre los flujos.
_rc.stopRecord(); _rc.commit(); _out.close(); _fc.close();

8.

Para grabar un vdeo en un archivo. a. Configure la ubicacin de salida donde se grabarn los datos.
RecordControl _rc.setRecordLocation( "file:///SDCard/BlackBerry/videos/ mmapi_video.3gp" );

b. c.

Inicie la grabacin de vdeo en formato 3GP.


_rc.startRecord();

Una vez se ha capturado el vdeo, detenga el proceso y finalice la grabacin.


_rc.stopRecord(); _rc.commit();

Cdigo de ejemplo: uso de la API multimedia para grabar vdeo


import import import import import import import import import import import /* * the */ public { /* * java.io.*; javax.microedition.media.*; javax.microedition.media.control.*; javax.microedition.io.*; javax.microedition.io.file.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.util.*; net.rim.device.api.system.*; net.rim.device.api.media.*; entry class class VideoRecordingApplication extends UiApplication working constants hard coded to create video files on the SD media card

40

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

*/ private static final String VIDEO_FILE = "file:///SDCard/BlackBerry/videos/mmapi_rimlet.3GP"; private static final String STREAM_VIDEO_FILE = "file:///SDCard/BlackBerry/videos/mmapi_stream.sbv"; /* * video recording screen object used in several places within */ private static VideoRecordingScreen _vrs; /* * constructor */ private VideoRecordingApplication() { /* * to select the video encoding */ pushScreen( new ChooseEncodingScreen() ); } /* * main() entry point */ public static void main( String[] args ) { /* * fire up the event dispatcher loop */ new VideoRecordingApplication().enterEventDispatcher(); } /* * select video encoding screen * called by the VideoRecordingApplication class constructor */ private static final class ChooseEncodingScreen extends MainScreen { private static ObjectChoiceField _encodings; /* * constructor */ public ChooseEncodingScreen() { super(); setTitle( "Choose an encoding" ); /* * load String[] array with all MMAPI video encoding system property values */ String[] encodings = getEncodings(); /* * prep for display */ _encodings = new ObjectChoiceField( "Encoding:", encodings, 0 );

41

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

scheme

/* * add field to this screen's manager */ add( _encodings ); /* * create a menu item to start recording using the selected encoding

*/ addMenuItem( new MenuItem( "Go", 0, 0 ) { public void run() { /* * create and display the video recording screen, passing the selected video encoding scheme */ _vrs = new VideoRecordingScreen( (String)_encodings.getChoice( _encodings.getSelectedIndex() ) ); UiApplication.getUiApplication().pushScreen( _vrs ); } } ); } /* * returns all MMAPI video encoding system property values */ private String[] getEncodings() { String[] encodings = new String[0]; /* * load String with all video.encodings property values * each value is separated by a space */ String encodingsString = System.getProperty( "video.encodings" ); /* * determine where the first value ends */ int space = encodingsString.indexOf( ' ' ); /* * loop through values, end when a new field separator is not found */ while( space != -1 ) { /* * add a new String array element that contains the system property value */ Arrays.add( encodings, encodingsString.substring( 0, space ) ); /* * remove the last property value from the encoding string */ encodingsString = encodingsString.substring( space + 1 ); /*

42

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

value

} /* * add a new String array element that contains the final system property */ Arrays.add( encodings, encodingsString ); /* * return the resulting String[] array */ return encodings;

* determine where the first value ends */ space = encodingsString.indexOf( ' ' );

} } /* * video recording screen displayed after the user selects "Go" from the menu */ private static final class VideoRecordingScreen extends MainScreen { private static Player _player; private static VideoControl _vc; private static RecordControl _rc; private static boolean _visible = true; private static boolean _locationSet = false; private static RichTextField _status; private static CheckboxField _stream; private static OutputStream _out; private static FileConnection _fc; private static RichTextField _flashIndicator; /* * constructor passed the chosen video encoding property value */ public VideoRecordingScreen( String encoding ) { super(); try { /* * create a video media player to capture video using the passed encoding value */ _player = javax.microedition.media.Manager.createPlayer( "capture://video?" + encoding ); /* * try to start the player */ _player.start(); _vc = (VideoControl)_player.getControl( "VideoControl" ); _rc = (RecordControl)_player.getControl( "RecordControl" ); /* * Initialize the mode on how the video is displayed. * This method must be called before the video can be displayed.

43

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

* * USE_GUI_PRIMITIVE defines a mode on how the GUI is displayed. * It is used in conjunction with initDisplayMode(int, java.lang.Object). */ Field videoField = (Field)_vc.initDisplayMode( VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field" ); /* * add field to this screen's manager */ add( videoField ); _status = new RichTextField( "Idle" ); add( _status ); _stream = new CheckboxField( "Use OutputStream", false ); add( _stream ); } catch ( Exception e ) { System.out.println( "Exception in VideoScreen constructor" ); } addMenuItem( new MenuItem( "Start Record", 0, 0 ) { public void run() { startRecord(); } } ); addMenuItem( new MenuItem( "Stop Record", 0, 0 ) { public void run() { stopRecord(); } } ); addMenuItem( new MenuItem( "Commit Record", 0, 0 ) { public void run() { commit(); } } ); addMenuItem( new MenuItem( "Toggle Visibility", 0, 0 ) { public void run() { toggleVisibility(); } } ); addMenuItem( new MenuItem( "Play Recording", 0, 0 ) { public void run() { //InputStream recording = _stream.getChecked() ? new // ByteArrayInputStream( _out.toByteArray() ) : null;

44

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

null ) );

Application.getApplication().invokeLater( new ShowVideoRunnable(

} } ); /* * this loads the streamed video into memory then does nothing with it */ addMenuItem( new MenuItem( "Analyze Recording Stream", 0, 0 ) { public void run() { try { /* * get a handle to the streaming video file located on the SDCard (declared near the start of this file) */ _fc = (FileConnection)Connector.open( STREAM_VIDEO_FILE ); /* * determine the file size */ long size = _fc.fileSize(); /* * declare a block of ram to store the file */ byte[] file = new byte[(int)size]; /* * open the stream for read */ InputStream in = _fc.openInputStream(); /* * load the file into memory */ in.read( file ); } catch ( Exception e ) { } } } ); } /* * decipher and act upon shortcut keys */ protected boolean keyChar( char c, int status, int time ) { switch( c ) { case 's': startRecord(); return true; case 'x': stopRecord(); return true; case 'c': commit();

45

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

);

} } /* * record captured video */ private void startRecord() { try { /* * _locationSet == false by default */ if( !_locationSet ) { /* * test if "Use OutputStream" CheckboxField is set */ if( _stream.getChecked() ) { try { _fc = (FileConnection)Connector.open( STREAM_VIDEO_FILE /* * create streaming file if it does not exist */ if( !_fc.exists() ) { _fc.create(); } /* * zap the file */ _fc.truncate( 0 ); /* * ready to write video stream */ _out = _fc.openOutputStream(); } catch ( Exception e ) { return; } _rc.setRecordStream( _out ); } else { /* * FileConnection: Set the output stream where the data will

return true; case 'v': toggleVisibility(); return true; case 'r': reset(); return true; default: return false;

46

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

be recorded. saved.

* The locator specifying where the recorded media will be * The locator must be specified as a URL. */ _rc.setRecordLocation( VIDEO_FILE );

} private void stopRecord() { try { /* * Stop recording the media. * stopRecord will not automatically stop the Player. * It only stops the recording, putting the Player in "standby" mode */ _rc.stopRecord(); _status.setText( "Recording stopped" ); } catch ( Exception e ) { } } private void commit() { try { /* * Complete the current recording. * If the recording is in progress, commit will implicitly call stopRecord. */ _rc.commit(); Dialog.alert( "Committed" ); _locationSet = false; _status.setText( "Committed" ); /* * video stream was recorded */ if( _stream.getChecked() ) { /* * close the stream */ try { _out.close();

} /* * Start recording the media. */ _rc.startRecord(); _status.setText( "Recording" ); } catch ( Exception e ) { }

} _locationSet = true;

47

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

} /* * toggle video visibility */ private void toggleVisibility() { try { _visible = !_visible; /* * show or hide the video */ _vc.setVisible( _visible ); } catch ( Exception e ) { } } /* * Erase the current recording */ private void reset() { try { _rc.reset(); _status.setText( "Reset called, idle" ); } catch ( Exception e ) { } } /* * hide the video */ public void hide() { try { _visible = false; _vc.setVisible( _visible ); } catch ( Exception e ) { } } /* * show the video */ public void show() { try { _visible = true; _vc.setVisible( _visible ); } catch ( Exception e ) {

} } catch ( Exception e ) { }

_fc.close(); } catch ( Exception e ) { }

48

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

} /* * ShowVideoRunnable() called within VideoRecordingScreen() through the "Play Recording" menu */ private static final class VideoPlaybackScreen extends MainScreen { private Player _video; private VideoControl _vc; public VideoPlaybackScreen( InputStream vid ) { super(); try { /* * existing video stream passed */ if( vid != null ) { /* * Create a Player to play back media from an InputStream (streamed video) */ _video = javax.microedition.media.Manager.createPlayer( vid, "video/x-rim" ); } else { /* * Create a Player from an input locator (a standard video file in .3GP format) */ _video = javax.microedition.media.Manager.createPlayer( VIDEO_FILE ); } /* * Constructs portions of the Player without acquiring the scarce and exclusive resources. */ _video.realize(); /* * Obtain the object that implements the specified Control interface. */ _vc = (VideoControl)_video.getControl( "VideoControl" ); /* * Initialize the mode on how the video is displayed */ Field vField = (Field)_vc.initDisplayMode( VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field" ); add( vField ); VolumeControl vol = (VolumeControl)_video.getControl( "VolumeControl" ); vol.setLevel( 30 );

49

Gua de desarrollo

Grabacin de archivos multimedia a travs de una aplicacin de dispositivo BlackBerry

} /* * called within VideoRecordingScreen() through the "Play Recording" menu */ private static final class ShowVideoRunnable implements Runnable { private InputStream _in; public ShowVideoRunnable( InputStream in ) { _in = in; } public void run() { /* * hide the VideoRecordingScreen */ _vrs.hide(); /* * Retrieves this UI application object. */ UiApplication ui = UiApplication.getUiApplication(); /* * handle video playback */ ui.pushScreen( new VideoPlaybackScreen( _in ) );

} protected void onVisibilityChange( boolean visible ) { if( visible ) { try { /* * Starts the Player as soon as possible. */ _video.start(); } catch ( Exception e ) { } } } public boolean onClose() { try { /* * Close the Player and release its resources. */ _video.close(); } catch ( Exception e ) { } _vrs.show(); return super.onClose(); }

} catch ( Exception e ) { System.out.println( "Exception while showing video" ); }

50

Gua de desarrollo

Reproducir archivos multimedia en la aplicacin multimedia del dispositivo BlackBerry

Reproducir archivos multimedia en la aplicacin multimedia del dispositivo BlackBerry


En los dispositivos BlackBerry que incluyen la aplicacin multimedia de dispositivos BlackBerry, una aplicacin de dispositivo BlackBerry puede utilizar los paquetes javax.microedition.content y net.rim.device.api.content para iniciar la aplicacin multimedia del dispositivo BlackBerry pasando o sin pasar contenido multimedia para cargarlo.

Iniciar la aplicacin multimedia con o sin contenido


1. 2. Importe la clase necesaria.
import javax.microedition.content;

Invoque Registry.getRegistry(classname) donde el parmetro classname es el nombre de la clase en la aplicacin del dispositivo BlackBerry que extiende javax.microedition.midlet.MIDlet, net.rim.device.api.system.Application o net.rim.device.api.ui.UiApplication. Almacene una referencia al objeto devuelto en un objeto Registry.
Registry reg = Registry.getRegistry(String classname);

3.

Lleve a cabo una de las siguientes tareas: Tarea Iniciar la aplicacin multimedia con o sin contenido. Iniciar la aplicacin multimedia con contenido Pasos Cree una instancia nueva de un objeto Invocation. Almacenar una referencia al objeto en un objeto Invocation.
Invocation invocation = new Invocation(null, null, BlackBerryContentHandler.ID_MEDIA_CONTENT_HANDLER)

Cree una instancia nueva de un objeto Invocation. Utilice un tipo multimedia compatible con la aplicacin multimedia como parmetro y almacene una referencia al objeto en un objeto Invocation.
Invocation invocation = new Invocation("file://...")

4.

Para iniciar la aplicacin multimedia, invoque Registry.invoke(Invocation invocation) pasando un objeto


Invocation. reg.invoke(invocation)

51

Gua de desarrollo

Reproducir archivos multimedia en la aplicacin multimedia del dispositivo BlackBerry

Reproducir audio en BlackBerry Browser


1. Importe las clases necesarias.
import net.rim.blackberry.api.browser.Browser; import net.rim.blackberry.api.browser.BrowserSession;

2. 3.

Invoque Browser.getDefaultSession().
BrowserSession soundclip = Browser.getDefaultSession();

Invoque BrowserSession.displaypage().
soundclip.displayPage("file:///SDCard/BlackBerry/music/yourFile.mp3");

Reproducir un vdeo en BlackBerry Browser.


1. Importe las clases necesarias.
import net.rim.blackberry.api.browser.Browser; import net.rim.blackberry.api.browser.BrowserSession;

2. 3.

Invoque Browser.getDefaultSession().
BrowserSession videoclip = Browser.getDefaultSession();

Invoque BrowserSession.displaypage().
videoclip.displayPage("file:///SDCard/BlackBerry/Video/soccergame avi");

52

Gua de desarrollo

Trabajo con imgenes de la aplicacin Cmara

Trabajo con imgenes de la aplicacin Cmara


Iniciar la cmara desde una aplicacin del dispositivo BlackBerry

Puede crear una aplicacin de dispositivo BlackBerry que utilice la clase Invoke para iniciar la aplicacin Cmara de forma que el usuario del dispositivo BlackBerry pueda tomar una fotografa. 1. Importe la clase necesaria.
import net.rim.blackberry.api.invoke.Invoke;

2.

Invoque invokeApplication() para invocar la aplicacin Cmara.


Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA, new CameraArguments());

Crear una aplicacin Gestor de contenido que reproduzca multimedia


Este artculo describe el desarrollo de una aplicacin Gestor de contenido que utiliza JSR 211 para permitir a las aplicaciones invocar otras aplicaciones, incluidas las aplicaciones nativas del dispositivo BlackBerry, para gestionar tipos de contenido especficos. Al registrar el gestor de contenido para gestionar tipos de contenido de vdeo o imgenes con la accin SEND, por ejemplo, aparecer un elemento de men siempre que vea un vdeo o imagen en la pantalla de vista previa de la cmara, en el explorador de archivos, etc. Al hacer clic en este men, el elemento de men invocar el gestor de contenido con una accin SEND y un vnculo al vdeo o imagen. 1. Importe las clases necesarias.
import import import import import javax.microedition.content.ContentHandlerServer; javax.microedition.content.RequestListener; javax.microedition.content.Registry; javax.microedition.content.Invocation; javax.microedition.content.ActionNameMap;

2.

Cree una clase que extienda UiApplication e implemente RequestListener.


public final class SendMediaDemo extends UiApplication implements RequestListener {

3.

Gestione el inicio de la aplicacin.


public static void main(String[] args) throws Exception { if(args != null && args.length > 0) { if (args[0].equals("startup")) { // Register ourselves as a content handler on startup register(); } } else { // Create a new instance of the application and make the currently

53

Gua de desarrollo

Crear una aplicacin Gestor de contenido que reproduzca multimedia

// running thread the application's event dispatching thread. SendMediaDemo app = new SendMediaDemo(); app.enterEventDispatcher();

4.

Registre la aplicacin como un RequestListener.


public SendMediaDemo() throws ContentHandlerException { // Get access to the ContentHandlerServer for this application and // register as a listener. ContentHandlerServer contentHandlerServer = Registry.getServer(CLASSNAME); contentHandlerServer.setListener(this); }

5.

Cree un mtodo para gestionar el registro del gestor de contenido. Este mtodo utilizar Registry.register() para garantizar que esta aplicacin pueda ser iniciada con opciones de men externas para enviar vdeo e imgenes a esta aplicacin.
private static void register() throws ContentHandlerException { String[] types = {"image/bmp", "image/png", "image/jpeg", "video/3gpp", "video/mp4"}; String[] suffixes = {".bmp", ".png", ".jpg", ".3GP", ".mp4"}; String[] actions = {ContentHandler.ACTION_SEND}; String[] actionNames = {"Send to demo app"}; ActionNameMap[] actionNameMaps = {new ActionNameMap(actions,actionNames,"en")}; // Get access to the registry Registry registry = Registry.getRegistry(CLASSNAME); // Register as a content handler registry.register(CLASSNAME, types, suffixes, actions, actionNameMaps, ID, null); }

6.

Implemente RequestListener.invocationRequestNotify(). Este gestor se invocar cuando otra aplicacin pasa el contenido a esta aplicacin.
public void invocationRequestNotify(ContentHandlerServer server) { Invocation invoc = server.getRequest(false); if(invoc != null) { String type = invoc.getType(); if(type.equals("image/bmp") || type.equals("image/png") || type.equals("image/jpeg")) { byte[] data = getData(invoc.getURL()); displayImage(data); } else if(type.equals("video/3gpp") || type.equals("video/mp4")) { initVideo(invoc.getURL()); if(_videoField != null) { displayVideo(); } } else {

54

Gua de desarrollo

Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia

System.exit(0); } server.finish(invoc, Invocation.OK);

Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia
package com.rim.samples.device.sendmediademo; import java.io.*; import javax.microedition.content.*; import javax.microedition.io.*; import javax.microedition.media.*; import javax.microedition.media.control.*; import javax.microedition.io.file.*; import net.rim.device.api.system.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; public final class SendMediaDemo extends UiApplication implements RequestListener { private static final String ID = "com.rim.samples.device.sendmediademo"; private static final String CLASSNAME = "com.rim.samples.device.sendmediademo.SendMediaDemo"; private Player _player; private Field _videoField; private VideoControl _vc; /** * Entry point for application * @param args Command line arguments */ public static void main(String[] args) { if(args != null && args.length > 0) { if (args[0].equals("startup")) { // Register ourselves as a content handler on startup register(); } } else { // Create a new instance of the application and make the currently // running thread the application's event dispatching thread. SendMediaDemo app = new SendMediaDemo(); app.enterEventDispatcher(); }

55

Gua de desarrollo

Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia

} /** * Registers this application as a content handler for image files */ private static void register() { String[] types = {"image/bmp", "image/png", "image/jpeg", "video/3gpp", "video/mp4"}; String[] suffixes = {".bmp", ".png", ".jpg", ".3GP", ".mp4"}; String[] actions = {ContentHandler.ACTION_SEND}; String[] actionNames = {"Send to demo app"}; ActionNameMap[] actionNameMaps = {new ActionNameMap(actions,actionNames,"en")}; // Get access to the registry Registry registry = Registry.getRegistry(CLASSNAME); try { // Register as a content handler registry.register(CLASSNAME, types, suffixes, actions, actionNameMaps, ID, null); } catch (ContentHandlerException che) { System.out.print(che.toString()); } catch (ClassNotFoundException cnfe) { System.out.print(cnfe.toString()); } } // Constructor public SendMediaDemo() { try { // Get access to the ContentHandlerServer for this application and // register as a listener. ContentHandlerServer contentHandlerServer = Registry.getServer(CLASSNAME); contentHandlerServer.setListener(this); } catch(ContentHandlerException che) { System.out.println(che.toString()); } } /** * RequestListener implementation * @param server The content handler server from which to request Invocation objects */ public void invocationRequestNotify(ContentHandlerServer server)

56

Gua de desarrollo

Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia

Invocation invoc = server.getRequest(false); if(invoc != null) { String type = invoc.getType(); if(type.equals("image/bmp") || type.equals("image/png") || type.equals("image/jpeg")) { byte[] data = getData(invoc.getURL()); displayImage(data); } else if(type.equals("video/3gpp") || type.equals("video/mp4")) { initVideo(invoc.getURL()); if(_videoField != null) { displayVideo(); } } else { System.exit(0); } server.finish(invoc, Invocation.OK); } } /** * Sets the size of the video * @param width Width of the video display * @param height Height of the video display */ private void setVideoSize(int width, int height) { try { if (_vc != null) { _vc.setDisplaySize(width, height); } } catch(MediaException pe) { System.out.println(pe.toString()); } } /** * Creates and initializes a video player * @param url The URL of the video file to play */ private void initVideo(String url) { try

57

Gua de desarrollo

Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia

_player = javax.microedition.media.Manager.createPlayer(url); _player.realize(); _vc = (VideoControl) _player.getControl("VideoControl"); if (_vc != null) { _videoField = (Field) _vc.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field"); _vc.setVisible(true); } } catch(MediaException pe) { System.out.println(pe.toString()); } catch (IOException ioe) { System.out.println(ioe.toString()); } } /** * Returns a byte array containing data representing the image at the specified URL * @param url The location of the image to display * @return The image data */ private byte[] getData(String url) { byte[] data = new byte[0]; try { FileConnection file = (FileConnection)Connector.open(url); int fileSize = (int)file.fileSize(); data = new byte[fileSize]; InputStream inputStream = file.openInputStream(); inputStream.read(data); } catch(Exception e) { System.out.println(e.toString()); } return data; } /** * Creates a screen and displays the image * @param data The data representing the image to be rendered */ private void displayImage(byte [] data) { // Create image field Bitmap image = Bitmap.createBitmapFromBytes( data, 0, -1, 5); BitmapField imageField = new BitmapField( image, Field.FIELD_HCENTER);

58

Gua de desarrollo

Cdigo de ejemplo: crear una aplicacin Gestor de contenido que reproduzca multimedia

// Create and display screen MainScreen screen = new MainScreen(net.rim.device.api.ui.Manager.NO_VERTICAL_SCROLL); screen.setTitle("Send Media Demo"); screen.add(imageField); pushScreen(screen); } /** * Creates a video screen and starts the video player */ private void displayVideo() { // Create and display screen VideoMainScreen screen = new VideoMainScreen(); screen.setTitle("Send Media Demo"); screen.add(_videoField); pushScreen(screen); try { // Start media player _player.start(); } catch(MediaException pe) { System.out.println(pe.toString()); } } /** * A main screen in which to play video files */ final private class VideoMainScreen extends MainScreen { // Constructor VideoMainScreen() { super(net.rim.device.api.ui.Manager.NO_VERTICAL_SCROLL); } /** * @see net.rim.device.api.ui.Manager#sublayout(int,int) */ protected void sublayout(int width, int height) { setVideoSize(Display.getWidth(), Display.getHeight()); super.sublayout(width, height); } /** * @see net.rim.device.api.ui.Screen#onClose() */ public boolean onClose() { _player.close();

59

Gua de desarrollo

Recibir una notificacin de los eventos del sistema de archivos

return super.onClose();

Recibir una notificacin de los eventos del sistema de archivos


Puede crear una aplicacin de dispositivo BlackBerry que utilice las siguientes clases e interfaz para detectar cundo se agrega o elimina una imagen de un sistema de archivos para un dispositivo BlackBerry. La clase FileSystemJournal acta como un diario que efecta un seguimiento de los cambios en el sistema de archivos. La aplicacin del dispositivo BlackBerry puede consultar a este diario con el fin de obtener informacin acerca de los eventos del sistema de archivos.
net.rim.device.api.io.file.FileSystemJournal net.rim.device.api.io.file.FileSystemJournalEntry net.rim.device.api.io.file.FileSystemJournalListener

Detectar cundo se agrega o elimina una imagen en el sistema de archivos del dispositivo BlackBerry
1. Importe las clases necesarias.
import net.rim.device.api.system.Application; import net.rim.device.api.io.file.FileSystemJournalListener;

2.

Implemente la interfaz FileSystemJournalListener.


class FileExplorerDemoJournalListener implements FileSystemJournalListener {

3. 4.

Cree una variable de la instancia que representa el ltimo nmero de la secuencia de actualizacin.
private long _lastUSN;

Implemente FileSystemJournalListener.fileJournalChanged() para recibir notificaciones cuando ocurra un nuevo evento del sistema de archivos.
public void fileJournalChanged() {

5. 6.

Dentro de la implementacin del archivo JournalChanged(), debe obtener el siguiente USN que utilizar el diario.
long nextUSN = FileSystemJournal.getNextUSN();

Cree un bucle for que itere hacia atrs desde el siguiente USN que utilizar el diario. Una prctica recomendada consiste en detener la iteracin una vez la aplicacin del dispositivo BlackBerry recupera una entrada del diario.
for (long lookUSN = nextUSN - 1; lookUSN >= _lastUSN && msg == null; --lookUSN) {

60

Gua de desarrollo

Recuperar una imagen

7. 8.

En el bucle for, recupere la entrada del diario que se corresponde con el USN actual.
FileSystemJournalEntry entry = FileSystemJournal.getEntry(lookUSN);

Cree una clusula IF que compruebe si la entrada en el diario es nula. Si es as, la nueva entrada del diario del sistema no existe.
if (entry == null) { break; }

9.

En el caso de que exista la entrada del diario, debe obtener la ruta asociada con la entrada.
String path = entry.getPath();

10. Cree una clusula IF que compruebe si la ruta de la entrada no es nula.


if (path != null) {

11.

Cree una clusula IF que compruebe si el evento del sistema de archivos implica un archivo de imagen.
if (path.endsWith("png") || path.endsWith("jpg") || path.endsWith("bmp") || path.endsWith("gif") ){

12. Lleve a cabo las acciones correspondientes si se ha agregado o eliminado un archivo del sistema de archivos.
switch (entry.getEvent()) { case FileSystemJournalEntry.FILE_ADDED: //either a picture was taken or a picture was added to the BlackBerry device break; case FileSystemJournalEntry.FILE_DELETED: //a picture was removed from the BlackBerry device; break;

13. Invoque Application.addFileSystemJournalListener() para agregar el oyente a la aplicacin de dispositivo BlackBerry. En este ejemplo, FileExplorerDemo extiende UIApplication que extiende a su vez Application.
this.addFileSystemJournalListener(new FileExplorerDemoJournalListener());

Recuperar una imagen


1. Importe las clases e interfaces necesarias.
import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection;

2. 3.

Implemente la siguiente interfaz. javax.microedition.io.file.FileConnection Invoque Connector.open() utilizando como parmetro la ubicacin de la imagen en el dispositivo BlackBerry o la tarjeta microSD.

61

Gua de desarrollo

Mover una imagen dentro del mismo directorio del sistema de archivos

FileConnection fconn = (FileConnection)Connector.open("file:///store/home/user/pictures/ newfile.jpg"); FileConnection fconn = (FileConnection)Connector open("file:///SDCard/pictures/newfile.jpg");

Mover una imagen dentro del mismo directorio del sistema de archivos
Las imgenes se pueden mover cambiando el nombre de un archivo o directorio seleccionado por un nombre nuevo en el mismo directorio, siempre que el nombre nuevo no est ya en uso. El nombre del archivo o directorio cambia inmediatamente en el sistema de archivos real tras la invocacin de este mtodo. Tras la llamada a este mtodo el archivo o directorio con el nombre original dejar de existir. 1. Importe las clases e interfaces necesarias.
import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection;

2.

Invoque Connector.open() con un parmetro de la ubicacin de la imagen en una tarjeta de microSD.


FileConnection fconn = (FileConnection)Connector.open("file:///SDCard/pictures/newfile.jpg");

3.

Invoque FileConnection.rename().
fconn.rename("newfilename.jpg");

Mover una imagen a un directorio diferente del sistema de archivos


1. Importe las clases e interfaz necesarias.
import import import import java.io.InputStream; java.io.OutputStream; javax.microedition.io.Connector; javax.microedition.io.file.FileConnection;

2.

Almacene el nombre y ubicacin del archivo anterior y del archivo nuevo.


String oldFile = "file:///store/home/user/pictures/newfile.jpg"; String newFile = "file:///SDCard/pictures/newfile.jpg";

3.

Cree una conexin de archivo para la ubicacin anterior y nueva del archivo.
FileConnection source = (FileConnection) Connector.open(oldFile); FileConnection dest = (FileConnection) Connector.open(newFile);

4.

Si el archivo no existe en el directorio de destino, crelo.

62

Gua de desarrollo

Eliminar una imagen del sistema de archivos

if (!dest.exists()) { dest.create(); }

5. 6. 7. 8. 9.

El archivo en el directorio de destino debe tener permiso de escritura.


dest.setWritable(true);

Abra un flujo de salida a la ubicacin de destino del archivo.


OutputStream outStream = dest.openOutputStream();

Abra un flujo de entrada a la ubicacin de origen del archivo.


InputStream inStream = source.openInputStream();

Cree una matriz Byte que represente el tamao del bfer para FileInputStream.
byte[] Buffer = new byte[1024];

Cree un bucle While que lea los datos desde InputStream y hasta OutputStream.
int length = -1; while ((length = inStream.read(buffer)) > 0) { outStream.write(buffer, 0 , length); }

10. Elimine el archivo de origen y, a continuacin, cierre las conexiones del flujo de entrada y de salida.
inStream.delete(); inStream.close(); outStream.close();

Eliminar una imagen del sistema de archivos


1. Importe las clases e interfaces necesarias.
import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection;

2.

Invoque Connector.open() utilizando como parmetro la ubicacin de la imagen en el dispositivo BlackBerry o la tarjeta microSD.
FileConnection fconn = (FileConnection)Connector.open("file:///store/home/user/pictures/ newfile.jpg");

3. 4.

Invoque FileConnection.delete().
fconn.delete();

Puesto que invocar FileConnection.delete() vaca y cierra automticamente todos los flujos de entrada y salida, debe invocar FileConnection.close() para evitar que ocurran excepciones.

63

Gua de desarrollo

Eliminar una imagen del sistema de archivos

fconn.close();

64

Gua de desarrollo

Dibujar y posicionar imgenes

Dibujar y posicionar imgenes

Su aplicacin de dispositivo BlackBerry puede utilizar objetos Graphics para llevar a cabo funciones de dibujo y operaciones de representacin. Utilice la clase Graphics para dibujar sobre toda la pantalla o en una clase Field. Si su aplicacin no cuenta con ningn campo, omita el mtodo javax.microedition.lcdui.Canvas.paint(Graphics) para realizar el dibujo utilizando el objeto Graphics especificado. Para dibujar en un objeto Bitmap especfico, una aplicacin de dispositivo BlackBerry obtiene un contexto grfico pasando el objeto Bitmap al constructor Graphics. Para dibujar sobre un objeto Bitmap sin cambiar el contenido de Bitmap, cree un BitmapField y pase el objeto Bitmap al constructor BitmapField. Al dibujar en un campo, el administrador del campo pasa un contexto grfico a los campos cuando stos se vuelven a dibujar. Para realizar dibujos personalizados en un campo, omita el mtodo paint(Graphics g) cuando extienda la clase Field. La clase Graphics le permite dibujar formas, por ejemplo, arcos, lneas, rectngulos y crculos.

Posicionar una imagen


1. Importe las clases necesarias.
import import import import net.rim.device.api.system.Bitmap; net.rim.device.api.ui.component.BitmapField; net.rim.device.api.ui.Graphics; net.rim.device.api.ui.container.MainScreen;

2.

Realice una de las siguientes tareas: Tarea Utilice un campo para posicionar la imagen Pasos a. Invoque el constructor Graphics().
Bitmap surface = new Bitmap(100, 100); BitmapField surfaceField = new BitmapField(surface); Graphics graphics = new Graphics(surface);

b. Utilice la pantalla de una a. aplicacin para posicionar la imagen b.

Agregue BitmapField a la pantalla.


mainScreen.add(surfaceField);

Invoque el mtodo Screen.getGraphics().


Graphics graphics = Screen.getGraphics();

Especifique que los mtodos llevan a cabo las funciones de dibujo dentro de los lmites de la pantalla.
graphics.fillRect(10, 10, 30, 30); graphics.drawRect(15, 15, 30, 30);

65

Gua de desarrollo

Comprobar que el dispositivo BlackBerry es compatible con una pantalla en color

Comprobar que el dispositivo BlackBerry es compatible con una pantalla en color


1. 2. Importe la clase necesaria.
import net.rim.device.api.system.Display;

Invoque Display.isColor().
if( Display.isColor() ) { RED = 0xff0000; GREEN = 0x00ff00; BLUE = 0x5555ff; } else { RED = 0xffffff; GREEN = 0xffffff; BLUE = 0xffffff; }

Recuperar el nmero de colores con los que es compatible la pantalla del dispositivo BlackBerry
1. 2. Importe la clase necesaria.
import net.rim.device.api.system.Display;

Invoque Display.getNumColors().
switch( Display.getNumColors() case 2: // MONO modes = new int[] { 0, break; case 4: // GRAYSCALE modes = new int[] { 0, break; case 65536: // COLOR modes = new int[] { 0, break; } ) { 1 }; 1, 4, 5 }; 1, 8, 9, 11 };

66

Gua de desarrollo

Configurar la transparencia del pxel en el rea de trabajo

Configurar la transparencia del pxel en el rea de trabajo


La transparencia del pxel se establece en el valor alfa global y actual para dibujar operaciones. Este valor oscila entre 0 (completamente transparente) y 255 (completamente opaco). El valor actual se puede recuperar a travs de Graphics.getGlobalAlpha() y puede configurarse utilizando Graphics.setGlobalAlpha(). 1. Importe la clase necesaria.
import net.rim.device.api.ui.Graphics;

2. 3.

Cree una instancia de un objeto Graphics.


private Graphics _g;

Realice una de las siguientes tareas: Para configurar el valor alfa global, invoque _g.setGlobalApha(). Para recuperar el valor alfa global, invoque _g.getGlobalApha().

Consultar las operaciones de malla con las que es compatible la aplicacin de dispositivo BlackBerry
La aplicacin de dispositivo BlackBerry puede utilizar Graphics.isRopSupported(int rop) para consultar si una operacin de malla en particular es compatible con el objeto Graphics. 1. Importe la clase necesaria.
import net.rim.device.api.ui.Graphics;

2. 3.

Cree una instancia de un objeto Graphics.


private Graphics _g;

Invoque Graphics.isRopSupported(int) pasando una constante ROP_* o ROP2_* como parmetro.


if ( _g.isRopSupported(Graphics.ROP_SRC_COPY)) {

Dibujar una ruta sombreada y con relleno


1. 2. Importe la clase necesaria.
import net.rim.device.api.ui.Graphics;

Invoque Graphics.drawShadedFilledPath().
public void paint(Graphics g) { g.setColor(186895); int x[] = { 71,90,150,100,115,71,30,45,0,55 }; int y[] = { 30,75,75,108,160,130,160,108,75,75 };

67

Gua de desarrollo

Cdigo de ejemplo: dibujo de una ruta que pase del azul al rojo en la pantalla de un dispositivo BlackBerry

int col[] = { 186895,186895,186895,186895,186895,186895,186895,186895,186895,1868 5 }; g.drawShadedFilledPath( x, y, null, col, null ); this.getUiEngine().updateDisplay(); }

Cdigo de ejemplo: dibujo de una ruta que pase del azul al rojo en la pantalla de un dispositivo BlackBerry
int _width = Display.getWidth(); int _height = Display.getHeight(); Bitmap surface = new Bitmap(_width, _height); BitmapField surfaceField = new BitmapField(surface); add(surfaceField); Graphics graphics = new Graphics(surface); int[] X_PTS = { 0, 0, _width, _width }; int[] Y_PTS = { 20, 50, 50, 20 }; int[] drawColors = { 0x0000CC, 0x0000CC, 0xCC0000, 0xCC0000 }; try { graphics.drawShadedFilledPath(X_PTS, Y_PTS, null, drawColors, null); } catch (IllegalArgumentException iae) { System.out.println("Bad arguments."); }

Activar o desactivar un estilo de dibujo


1. 2. 3. Importe la clase necesaria.
import net.rim.device.api.ui.Graphics;

Cree una instancia de un objeto Graphics.


private Graphics _g;

Invoque Graphics.setDrawingStyle(int drawStyle, boolean on) donde el parmetro "on" se ha configurado en true para activar el estilo de dibujo y en false para desactivar el estilo de dibujo
_g.setDrawingStyle(Graphics.DRAWSTYLE_AAPOLYGONS, true); _g.setDrawingStyle(Graphics.DRAWSTYLE_AAPOLYGONS, false);

Determinar si se ha configurado un estilo de dibujo


1. Importe la clase necesaria.

68

Gua de desarrollo

Cdigo de ejemplo: determinacin de si el estilo de dibujo especificado est activado

import net.rim.device.api.ui.Graphics;

2.

Invoque Graphics.isDrawingStyleSet(int drawStyle).


if(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)) {

Cdigo de ejemplo: determinacin de si el estilo de dibujo especificado est activado


public static void paintPanel( Graphics g, int width, int height, boolean isBottomRow, int panelType ) { int[] colors; if(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)) { colors = new int[]{ COLOR_BACKGROUND_FOCUS, COLOR_BACKGROUND_FOCUS, COLOR_GRADIENT_END_FOCUS, COLOR_GRADIENT_END_FOCUS }; g.setColor(COLOR_BACKGROUND_FOCUS);] } else { colors = new int[]{ COLOR_BACKGROUND, COLOR_BACKGROUND, COLOR_GRADIENT_END, COLOR_GRADIENT_END }; g.setColor(COLOR_BACKGROUND); } }

Utilizar una imagen de mapa de bits monocromticos como marca


El dibujo de una marca en una imagen de mapa de bits permite que los pxeles transparentes sigan siendo transparentes (slo se actualizarn los pxeles opacos). 1. 2. Importe la clase necesaria.
import net.rim.device.api.ui.component.BitmapField;

Para utilizar una imagen de mapa de bits monocromticos como marca mediante la representacin en color de la regin no transparente, debe crear un objeto BitmapField utilizando como parmetro la constante STAMP_MONOCHROME. Deber utilizar nicamente la constante STAMP_MONOCHROME con imgenes de mapa de bits que tengan una profundidad de bits de 1 con alfa definido.

69

Gua de desarrollo

Cdigo de ejemplo: demostracin del uso de una imagen de mapa de bits monocromticos como marca

BitmapField field = new BitmapField(original, BitmapField.STAMP_MONOCHROME);

Cdigo de ejemplo: demostracin del uso de una imagen de mapa de bits monocromticos como marca
final class DrawDemoScreen extends MainScreen { DrawDemoScreen() { LabelField title = new LabelField("UI Demo", LabelField.USE_ALL_WIDTH); setTitle(title); Bitmap original = Bitmap.getPredefinedBitmap(Bitmap.INFORMATION); Bitmap restored = new Bitmap(original.getType(), original.getWidth(), original.getHeight()); Graphics graphics = new Graphics(restored); // Retrieve raw data from original image. int[] argb = new int[original.getWidth() * original.getHeight()]; original.getARGB(argb, 0, original.getWidth(), 0, 0, original.getWidth(), original.getHeight()); // Draw new image using raw data retrieved from original image. graphics.drawRGB(argb, 0, restored.getWidth(), 0, 0, restored.getWidth(), restored.getHeight()); if(restored.equals(original)) { System.out.println("Success! Bitmap renders correctly with RGB data."); } else if(!restored.equals(original)) { System.out.println("Bitmap rendered incorrectly with RGB data."); } BitmapField field1 = new BitmapField(original, BitmapField.STAMP_MONOCHROME); BitmapField field2 = new BitmapField(restored); add(new LabelField("Original bitmap: ")); add(field1); add(new LabelField("Restored bitmap: ")); add(field2); } }

Crear una imagen de mapa de bits utilizando otra imagen de mapa de bits
Una aplicacin de dispositivo BlackBerry puede manipular directamente los datos de imgenes sin procesar una vez que los datos de las imgenes sin procesar de una regin especfica en una imagen de bits se almacenen en una matriz de enteros.

70

Gua de desarrollo

Crear una imagen de mapa de bits que contenga contenido con tamao modificado de otra imagen de mapa de bits

Crear una imagen de mapa de bits que contenga contenido con tamao modificado de otra imagen de mapa de bits
1. 2. 3. 4. Importe la clase necesaria.
import net.rim.device.api.system.Bitmap;

Recupere una imagen existente de mapa de bits.


Bitmap testBitmap0 = Bitmap.getBitmapResource("rim.png");

Cree un rea de mapa de bits que contenga la versin escalada de la imagen de mapa de bits original.
Bitmap scaledBitmap1 = new Bitmap(200, 50);

Escale la imagen de mapa de bits original y almacnela en otra imagen de mapa de bits.
testBitmap0.scaleInto(scaledBitmap1, Bitmap.FILTER_BILINEAR);

Duplicar una imagen de mapa de bits


1. 2. 3. Importe la clase necesaria.
import net.rim.device.api.system.Bitmap;

Agregue la imagen de mapa de bits existente a una matriz de bytes.


byte[] data = getNamedResource("image.gif");

Cree una nueva imagen de mapa de bits que sea un duplicado exacto de la imagen existente.
Bitmap newBitmap = Bitmap.createBitmapFromBytes(data, 0, -1, 1);

Crear una imagen de mapa de bits que contenga parte del contenido de otra imagen de mapa de bits
1. 2. 3. Importe la clase necesaria.
import net.rim.device.api.system.Bitmap;

Cargue la imagen de mapa de bits existente en una matriz de bytes.


byte[] data = getNamedResource("image.gif");

Cree una nueva imagen de mapa de bits que sea un subconjunto de la imagen existente donde START_OFFSET constituya la compensacin inicial en la matriz de bytes y NUM_BYTES sea el nmero de bytes que se ha de escribir en la nueva imagen de mapa de bits.

71

Gua de desarrollo

Dibujar una imagen en una imagen de mapa de bits vaca

Bitmap newBitmap = Bitmap.createBitmapFromBytes(data, START_OFFSET, NUM_BYTES, 1);

Dibujar una imagen en una imagen de mapa de bits vaca


1. Importe las clases necesarias.
import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.component.BitmapField;

2.

Cree una imagen de mapa de bits vaca, copiando el tipo y el tamao de una imagen de mapa de bits existente.
Bitmap restored = new Bitmap(original.getType(), original.getWidth(), original.getHeight());

3. 4.

Cree un objeto Graphics y utilice la imagen de mapa de bits vaca como superficie de dibujo.
Graphics graphics = new Graphics(restored);

Invoque Graphics.rawRGB() para dibujar una imagen nueva utilizando datos sin procesar recuperados de la imagen original.
graphics.drawRGB(argb, 0, restored.getWidth(), 0, 0, restored.getWidth(), restored.getHeight());

Filtros de interpolacin
La interpolacin es necesaria para eliminar la apariencia en forma de bloques de una imagen de mapa de bits de nueva escala debido a los cambios en el nmero de pxeles. La interpolacin vuelve a probar los datos de la imagen de mapa de bits e intenta evitar una apariencia pixelada en forma de bloques. Puesto que el resultado visual de cada filtro puede parecer diferente cuando se aplica a varios tipos de imgenes, el usuario puede optar por elegir un filtro de interpolacin adecuado. Hay tres filtros disponibles para su uso con mtodos de escala de imgenes de mapa de bits. Filtro Bitmap.FILTER_LANCZ OS Bitmap.FILTER_BOX Bitmap.FILTER_BILINE AR Descripcin El filtro Lanczos es el ms lento de los filtros de interpolacin disponibles. La interpolacin de Lanczos puede dar lugar a imgenes definidas pero puede introducir artefactos de sonido. El filtro box, tambin conocido como filtro de valor medio, filtro de alisado y filtro de promedio, puede generar rpidamente imgenes borrosas. El filtro bilinear puede generar rpidamente buenos resultados para imgenes con tamao modificado, aunque puede mostrar lneas de transicin definidas. Este filtro a menudo se utiliza para representar vistas previas de la imagen de mapa de bits.

72

Gua de desarrollo

Visualizacin de imgenes

Visualizacin de imgenes
Visualizacin de una imagen acercndola, alejndola y desplazndola

La clase ZoomScreen le permite acercar, alejar y desplazar una imagen. Si el usuario del dispositivo BlackBerry hace clic en la bola de desplazamiento o en la pantalla tctil, la pantalla muestra la regin central de la imagen ampliada. Si la imagen se amplia, la pantalla tambin muestra una superposicin que resalta la regin sobre la que se ha aplicado el zoom. Al desplazar la rueda de desplazamiento o al deslizar el dedo por la pantalla se desplazar la imagen. Cuando el usuario deja de desplazar y de acercar o alejar la imagen, la superposicin desaparece de la pantalla. En dispositivos BlackBerry con pantalla tctil, los usuarios pueden definir la regin de la imagen a la que aplicar el zoom. El usuario puede tocar dos puntos en la imagen para definir las esquinas opuestas en diagonal de la regin. Cuando se selecciona la regin, el usuario puede deslizar un dedo alrededor de la imagen para mover la regin del zoom. Para ampliar la regin definida, el usuario hace clic en la pantalla. Para alejar la imagen, el usuario pulsa la tecla Escape.

Mostrar una imagen acercndola, alejndola y desplazndola


1. Importe las clases y las interfaces necesarias.
import import import import net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.extension.container.*;

2.

Cree el marco de la aplicacin ampliando la clase UiApplication. En main(), cree una instancia de la clase nueva e invoque enterEventDispatcher() para activar la aplicacin para que reciba eventos. En el constructor, cree un EncodedImage mediante un recurso del proyecto, cree un ZoomScreen con EncodedImage e invoque pushScreen () para mostrar la imagen con el fin de acercarla, alejarla y desplazarla.
public class ZoomableImageApp extends UiApplication { public static void main(String[] args) { ZoomableImageApp theApp = new ZoomableImageApp(); theApp.enterEventDispatcher(); } public ZoomableImageApp() { EncodedImage myImg = new EncodedImage(img/myImg.jpg); ZoomScreen zoomableImg = new ZoomScreen(myImg); pushScreen(zoomableImg); } }

73

Gua de desarrollo

Cdigo de ejemplo: visualizacin de una imagen acercndola, alejndola y desplazndola

Cdigo de ejemplo: visualizacin de una imagen acercndola, alejndola y desplazndola


import net.rim.device.api.system.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.extension.container.*; public class ZoomableImageApp extends UiApplication { public static void main(String[] args) { ZoomableImageApp theApp = new ZoomableImageApp(); theApp.enterEventDispatcher(); } public ZoomableImageApp() { EncodedImage myImg = new EncodedImage(img/myImg.jpg); ZoomScreen zoomableImg = new ZoomScreen(myImg); pushScreen(zoomableImg); } }

Visualizacin de una fila de imgenes para realizar desplazamientos


Puede utilizar la clase PictureScrollField para representar una fila horizontal de imgenes por las que el usuario se pueda desplazar mediante la rueda de desplazamiento o con toques sobre la pantalla.
PictureScrollField le permite definir el estilo para resaltar la imagen seleccionada, el estilo del fondo de PictureScrollField, el texto mostrado bajo la imagen seleccionada, el texto de la sugerencia que aparece cuando una

imagen se selecciona inicialmente y la altura y anchura de las imgenes.

Mostrar una fila de imgenes para realizar desplazamientos


1. Importe las clases y las interfaces necesarias.
import import import import import import net.rim.device.api.system.*; net.rim.device.api.ui.*; net.rim.device.api.ui.component.*; net.rim.device.api.ui.container.*; net.rim.device.api.ui.decor.*; net.rim.device.api.ui.extension.component.*;

74

Gua de desarrollo

Mostrar una fila de imgenes para realizar desplazamientos

2.

Cree el marco de la aplicacin ampliando la clase UiApplication. En main(), cree una instancia de la clase nueva e invoque enterEventDispatcher() para activar la aplicacin para que reciba eventos. En el constructor, invoque pushScreen() para mostrar la pantalla personalizada de la aplicacin. La clase PictureScrollFieldDemoScreen, descrita en el paso 3, representa la pantalla personalizada.
public class PictureScrollFieldDemo extends UiApplication { public static void main(String[] args) { PictureScrollFieldDemo app = new PictureScrollFieldDemo(); app.enterEventDispatcher(); } public PictureScrollFieldDemo() { pushScreen(new PictureScrollFieldDemoScreen()); } }

3.

Cree el marco para la pantalla personalizada ampliando la clase MainScreen.


class PictureScrollFieldDemoScreen extends MainScreen { { public PictureScrollFieldDemoScreen() { } }

4. 5.

En el constructor, invoque setTitle() para establecer el texto que aparece en la seccin del ttulo de la pantalla.
setTitle(PictureScrollField Demo);

En el constructor, cree e inicialice tres matrices para almacenar las imgenes para mostrar en PictureScrollField y las etiquetas y texto de las sugerencias que aparece cuando se selecciona cada una de las imgenes. En este ejemplo, PictureScrollField contiene tres imgenes.
Bitmap[] images = new Bitmap[3]; String[] labels = new String[3]; String[] tooltips = new String[3]; images[0] = Bitmap.getBitmapResource(img1.jpg); labels[0] = Label for image 1; tooltips[0] = Tooltip for image 1; images[1] = Bitmap.getBitmapResource(img2.jpg); labels[1] = Label for image 2; tooltips[1] = Tooltip for image 2; images[2] = Bitmap.getBitmapResource(img3.jpg); labels[2] = Label for image 3; tooltips[2] = Tooltip for image 3;

6.

En el constructor, cree e inicializa una matriz de objetos ScrollEntry. Un ScrollEntry representa cada elemento de PictureScrollField.

75

Gua de desarrollo

Cdigo de ejemplo: visualizacin de una fila de imgenes para realizar desplazamientos

ScrollEntry[] entries = ScrollEntry[3]; for (int i = 0; i < entries.length; i++) { entries[i] = new ScrollEntry(images[i], labels[i], tooltips[i]); }

7.

En el constructor, cree e inicializa PictureScrollField con cada imagen de 150 pxeles de ancho y 100 pxeles de alto. Invoque setData() para establecer las entradas en PictureScrollField. El segundo parmetro en setData () especifica qu posicin de imagen se selecciona de forma predeterminada.
PictureScrollField pictureScrollField = new PictureScrollField(150, 100); pictureScrollField.setData(entries, 0);

8.

En el constructor, configure el estilo de PictureScrollField. Invoque setHighlightStyle() para especificar cmo se resalta la imagen seleccionada. Invoque setHighlightBorderColor() para especificar el color del borde de la imagen seleccionada. Invoque setBackground() para especificar el fondo de PictureScrollField. Invoque setLabelVisible() para especificar si PictureScrollField muestra la etiqueta de la imagen seleccionada.
pictureScrollField.setHighlightStyle(HighlightStyle.ILLUMINATE); pictureScrollField.setHighlightBorderColor(Color.BLUE); pictureScrollField.setBackground(BackgroundFactory createSolidTransparentBackground(Color.RED, 150)); pictureScrollField.setLabelsVisible(true);

9.

En el constructor, invoque add() para mostrar PictureScrollField.


add(pictureScrollField);

Cdigo de ejemplo: visualizacin de una fila de imgenes para realizar desplazamientos


import net.rim.device.api.system.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.ui.decor.*; import net.rim.device.api.ui.extension.component.*; public class PictureScrollFieldDemo extends UiApplication { public static void main(String[] args) { PictureScrollFieldDemo app = new PictureScrollFieldDemo(); app.enterEventDispatcher(); } public PictureScrollFieldDemo() { pushScreen(new PictureScrollFieldDemoScreen());

76

Gua de desarrollo

Cdigo de ejemplo: visualizacin de una fila de imgenes para realizar desplazamientos

} } class PictureScrollFieldDemoScreen extends MainScreen { { public PictureScrollFieldDemoScreen() { setTitle(PictureScrollField Demo); Bitmap[] images = new Bitmap[3]; String[] labels = new String[3]; String[] tooltips = new String[3]; images[0] = Bitmap.getBitmapResource(img1.jpg); labels[0] = Label for image 1; tooltips[0] = Tooltip for image 1; images[1] = Bitmap.getBitmapResource(img2.jpg); labels[1] = Label for image 2; tooltips[1] = Tooltip for image 2; images[2] = Bitmap.getBitmapResource(img2.jpg); labels[2] = Label for image 2; tooltips[2] = Tooltip for image 2; ScrollEntry[] entries = ScrollEntry[3]; for (int i = 0; i < entries.length; i++) { entries[i] = new ScrollEntry(images[i], labels[i],tooltips[i]); } PictureScrollField pictureScrollField = new PictureScrollField(150, 100); pictureScrollField.setData(entries, 0); pictureScrollField.setHighlightStyle(HighlightStyle.ILLUMINATE); pictureScrollField.setHighlightBorderColor(Color.BLUE); pictureScrollField.setBackground (BackgroundFactory.createSolidTransparentBackground(Color.RED, 150)); pictureScrollField.setLabelsVisible(true); add(pictureScrollField); } }

77

Gua de desarrollo

Uso de imgenes sin procesar

Uso de imgenes sin procesar


Recuperar los datos de la imagen sin procesar
1. 2. Importe la clase necesaria.
import net.rim.device.api.system.Bitmap;

Invoque Bitmap.getARGB() para recuperar los datos de la imagen sin procesar de una regin de una imagen de mapa de bits y almacenar los datos en una matriz de enteros.
Bitmap original = Bitmap.getPredefinedBitmap(Bitmap.INFORMATION); int[] argb = new int[original.getWidth() * original.getHeight()];

Almacenar datos sin procesar de la imagen


1. 2. 3. 4. Importe la clase necesaria.
import net.rim.device.api.system.Bitmap;

Cree un objeto de Mapa de bits a partir de una imagen de mapa de bits existente.
Bitmap img = Bitmap.getPredefinedBitmap(Bitmap.INFORMATION);

Inicialice una matriz de enteros.


int[] argb = new int[img.getWidth() * img.getHeight()];

Invoque Bitmap.getARGB() para almacenar los datos de imagen sin procesar desde un mapa de bits nuevo o predefinido en una matriz de enteros.
img.getARGB(argb, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());

Comparar dos imgenes sin procesar


1. 2. Importe la clase necesaria.
import net.rim.device.api.system.Bitmap;

Invoque Bitmap.equals().

78

Gua de desarrollo

Comparar dos imgenes de mapa de bits para comprobar si son diferentes

if(restored.equals(original)) { System.out.println("Success! Bitmap renders correctly with RGB data."); } else (!restored.equals(original)) { System.out.println("Bitmap rendered incorrectly with RGB data."); }

Comparar dos imgenes de mapa de bits para comprobar si son diferentes


1. 2. Importe la clase necesaria.
import net.rim.device.api.system.Bitmap;

Cree dos objetos Bitmap de las imgenes de mapa de bits para la comparacin.
Bitmap _first = Bitmap.getBitmapResource("first.png"); Bitmap _last = Bitmap.getBitmapResource("last.png");

3. 4.

Cree un objeto XYRect para reflejar las diferencias entre las imgenes de bits.
XYRect diff = new XYRect(0, 0, _first.getWidth(), _first.getHeight());

Compare las imgenes de mapa de bits a travs del mtodo Bitmap.locateDifference(XYRect diffRect, Bitmap bmp2, int offset_x, int offset_y). Esta comparacin se realiza en la referencia XYRect proporcionada y se puede desplazar dentro de la segunda imagen de mapa de bits a una posicin alternativa. La diferencia mnima entre las imgenes de mapa de bits en el rea definida se determina, con la referencia XYRect modificada con las nuevas coordenadas que representan este rea. Un XYRect vaco no representa una diferencia entre los dos mapas de bits dentro del rea determinada.
_first.locateDifference( diff, _last, 0, 0 );

79

Gua de desarrollo

Uso de imgenes cifradas

Uso de imgenes cifradas


Acceder a una imagen cifrada a travs de un flujo de entrada
1. 2. 3. 4. Importe las clases necesarias.
import java.io.InputStream;

Guarde la imagen en la carpeta o subcarpeta del proyecto. Agregue la imagen al proyecto en BlackBerry Integrated Development Environment. Invoque getClass().getResourceAsStream() para recuperar la imagen como un flujo de entrada de bytes.
private InputStream input; ... Class _class = this.getClass(); input = _class.getResourceAsStream("/images/example.png");

Cifrar una imagen


1. 2. 3. Importe las clases necesarias.
import net.rim.device.api.system.EncodedImage;

Invoque EncodedImage.createEncodedImage(). Este mtodo utiliza los datos de imagen sin procesar en la matriz de bytes para crear una instancia de EncodedImage. Busque el IllegalArgumentException que EncodedImage.createEncodedImage() arroja si la matriz de bytes que ha proporcionado como parmetro no contiene un formato de imagen reconocido.
// Store the contents of the image file. private byte[] data = new byte[2430]; try { // Read the image data into the byte array input.read(data); } catch (IOException e) { // Handle exception. } try { EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length); } catch (IllegalArgumentException iae) { System.out.println("Image format not recognized."); }

80

Gua de desarrollo

Mostrar una imagen cifrada

Mostrar una imagen cifrada


1. 2. 3. Importe la clase necesaria.
import net.rim.device.api.ui.component.BitmapField;

Invoque BitmapField.setImage() para asignar la imagen cifrada a un BitmapField. Invoque add() para agregar BitmapField a la pantalla.
BitmapField field = new BitmapField(); field.setImage(image); add(field);

Especificar el modo de descodificacin de una imagen


1. 2. Importe la clase necesaria.
import net.rim.device.api.system.EncodedImage;

Invoque EncodedImage.setDecodeMode() utilizando uno de los siguientes modos como parmetro: Utilice DECODE_ALPHA para descodificar un canal alfa, si existe (ste es el modo predeterminado). Utilice DECODE_NATIVE para forzar la descodificacin de la imagen del mapa de bits segn el tipo de imagen nativa de mapa de bits de BlackBerry Device Software. Utilice DECODE_READONLY para marcar la imagen de mapa de bits descodificada como de slo lectura.

Especificar el tamao de la pantalla de una imagen cifrada


1. 2. Importe la clase necesaria.
import net.rim.device.api.system.EncodedImage;

Invoque EncodedImage.scaleImage32(int scaleX, int scaleY). Los parmetros del valor de escala pasados deben ser los nmeros net.rim.device.api.math.Fixed32 (0 < escala < 1 para escala ascendente y escala > 1 para escala descendente). ScaleImage32() crea un nuevo EncodedImage en lugar de modificar el actual.

81

Gua de desarrollo

Uso de contenido SVG en una aplicacin del dispositivo BlackBerry

Uso de contenido SVG en una aplicacin del dispositivo BlackBerry

El dispositivo BlackBerry es compatible con una representacin binaria de contenido SVG (Grficos vectoriales escalables) en un formato de archivo .pme. Puede utilizar BlackBerry Composer para crear un archivo .pme o utilizar Plazmic SVG Transcoding Utility para convertir un archivo .svg en un archivo .pme. BlackBerry Composer y Plazmic SVG Transcoding Utility forman parte de BlackBerry Theme Studio.

Descargar contenido SVG


1. 2. 3. Importe la clase necesaria.
import net.rim.plazmic.mediaengine.MediaManager;

Cree un objeto MediaManager.


MediaManager manager = new MediaManager();

Invoque MediaManager.createMedia(). La primera vez que invoque MediaManager.createMedia(), la URL debe ser absoluta, a menos que invoque en primer lugar MediaManager.setProperty("URI_BASE", <base_url>) para establecer una URL base. Al invocar posteriormente createMedia (), la URL anterior se utiliza como base.
try { Object media = manager.createMedia("http://webserver/sample.pme"); } catch (IOException ioe) { System.out.println("Error: requested content was not downloaded."); } catch (MediaException me) { System.out.println("Error: " + me.getCode()); }

Reproducir contenido multimedia enriquecido


1. Importe las clases necesarias.
import net.rim.plazmic.mediaengine.MediaPlayer; import net.rim.plazmic.mediaengine.MediaManager;

2.

Cree una clase que extienda MainScreen y un constructor.


final static class MediaSampleScreen extends MainScreen { public MediaSampleScreen() { super();

82

Gua de desarrollo

Escuchar eventos al descargar un archivo .pme

LabelField title = new LabelField("Media Sample", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH); setTitle(title);

3. 4. 5. 6. 7.

Cree un objeto MediaPlayer para gestionar la reproduccin de tipos multimedia compatibles con Media Engine.
MediaPlayer player = new MediaPlayer();

Cree un objeto MediaManager para gestionar la descarga de contenido multimedia de Internet o del almacn local.
MediaManager manager = new MediaManager();

Invoque MediaManager.createMedia(String) para recuperar contenido multimedia de un URI determinado.


Object media = manager.createMedia("http://webserver/SVGFILE.pme");

Invoque MediaPlayer.setMedia() para especificar los archivos multimedia para la reproduccin.


player.setMedia(media);

Invoque MediaPlayer.getUI() para recuperar un objeto UI que muestre contenido PME. Asigne el objeto resultante como un Field y, a continuacin, agrguelo a Screen para su visualizacin.
add((Field)player.getUI());

8.

Invoque MediaPlayer.start() para iniciar la reproduccin del contenido PME descargado.


player.start();

Despus de terminar: Debe crear una pantalla que no sea compatible con el desplazamiento para mostrar contenido SVG desde Plazmic Media Engine versin 4.2.

Escuchar eventos al descargar un archivo .pme


1. Importe las clases e interfaces necesarias.
import net.rim.plazmic.mediaengine.MediaManager; import net.rim.plazmic.mediaengine.MediaListener;

2.

Implemente la interfaz net.rim.plazmic.mediaengine.MediaListener para gestionar todos los posibles eventos multimedia.
public final class MediaListenerImpl implements MediaListener { public void mediaEvent(Object sender, int event, int eventParam, Object data) { switch(event) { case MEDIA_REQUESTED: break; case MEDIA_COMPLETE: break; case MEDIA_REALIZED: break; case MEDIA_IO:

83

Gua de desarrollo

Responder a eventos al descargar un archivo .pme

break;

3.

Invoque addMediaListener() en los objetos MediaPlayer y MediaManager para registrar el oyente de los eventos multimedia.
private MediaListenerImpl _listener = new MediaListenerImpl(); private MediaPlayer player = new MediaPlayer(); private MediaManager manager = new MediaManager(); player.addMediaListener(_listener); manager.addMediaListener(_listener);

Responder a eventos al descargar un archivo .pme


1. Importe las clases e interfaces necesarias.
import net.rim.plazmic.mediaengine.io.LoadingStatus; import net.rim.plazmic.mediaengine.MediaListener;

2. 3.

Implemente la interfaz net.rim.plazmic.mediaengine.MediaListener.


public final class MediaListenerImpl implements MediaListener {

En su implementacin de MediaListener.mediaEvent(), cuando tenga lugar el evento MEDIA_IO, asigne Object en el parmetro de datos al objeto LoadingStatus.
LoadingStatus s = (LoadingStatus)data;

4.

Invoque LoadingStatus.getStatus() para descargar contenido y gestionar el estado del archivo .pme que descarga la aplicacin.
switch(s.getStatus()) {

5.

Para cada estado normal, imprima un mensaje en la consola.


case LoadingStatus.LOADING_STARTED: System.out.println("Loading in progress"); break; case LoadingStatus.LOADING_READING: System.out.println("Parsing in progress"); break; case LoadingStatus.LOADING_FINISHED: System.out.println("Loading completed"); break;

6.

Si LoadingStatus.getStatus() devuelve un valor igual a LoadingStatus.LOADING_FAILED, lleve a cabo una o ms de las acciones siguientes: Para recuperar el cdigo de error, invoque LoadingStatus.getCode(). Para recuperar el mensaje detallado, invoque LoadingStatus.getMessage().

84

Gua de desarrollo

Cdigo de ejemplo: respuesta a eventos cuando una aplicacin de dispositivo BlackBerry descarga contenido SVG

Para recuperar la cadena de URL del contenido, invoque LoadingStatus.getSource().


case LoadingStatus.LOADING_FAILED: String errorName = null; int code = s.getCode(); switch (code) { case MediaException.INVALID_HEADER: errorName = "Invalid header"+ "/n" + s.getSource(); break; case MediaException.REQUEST_TIMED_OUT: errorName = "Request timed out" + "\n" + s.getSource(); break; case MediaException.INTERRUPTED_DOWNLOAD: break; case MediaException.UNSUPPORTED_TYPE: errorName = "Unsupported type" + s.getMessage() + "\n" + s.getSource(); break; default: { if (code > 200) { // A code > 200 indicates an HTTP error. errorName = "URL not found"; } else { // Default unidentified error. errorName = "Loading Failed"; } errorName += "\n" + s.getSource() + "\n" + s.getCode() + ": " + s.getMessage(); break; } } System.out.println(errorName); break;

Cdigo de ejemplo: respuesta a eventos cuando una aplicacin de dispositivo BlackBerry descarga contenido SVG
package com.rim.samples.device.mediaenginedemo; import net.rim.plazmic.mediaengine.*; import net.rim.plazmic.mediaengine.io.*; /** * The MediaListener implementation. */ public final class MediaListenerImpl implements MediaListener { public void mediaEvent(Object sender, int event, int eventParam, Object data) { switch(event)

85

Gua de desarrollo

Cdigo de ejemplo: respuesta a eventos cuando una aplicacin de dispositivo BlackBerry descarga contenido SVG

case MEDIA_REQUESTED: System.out.println("Media requested"); break; case MEDIA_COMPLETE: System.out.println("Media completed"); break; case MEDIA_REALIZED: System.out.println("Media realized"); break; case MEDIA_IO: { LoadingStatus s = (LoadingStatus)data; switch(s.getStatus()) { case LoadingStatus.LOADING_STARTED: System.out.println("Loading in progress"); break; case LoadingStatus.LOADING_READING: System.out.println("Parsing in progress"); break; case LoadingStatus.LOADING_FINISHED: System.out.println("Loading completed"); break; case LoadingStatus.LOADING_FAILED: String errorName = null; int code = s.getCode(); switch (code) { case MediaException.INVALID_HEADER: errorName = "nvalid header"+ "/n" + s.getSource(); break; case MediaException.REQUEST_TIMED_OUT: errorName = "Request timed out" + "\n" + s.getSource(); break; case MediaException.INTERRUPTED_DOWNLOAD: break; case MediaException.UNSUPPORTED_TYPE: errorName = "Unsupported type" + s.getMessage() + "\n" + s.getSource(); break; default: { if (code > 200) { // A code > 200 indicates an HTTP error. errorName = "URL not found"; } else { // Default unidentified error.

86

Gua de desarrollo

Descargar y reproducir un archivo .pme

errorName = "Loading Failed"; errorName += "\n" + s.getSource() + "\n" + s.getCode() + ": " + s.getMessage(); break;

} } System.out.println(errorName); break; } // End switch s.getStatus(). break;

Descargar y reproducir un archivo .pme


1. Importe las clases e interfaz necesarias.
import net.rim.plazmic.mediaengine.MediaPlayer; import net.rim.plazmic.mediaengine.MediaManager; import net.rim.plazmic.mediaengine.MediaListener;

2. 3.

Implemente la interfaz net.rim.plazmic.mediaengine.MediaListener.


public final class MediaListenerImpl implements MediaListener {

Cree un objeto MediaManager y, a continuacin, invoque MediaManager.createMediaLater().


MediaManager manager = new MediaManager(); manager.createMediaLater("http://webserver/sample.pme");

4.

En el mtodo MediaListener.mediaEvent(), agregue cdigo para administrar el evento MEDIA_REALIZED que ocurre cuando la aplicacin termina de cargar un archivo .pme en el archivo BlackBerry.
public void mediaEvent(Object sender, int event, int eventParam, Object data) { switch(event) { ... case MEDIA_REALIZED:

5. 6.

Invoque MediaPlayer.setMedia(data) para registrar el contenido.


player.setMedia(data);

Invoque MediaPlayer.start() para iniciar la reproduccin del contenido.


player.start();

87

Gua de desarrollo

Reproducir contenido SVG

Reproducir contenido SVG


1. Importe las clases necesarias.
import net.rim.device.api.ui.Screen; import net.rim.plazmic.mediaengine.MediaPlayer; import net.rim.plazmic.mediaengine.MediaException;

2. 3.

Cree un objeto MediaPlayer para gestionar la reproduccin de tipos multimedia compatibles con Media Engine.
MediaPlayer player = new MediaPlayer();

Invoque MediaPlayer.setMedia() para preparar MediaPlayer para reproducir archivos multimedia.


try { player.setMedia(media); } catch (MediaException me) { System.out.println("Error: requested content type is not supported.); }

4.

Cree una instancia de un objeto de pantalla utilizando para ello los campos NO_VERTICAL_SCROLL y NO_HORIZONTAL_SCROLL para permitir a una pantalla mostrar un archivo .pme creado por Plazmic Media Engine versin 4.2.
Screen screen = new Screen(Screen.NO_VERTICAL_SCROLL | Screen.NO_HORIZONTAL_SCROLL);

5. 6.

Invoque MediaPlayer.getUI(), asigne el objeto devuelto a un tipo Field y agrguelo a Screen para mostrarlo.
screen.add((Field)player.getUI());

Si el objeto Player se encuentra en el estado REALIZED, invoque MediaPlayer.start() para iniciar la reproduccin del archivo .pme.
if(player.getState() == MediaPlayer.REALIZED) { try { player.start(); } catch(MediaException me) { System.out.println("Error occurred during media playback: " + me.getCode() + me.getMessage()); } }

88

Gua de desarrollo

Acceder a contenido SVG a travs de una conexin con la que no es compatible MediaManager

Acceder a contenido SVG a travs de una conexin con la que no es compatible MediaManager
Puede crear una aplicacin de dispositivo BlackBerry que pueda descargar contenido SVG de Internet o del almacn local a travs de una conexin que sea compatible con un protocolo personalizado o que tenga una funcionalidad con la que MediaManager no es compatible o que MediaManager no proporciona. 1. Importe las clases necesarias.
import java.io.*; import net.rim.plazmic.mediaengine.*; import net.rim.plazmic.mediaengine.io.*;

2.

Para implementar un conector personalizado, implemente la interfaz net.rim.plazmic.mediaengine.io.Connector.


public class CustomPMEConnector implements Connector { private Connector delegate; private InputStream input; CustomPMEConnector(Connector delegate) { this.delegate = delegate; } public InputStream getInputStream(String uri, ConnectionInfo info) throws IOException, MediaException { if (uri.startsWith("myprotocol://")) { // Perform special tasks. info.setConnection(new MyProtocolConnection()); info.setContentType("application/x-vnd.rim.pme"); // OpenMyInputStream() is a custom method that opens //stream for "myprotocol://" input = openMyInputStream(uri); } else { input = delegate.getInputStream(uri, info); } return input; } private InputStream openMyInputStream(String uri) { InputStream input = null; // @todo: open stream here return input; } // Inner class that defines the connection class. public static class MyProtocolConnection { public MyProtocolConnection() { // ... } public void close() {

89

Gua de desarrollo

Cdigo de ejemplo: implementacin de un marco de conector personalizado.

// ...

3.

Para configurar las propiedades del conector personalizado, implemente setProperty(String, String).
public void setProperty(String property, String value) { delegate.setProperty(property, value); }

4.

Para iniciar la conexin personalizada, implemente releaseConnection(ConnectionInfo).


public void releaseConnection(ConnectionInfo info) throws IOException, MediaException { Object o = info.getConnection(); if (o instanceof MyProtocolConnection) { ((MyProtocolConnection)o).close(); // Perform cleanup. } else { delegate.releaseConnection(info); } }

Cdigo de ejemplo: implementacin de un marco de conector personalizado.


/* * CustomPMEConnector.java * Copyright (C) 2003-2007 Research In Motion Limited. All rights reserved. */ package com.rim.samples.docs.mediasample; import java.io.*; import net.rim.plazmic.mediaengine.*; import net.rim.plazmic.mediaengine.io.*; public class CustomPMEConnector implements Connector { private Connector delegate; private InputStream input; CustomPMEConnector(Connector delegate) { this.delegate = delegate; } public InputStream getInputStream(String uri, ConnectionInfo info) throws IOException, MediaException { if (uri.startsWith("myprotocol://")) { // Perform special tasks. info.setConnection(new MyProtocolConnection()); info.setContentType("application/x-vnd.rim.pme"); // OpenMyInputStream() is a custom method that opens //stream for "myprotocol://" input = openMyInputStream(uri); } else { input = delegate.getInputStream(uri, info); } return input;

90

Gua de desarrollo

Cdigo de ejemplo: implementacin de un marco de conector personalizado.

} private InputStream openMyInputStream(String uri) { InputStream input = null; // @todo: open stream here return input; } public void releaseConnection(ConnectionInfo info) throws IOException, MediaException { Object o = info.getConnection(); if (o instanceof MyProtocolConnection) { ((MyProtocolConnection)o).close(); // Perform cleanup. } else { delegate.releaseConnection(info); } } public void setProperty(String property, String value) { delegate.setProperty(property, value); } // Inner class that defines the connection class. public static class MyProtocolConnection { public MyProtocolConnection() { // ... } public void close() { // ... } }

91

Gua de desarrollo

Creacin de grficos 2D y 3D con JSR-239

Creacin de grficos 2D y 3D con JSR-239

Puede crear grficos 2D y 3D para un dispositivo BlackBerry utilizando JSR-239 y las API de BlackBerry. JSR-239 incluye Java Binding para OpenGL ES. OpenGL ES se basa en la versin de escritorio de OpenGL, pero se ha diseado para su uso en dispositivos inalmbricos. Para obtener ms informacin acerca de OpenGL, visite www.khronos.org/opengles/.

Paquetes para la compatibilidad con JSR-239


Paquete
javax.microedition.khronos.opengles

Descripcin Este paquete ofrece un subconjunto de API de OpenGL y los enlaces para OpenGL ES 1.0, 1.1 y sus extensiones. Incluye los mtodos para la manipulacin de punto fijo y flotante de los valores. Este paquete proporciona los enlaces para EGL 1.0 y 1.1 para la API de OpenGL ES. Los contextos de representacin compatibles pueden proporcionar un contenedor para el estado de representacin de OpenGL ES. El paquete se ha diseado para ser compatible con las superficies de representacin de Windows, Pbuffer y Pixmap. La clase GLUtils en este paquete proporciona compatibilidad con las siguientes acciones: comprobar que el dispositivo BlackBerry es compatible con OpenGL ES cargar una matriz de proyeccin de perspectiva en 3D cargar una matriz de transformacin de vista definir una matriz de proyeccin ortogrfica en 2D cargar una textura desde una imagen Bitmap liberar la memoria asignada actualmente al bfer directo

javax.microedition.khronos.egl

net.rim.device.api.opengles

java.nio net.rim.device.api.math

Este paquete proporciona las clases que activan su aplicacin para la lectura y escritura en la entrada/salida bloqueante de alta velocidad. Este paquete proporciona las clases diseadas para ayudarle a mejorar la versatilidad aritmtica y la velocidad de procesamiento de las aplicaciones del dispositivo BlackBerry que ha creado.

92

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores


El siguiente cdigo de ejemplo muestra cmo utilizar JSR-239 para representar un tringulo 2D en varios colores.
import java.nio.*; import javax.microedition.khronos.egl.*; import javax.microedition.khronos.opengles.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.system.*; import net.rim.device.api.opengles.*; public final class OpenGLTest extends UiApplication { public OpenGLTest() { pushScreen(new OpenGLTestScreen()); } public static void main(String[] args) { new OpenGLTest().enterEventDispatcher(); } } class OpenGLTestScreen extends FullScreen implements Runnable { private EGL11 _egl; private EGLDisplay _eglDisplay; private EGLConfig _eglConfig; private EGLSurface _eglSurface; private EGLContext _eglContext; private GL10 _gl; private Bitmap _offscreenBitmap; private Graphics _offscreenGraphics; private FloatBuffer _vertexArray; private FloatBuffer _colorArray; private boolean _running; private boolean _paused; OpenGLTestScreen() { super(FullScreen.DEFAULT_MENU | FullScreen.DEFAULT_CLOSE); } private void initialize() { // Get EGL interface _egl = (EGL11)EGLContext.getEGL(); // Get the EGL display _eglDisplay = _egl.eglGetDisplay(EGL11.EGL_DEFAULT_DISPLAY); // Initialize the display for EGL setting the version to null _egl.eglInitialize(_eglDisplay, null);

93

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

} private void createEGLContext() { // Create an EGL context _eglContext = _egl.eglCreateContext (_eglDisplay, _eglConfig, EGL10.EGL_NO_CONTEXT, null); // Get the GL interface for the new context _gl = (GL10)_eglContext.getGL(); // Make the new context current _egl.eglMakeCurrent (_eglDisplay, _eglSurface, _eglSurface, _eglContext); } private void destroyEGL() { _egl.eglMakeCurrent(_eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);

// Choose an EGL config EGLConfig[] configs = new EGLConfig[1]; int[] numConfigs = new int[1]; int[] attrs = { EGL11.EGL_RED_SIZE, 5, EGL11.EGL_GREEN_SIZE, 6, EGL11.EGL_BLUE_SIZE, 5, EGL11.EGL_NONE }; _egl.eglChooseConfig(_eglDisplay, attrs, configs, 1, numConfigs); _eglConfig = configs[0]; // Create an EGL window surface _eglSurface = _egl.eglCreateWindowSurface (_eglDisplay, _eglConfig, this, null); // Create an EGL context createEGLContext(); // Specify vertices and colors for a triangle float[] vertices = { -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f }; float[] colors = { 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f }; _vertexArray = ByteBuffer.allocateDirect(3 * 3 * 4).asFloatBuffer(); _vertexArray.put(vertices); _vertexArray.rewind(); _colorArray = ByteBuffer.allocateDirect(4 * 3 * 4).asFloatBuffer(); _colorArray.put(colors); _colorArray.rewind();

94

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

} private void handleContextLost() { // Destroy the EGL context _egl.eglMakeCurrent(_eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); _egl.eglDestroyContext(_eglDisplay, _eglContext); _eglContext = EGL10.EGL_NO_CONTEXT; // Re-create the EGL context createEGLContext(); } /** * Main render loop. */ public void run() { initialize(); while (_running) { // Idle if this thread is in the background if (_paused) { synchronized (this) { try { wait(); } catch (InterruptedException x) { } } } updateBackBuffer(); renderFrame(); // Throttle cpu usage try { Thread.sleep(20); } catch (InterruptedException x) { } } destroyEGL(); } private void renderFrame() { // Make the context and surface current and check for EGL_CONTEXT_LOST if (!_egl.eglMakeCurrent(_eglDisplay, _eglSurface, _eglSurface, _eglContext)) { if (_egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) handleContextLost(); }

_egl.eglDestroyContext(_eglDisplay, _eglContext); _egl.eglDestroySurface(_eglDisplay, _eglSurface);

95

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

} private void render(GL10 gl) { // Set the GL viewport gl.glViewport(0, 0, getWidth(), getHeight()); // Clear the surface gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // Set the projection matrix gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); GLUtils.gluPerspective (gl, 45.0f, (float)getWidth()/(float)getHeight(), 0.15f, 10.0f); // Draw the triangle gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(0.0f, 0.0f, -3.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, _vertexArray); gl.glColorPointer(4, GL10.GL_FLOAT, 0, _colorArray); gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3); } /** * Called by the UI system to paint the screen. */ protected void paint(Graphics g) { if (_offscreenBitmap != null) g.drawBitmap(0, 0, _offscreenBitmap.getWidth(), _offscreenBitmap.getHeight(), _offscreenBitmap, 0, 0); } /** * Called when the visibility of the screen changes. * * @param visible true if the screen is being made visible, * false if hidden */ protected void onVisibilityChange(boolean visible) { if (visible) { resume(); } else

// Signal that OpenGL rendering is about to begin _egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, _offscreenGraphics); render(_gl); // Signal that OpenGL ES rendering is complete _egl.eglWaitGL(); // Swap the window surface to the display _egl.eglSwapBuffers(_eglDisplay, _eglSurface);

96

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

{ }

pause();

} /** * Called when the screen is closing. */ public void close() { _running = false; synchronized (this) { notifyAll(); } super.close(); } /** * Keeps the back buffer in sync with the screen size. */ private void updateBackBuffer() { if (_offscreenBitmap != null) { if (_offscreenBitmap.getWidth() == getWidth() && _offscreenBitmap.getHeight() == getHeight()) return; // no change needed } _offscreenBitmap = new Bitmap(getWidth(), getHeight()); _offscreenGraphics = Graphics.create(_offscreenBitmap); } private void pause() { _paused = true; } private void resume() { if (_running) { // Pause the render loop _paused = false; synchronized (this) { notifyAll(); } } else { // Start the render thread. _running = true; new Thread(this).start(); } }

97

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

Cdigo de ejemplo: dibujo de un cubo en 3D


Puede utilizar la interfaz GL10 para dibujar un cubo en 3D.
import java.nio.ByteBuffer; import java.nio.FloatBuffer; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL10; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.container.FullScreen; class ThreeDCube extends FullScreen implements Runnable { private EGL11 _egl; private EGLDisplay _eglDisplay; private EGLConfig _eglConfig; private EGLSurface _eglSurface; private EGLContext _eglContext; private GL10 _gl; private Bitmap _offscreenBitmap; private Graphics _offscreenGraphics; private boolean _running; private boolean _paused; private FloatBuffer _cubeVertices, _cubeNormals, _cubeColors; float _angle = 45f; private int _vertexCount; private static final float[] _vertices = { // front -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, // right 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, // back 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, // left -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, // top -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, // bottom

98

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

}; private static final float[] _normals = { /* front */ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, /* right */ 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, /* back */ 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, /* left */ -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, /* top */ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, /* bottom */ 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0 }; private static final float[] _colors = { /* front white */ 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, /* right red */ 1,0,0,1, 1,0,0,1, 1,0,0,1, 1,0,0,1, 1,0,0,1, 1,0,0,1, /* back green */ 0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1, /* left blue */ 0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1, /* top - yellow */ 1,1,0,1, 1,1,0,1, 1,1,0,1, 1,1,0,1, 1,1,0,1, 1,1,0,1, /* bottom - magenta*/ 1,0,1,1, 1,0,1,1, 1,0,1,1, 1,0,1,1, 1,0,1,1, 1,0,1,1 }; ThreeDCube() { super(FullScreen.DEFAULT_MENU | FullScreen.DEFAULT_CLOSE); } private void initialize() { // Get EGL interface _egl = (EGL11)EGLContext.getEGL(); // Get the EGL display _eglDisplay = _egl.eglGetDisplay(EGL11.EGL_DEFAULT_DISPLAY); // Initialize the display for EGL, null since we don't really need the // version. _egl.eglInitialize(_eglDisplay, null); // Choose an EGL config EGLConfig[] configs = new EGLConfig[1]; int[] numConfigs = new int[1]; int[] attrs = { EGL11.EGL_RED_SIZE, 5, EGL11.EGL_GREEN_SIZE, 6, EGL11.EGL_BLUE_SIZE, 5, EGL11.EGL_NONE }; _egl.eglChooseConfig(_eglDisplay, attrs, configs, 1, numConfigs); _eglConfig = configs[0]; // Create an EGL window surface _eglSurface = _egl.eglCreateWindowSurface

-0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f

99

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

} private FloatBuffer createVertexBuffer() { FloatBuffer buffer = ByteBuffer.allocateDirect(_vertices.length * 4).asFloatBuffer(); buffer.put(_vertices); buffer.rewind(); return buffer; } private FloatBuffer createNormalBuffer() { FloatBuffer buffer = ByteBuffer.allocateDirect(_normals.length * 4).asFloatBuffer(); buffer.put(_normals); buffer.rewind(); return buffer; } private FloatBuffer createColorBuffer() { FloatBuffer buffer = ByteBuffer.allocateDirect(_colors.length * 4).asFloatBuffer(); buffer.put(_colors); buffer.rewind(); return buffer; } private void createEGLContext() { // Create an EGL context _eglContext = _egl.eglCreateContext (_eglDisplay, _eglConfig, EGL10.EGL_NO_CONTEXT, null); // Get the GL interface for our new context _gl = (GL10)_eglContext.getGL(); // Make our new context current _egl.eglMakeCurrent (_eglDisplay, _eglSurface, _eglSurface, _eglContext); } private void destroyEGL() { _egl.eglMakeCurrent(_eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); _egl.eglDestroyContext(_eglDisplay, _eglContext); _egl.eglDestroySurface(_eglDisplay, _eglSurface); } private void handleContextLost() {

(_eglDisplay, _eglConfig, this, null); // Create an EGL context createEGLContext(); _cubeVertices = createVertexBuffer(); _cubeNormals = createNormalBuffer(); _cubeColors = createColorBuffer(); _vertexCount = _vertices.length / 3;

100

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

} /** * Main render loop. */ public void run() { initialize(); int throttle = 0; while (_running) { throttle = (int)System.currentTimeMillis(); // Idle If we are in the background if (_paused) { synchronized (this) { try { wait(); } catch (InterruptedException x) { } } } updateBackBuffer(); renderFrame(); ++_angle; if (_angle >= 360f) { _angle = 0f; } //Determine how long the frame took to render. throttle = (int)System.currentTimeMillis() - throttle; //Throttle to 30 FPS to control CPU usage. throttle = 33 - throttle; if (throttle > 0) { // Throttle cpu usage try { Thread.sleep(throttle); } catch (InterruptedException x) { } } } destroyEGL();

// Destroy our EGL context _egl.eglMakeCurrent(_eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); _egl.eglDestroyContext(_eglDisplay, _eglContext); _eglContext = EGL10.EGL_NO_CONTEXT; // Re-create our EGL context createEGLContext();

101

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

} private void renderFrame() { // Make our context and surface current and check for EGL_CONTEXT_LOST if (!_egl.eglMakeCurrent(_eglDisplay, _eglSurface, _eglSurface, _eglContext)) { if (_egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) handleContextLost(); } // Signal that we are about to begin OpenGL rendering _egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, _offscreenGraphics); render(_gl); // Signal that OpenGL ES rendering is complete _egl.eglWaitGL(); // Swap the window surface to the display _egl.eglSwapBuffers(_eglDisplay, _eglSurface); } private void render(GL10 gl) { // Set our GL viewport gl.glViewport(0, 0, getWidth(), getHeight()); // Clear the surface gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); net.rim.device.api.opengles.GLUtils.gluPerspective(gl, 45.0f, (float)getWidth()/(float)getHeight(), 0.15f, 100.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); // Setup drawing state gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_LIGHTING); gl.glEnable(GL10.GL_LIGHT0); gl.glEnable(GL10.GL_COLOR_MATERIAL); // Draw our cube gl.glTranslatef(0, 0, -3.5f); gl.glRotatef(_angle, 1.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, _cubeVertices); gl.glNormalPointer(GL10.GL_FLOAT, 0, _cubeNormals); gl.glColorPointer(4, GL10.GL_FLOAT, 0, _cubeColors); gl.glDrawArrays(GL10.GL_TRIANGLES, 0, _vertexCount); } /** * Called by the UI system to paint the screen. */ protected void paint(Graphics g) { if (_offscreenBitmap != null)

102

Gua de desarrollo

Cdigo de ejemplo: representacin de un tringulo 2D en varios colores

} /** * Called when the visibility of our screen changes. * * @param visible true if our screen is being made visible, * false if it's being hidden */ protected void onVisibilityChange(boolean visible) { if (visible) { resume(); } else { pause(); } } /** * Called when the screen is closing. */ public void close() { _running = false; synchronized (this) { notifyAll(); } super.close(); } /** * Keeps the back buffer in sync with the screen size. */ private void updateBackBuffer() { if (_offscreenBitmap != null) { if (_offscreenBitmap.getWidth() == getWidth() && _offscreenBitmap.getHeight() == getHeight()) return; // no change needed } _offscreenBitmap = new Bitmap(getWidth(), getHeight()); _offscreenGraphics = Graphics.create(_offscreenBitmap); } private void pause() { _paused = true; } private void resume() { if (_running) { // Pause the render loop

g.drawBitmap(0, 0, _offscreenBitmap.getWidth(), _offscreenBitmap.getHeight(), _offscreenBitmap, 0, 0);

103

Gua de desarrollo

Cdigo de ejemplo: dibujo de un cubo en 3D

} else {

_paused = false; synchronized (this) { notifyAll(); }

// Start the render thread. _running = true; new Thread(this).start();

Cdigo de ejemplo: dibujo de un cubo en 3D


Puede utilizar la interfaz GL10 para dibujar un cubo en 3D.
import java.nio.ByteBuffer; import java.nio.FloatBuffer; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL10; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.container.FullScreen; class ThreeDCube extends FullScreen implements Runnable { private EGL11 _egl; private EGLDisplay _eglDisplay; private EGLConfig _eglConfig; private EGLSurface _eglSurface; private EGLContext _eglContext; private GL10 _gl; private Bitmap _offscreenBitmap; private Graphics _offscreenGraphics; private boolean _running; private boolean _paused; private FloatBuffer _cubeVertices, _cubeNormals, _cubeColors; float _angle = 45f; private int _vertexCount; private static final float[] _vertices = { // front -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f,

104

Gua de desarrollo

Cdigo de ejemplo: dibujo de un cubo en 3D

}; private static final float[] _normals = { /* front */ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, /* right */ 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, /* back */ 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, /* left */ -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, /* top */ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, /* bottom */ 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0 }; private static final float[] _colors = { /* front white */ 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, /* right red */ 1,0,0,1, 1,0,0,1, 1,0,0,1, 1,0,0,1, 1,0,0,1, 1,0,0,1, /* back green */ 0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1, /* left blue */ 0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1, /* top - yellow */ 1,1,0,1, 1,1,0,1, 1,1,0,1, 1,1,0,1, 1,1,0,1, 1,1,0,1, /* bottom - magenta*/ 1,0,1,1, 1,0,1,1, 1,0,1,1, 1,0,1,1, 1,0,1,1, 1,0,1,1 }; ThreeDCube() { super(FullScreen.DEFAULT_MENU | FullScreen.DEFAULT_CLOSE); } private void initialize() { // Get EGL interface _egl = (EGL11)EGLContext.getEGL(); // Get the EGL display _eglDisplay = _egl.eglGetDisplay(EGL11.EGL_DEFAULT_DISPLAY); // Initialize the display for EGL, null since we don't really need the // version. _egl.eglInitialize(_eglDisplay, null); // Choose an EGL config

// right 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, // back 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, // left -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, // top -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, // bottom -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f

105

Gua de desarrollo

Cdigo de ejemplo: dibujo de un cubo en 3D

} private FloatBuffer createVertexBuffer() { FloatBuffer buffer = ByteBuffer.allocateDirect(_vertices.length * 4).asFloatBuffer(); buffer.put(_vertices); buffer.rewind(); return buffer; } private FloatBuffer createNormalBuffer() { FloatBuffer buffer = ByteBuffer.allocateDirect(_normals.length * 4).asFloatBuffer(); buffer.put(_normals); buffer.rewind(); return buffer; } private FloatBuffer createColorBuffer() { FloatBuffer buffer = ByteBuffer.allocateDirect(_colors.length * 4).asFloatBuffer(); buffer.put(_colors); buffer.rewind(); return buffer; } private void createEGLContext() { // Create an EGL context _eglContext = _egl.eglCreateContext (_eglDisplay, _eglConfig, EGL10.EGL_NO_CONTEXT, null); // Get the GL interface for our new context _gl = (GL10)_eglContext.getGL();

EGLConfig[] configs = new EGLConfig[1]; int[] numConfigs = new int[1]; int[] attrs = { EGL11.EGL_RED_SIZE, 5, EGL11.EGL_GREEN_SIZE, 6, EGL11.EGL_BLUE_SIZE, 5, EGL11.EGL_NONE }; _egl.eglChooseConfig(_eglDisplay, attrs, configs, 1, numConfigs); _eglConfig = configs[0]; // Create an EGL window surface _eglSurface = _egl.eglCreateWindowSurface (_eglDisplay, _eglConfig, this, null); // Create an EGL context createEGLContext(); _cubeVertices = createVertexBuffer(); _cubeNormals = createNormalBuffer(); _cubeColors = createColorBuffer(); _vertexCount = _vertices.length / 3;

106

Gua de desarrollo

Cdigo de ejemplo: dibujo de un cubo en 3D

} private void destroyEGL() { _egl.eglMakeCurrent(_eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); _egl.eglDestroyContext(_eglDisplay, _eglContext); _egl.eglDestroySurface(_eglDisplay, _eglSurface); } private void handleContextLost() { // Destroy our EGL context _egl.eglMakeCurrent(_eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); _egl.eglDestroyContext(_eglDisplay, _eglContext); _eglContext = EGL10.EGL_NO_CONTEXT; // Re-create our EGL context createEGLContext(); } /** * Main render loop. */ public void run() { initialize(); int throttle = 0; while (_running) { throttle = (int)System.currentTimeMillis(); // Idle If we are in the background if (_paused) { synchronized (this) { try { wait(); } catch (InterruptedException x) { } } } updateBackBuffer(); renderFrame(); ++_angle; if (_angle >= 360f) { _angle = 0f; } //Determine how long the frame took to render. throttle = (int)System.currentTimeMillis() - throttle;

// Make our new context current _egl.eglMakeCurrent (_eglDisplay, _eglSurface, _eglSurface, _eglContext);

107

Gua de desarrollo

Cdigo de ejemplo: dibujo de un cubo en 3D

} private void renderFrame() { // Make our context and surface current and check for EGL_CONTEXT_LOST if (!_egl.eglMakeCurrent(_eglDisplay, _eglSurface, _eglSurface, _eglContext)) { if (_egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) handleContextLost(); } // Signal that we are about to begin OpenGL rendering _egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, _offscreenGraphics); render(_gl); // Signal that OpenGL ES rendering is complete _egl.eglWaitGL(); // Swap the window surface to the display _egl.eglSwapBuffers(_eglDisplay, _eglSurface); } private void render(GL10 gl) { // Set our GL viewport gl.glViewport(0, 0, getWidth(), getHeight()); // Clear the surface gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); net.rim.device.api.opengles.GLUtils.gluPerspective(gl, 45.0f, (float)getWidth()/(float)getHeight(), 0.15f, 100.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); // Setup drawing state gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_LIGHTING); gl.glEnable(GL10.GL_LIGHT0); gl.glEnable(GL10.GL_COLOR_MATERIAL); // Draw our cube gl.glTranslatef(0, 0, -3.5f); gl.glRotatef(_angle, 1.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

} destroyEGL();

//Throttle to 30 FPS to control CPU usage. throttle = 33 - throttle; if (throttle > 0) { // Throttle cpu usage try { Thread.sleep(throttle); } catch (InterruptedException x) { } }

108

Gua de desarrollo

Cdigo de ejemplo: dibujo de un cubo en 3D

} /** * Called by the UI system to paint the screen. */ protected void paint(Graphics g) { if (_offscreenBitmap != null) g.drawBitmap(0, 0, _offscreenBitmap.getWidth(), _offscreenBitmap.getHeight(), _offscreenBitmap, 0, 0); } /** * Called when the visibility of our screen changes. * * @param visible true if our screen is being made visible, * false if it's being hidden */ protected void onVisibilityChange(boolean visible) { if (visible) { resume(); } else { pause(); } } /** * Called when the screen is closing. */ public void close() { _running = false; synchronized (this) { notifyAll(); } super.close(); } /** * Keeps the back buffer in sync with the screen size. */ private void updateBackBuffer() { if (_offscreenBitmap != null) { if (_offscreenBitmap.getWidth() == getWidth() && _offscreenBitmap.getHeight() == getHeight()) return; // no change needed

gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, _cubeVertices); gl.glNormalPointer(GL10.GL_FLOAT, 0, _cubeNormals); gl.glColorPointer(4, GL10.GL_FLOAT, 0, _cubeColors); gl.glDrawArrays(GL10.GL_TRIANGLES, 0, _vertexCount);

109

Gua de desarrollo

Utilidades de matemticas 3D

} private void pause() { _paused = true; } private void resume() { if (_running) { // Pause the render loop _paused = false; synchronized (this) { notifyAll(); } } else { // Start the render thread. _running = true; new Thread(this).start(); } }

} _offscreenBitmap = new Bitmap(getWidth(), getHeight()); _offscreenGraphics = Graphics.create(_offscreenBitmap);

Utilidades de matemticas 3D
Puede utilizar los mtodos proporcionados en el paquete net.rim.device.api.math para mejorar la versatilidad matemtica y la velocidad de procesamiento de las aplicaciones del dispositivo BlackBerry que haya creado.

Cdigo de ejemplo: uso de aritmtica de punto fijo


La clase math.Fixed32 es una recopilacin de mtodos aritmticos de punto fijo que utiliza la convencin 16.16 para corregir el punto decimal. Esta convencin designa los 16 bits ms significativos del valor int de 32 bits como el componente de punto fijo del valor y el resto como el componente decimal El siguiente cdigo de ejemplo muestra cmo se puede y no se puede utilizar la clase Fixed32 para la suma, resta, multiplicacin, divisin, conversin del valor y trigonometra.
import net.rim.device.api.math.*; public class demoFixed32 { demoFixed32() { // convert an integer to fixed-point int n = Fixed32.toFP(7); // 7.0

110

Gua de desarrollo

Utilidades de matemticas 3D

// convert a quantity in ten-thousandths to fixed-point int m = Fixed32.tenThouToFP(70625); // 7.0625 // convert from fixed-point, truncate fractional component int trunc = Fixed32.toInt(m); // 7 // multiply by ten thousand int mult = Fixed32.toIntTenThou(m); // 70625 // add, subtract, negate, and compare int result = m - n; // 7.0625 - 7.0 == 0.0625 result = -result; // -0.0625 result -= n; // -0.0625 - 7.0 == -7.0625 boolean b = (result == -m); // true boolean bb = (m < n); // false // do not use increment and decrement operators result = Fixed32.toFP(2); ++result; // WRONG! result will NOT be 3 result = Fixed32.toFP(2); result += Fixed32.toFP(1); // Correct: result will be 3 // Use * and / when multiplying or dividing by an integer scalar // Use mul to multiply 2 fixed-point numbers // Use div to divide 2 fixed-point numbers m = Fixed32.tenThouToFP(12500); // 1.25 m *= 3; // OK: 1.25 * 3 == 3.75 m /= 2; // OK: 3.75 / 2 == 1.875 m = Fixed32.mul(m, Fixed32.tenThouToFP(15000)); // 1.875 * 1.5000 == 2.8125 m = Fixed32.div(m, m); // 2.8125 / 2.8125 == 1.0 // mul, div, sqrt, sind, cosd, tand, and atand2 // all work with 16.16 fixed-point numbers m = Fixed32.tenThouToFP(172500); // 17.2500 n = Fixed32.sqrt(m); // sqrt(17.25) n = Fixed32.sind(m); // sine of 17.25 degrees n = Fixed32.cosd(m); // cosine of 17.25 degrees result = Fixed32.atand2(-m, -m); // -135.0 degrees in fixed-point

111

Gua de desarrollo

Glosario

Glosario
API Application Programming Interface (Interfaz de programacin de aplicaciones) CLDC Connected Limited Device Configuration (Configuracin de dispositivos con conexin limitada) EVDO Evolution Data Optimized (Datos de evolucin optimizada) GSM Global System for Mobile communications (Sistema global para comunicaciones mviles) HTTP Hypertext Transfer Protocol (Protocolo de transferencia de hipertexto)

HTTPS Hypertext Transfer Protocol over Secure Sockets Layer (Protocolo de transferencia de hipertexto a travs de un nivel de socket seguro) E/S entrada/salida JSR Java Specification Request JVM Java Virtual Machine MIDP Mobile Information Device Profile (Perfil de dispositivo mvil de informacin) PCM pulse code modulation (modulacin de cdigo de pulso) RAPC RIM Application Program Compiler (Compilador de programas de aplicaciones de RIM) RMS Sistema de administracin de registros (Record Management System) RTSP

112

Gua de desarrollo

Glosario

Real Time Streaming Protocol (Protocolo de streaming en tiempo real) SVG Scalable Vector Graphics (Grficos vectoriales escalables) TCP Transmission Control Protocol (Protocolo de control de transmisin) TLS Transport Layer Security (Seguridad de capa de transporte)

113

Gua de desarrollo

Comentarios

Comentarios
Para ofrecer comentarios acerca de este documento, visite www.blackberry.com/docsfeedback.

10

114

Gua de desarrollo

Historial de revisin del documento

Historial de revisin del documento


Fecha 14 de agosto de 2009 Descripcin

11

Se aadieron los temas siguientes: Visualizacin de una imagen acercndola, alejndola y desplazndola Mostrar una imagen acercndola, alejndola y desplazndola Cdigo de ejemplo: visualizacin de una imagen acercndola, alejndola y desplazndola Visualizacin de una fila de imgenes para realizar desplazamientos Mostrar una fila de imgenes para realizar desplazamientos Cdigo de ejemplo: visualizacin de una fila de imgenes para realizar desplazamientos

115

Gua de desarrollo

Aviso legal

Aviso legal

12

2010 Research In Motion Limited. Todos los derechos reservados. BlackBerry, RIM, Research In Motion, SureType, SurePress y las marcas comerciales, nombres y logotipos relacionados son propiedad de Research In Motion Limited y estn registrados y/o se utilizan en EE.UU. y en diferentes pases del mundo. Bluetooth es una marca comercial de Bluetooth SIG. Java y Javadoc son marcas comerciales de Sun Microsystems, Inc. Plazmic es una marca comercial de Plazmic Inc. Todas las dems marcas comerciales son propiedad de sus respectivos propietarios. Esta documentacin, incluida cualquier documentacin que se incorpore mediante referencia como documento proporcionado o disponible en www.blackberry.com/go/docs, se proporciona o se pone a disposicin "TAL CUAL" y "SEGN SU DISPONIBILIDAD" sin ninguna condicin, responsabilidad o garanta de ningn tipo por Research In Motion Limited y sus empresas afiliadas ("RIM") y RIM no asume ninguna responsabilidad por los errores tipogrficos, tcnicos o cualquier otra imprecisin, error u omisin contenidos en esta documentacin. Con el fin de proteger la informacin confidencial y propia de RIM, as como los secretos comerciales, la presente documentacin describe algunos aspectos de la tecnologa de RIM en lneas generales. RIM se reserva el derecho a modificar peridicamente la informacin que contiene esta documentacin, si bien tampoco se compromete en modo alguno a proporcionar cambios, actualizaciones, ampliaciones o cualquier otro tipo de informacin que se pueda agregar a esta documentacin. Esta documentacin puede contener referencias a fuentes de informacin, hardware o software, productos o servicios, incluidos componentes y contenido como, por ejemplo, el contenido protegido por copyright y/o sitios Web de terceros (conjuntamente, los "Productos y servicios de terceros"). RIM no controla ni es responsable de ningn tipo de Productos y servicios de terceros, incluido, sin restricciones, el contenido, la exactitud, el cumplimiento de copyright, la compatibilidad, el rendimiento, la honradez, la legalidad, la decencia, los vnculos o cualquier otro aspecto de los Productos y servicios de terceros. La inclusin de una referencia a los Productos y servicios de terceros en esta documentacin no implica que RIM se haga responsable de dichos Productos y servicios de terceros o de dichos terceros en modo alguno. EXCEPTO EN LA MEDIDA EN QUE LO PROHBA ESPECFICAMENTE LA LEY DE SU JURISDICCIN, QUEDAN EXCLUIDAS POR LA PRESENTE TODAS LAS CONDICIONES, APROBACIONES O GARANTAS DE CUALQUIER TIPO, EXPLCITAS O IMPLCITAS, INCLUIDA, SIN NINGN TIPO DE LIMITACIN, CUALQUIER CONDICIN, APROBACIN, GARANTA, DECLARACIN DE GARANTA DE DURABILIDAD, IDONEIDAD PARA UN FIN O USO DETERMINADO, COMERCIABILIDAD, CALIDAD COMERCIAL, ESTADO DE NO INFRACCIN, CALIDAD SATISFACTORIA O TITULARIDAD, O QUE SE DERIVE DE UNA LEY O COSTUMBRE O UN CURSO DE LAS NEGOCIACIONES O USO DEL COMERCIO, O RELACIONADO CON LA DOCUMENTACIN O SU USO O RENDIMIENTO O NO RENDIMIENTO DE CUALQUIER SOFTWARE, HARDWARE, SERVICIO O CUALQUIER PRODUCTO O SERVICIO DE TERCEROS MENCIONADOS AQU. TAMBIN PODRA TENER OTROS DERECHOS QUE VARAN SEGN EL ESTADO O PROVINCIA. ES POSIBLE QUE ALGUNAS JURISDICCIONES NO PERMITAN LA EXCLUSIN O LA LIMITACIN DE GARANTAS IMPLCITAS Y CONDICIONES. EN LA MEDIDA EN QUE LO PERMITA LA LEY, CUALQUIER GARANTA IMPLCITA O CONDICIONES EN RELACIN CON LA DOCUMENTACIN NO SE PUEDEN EXCLUIR TAL Y COMO SE HA EXPUESTO ANTERIORMENTE, PERO PUEDEN SER LIMITADAS, Y POR LA PRESENTE ESTN LIMITADAS A NOVENTA (90) DAS DESDE DE LA FECHA QUE ADQUIRI LA DOCUMENTACIN O EL ELEMENTO QUE ES SUJETO DE LA RECLAMACIN. EN LA MEDIDA MXIMA EN QUE LO PERMITA LA LEY DE SU JURISDICCIN, EN NINGN CASO RIM ASUMIR RESPONSABILIDAD ALGUNA POR CUALQUIER TIPO DE DAOS RELACIONADOS CON ESTA DOCUMENTACIN O SU USO, O RENDIMIENTO O NO RENDIMIENTO DE CUALQUIER SOFTWARE, HARDWARE, SERVICIO O PRODUCTOS Y SERVICIOS

116

Gua de desarrollo

Aviso legal

DE TERCEROS AQU MENCIONADOS INCLUIDOS SIN NINGN TIPO DE LIMITACIN CUALQUIERA DE LOS SIGUIENTES DAOS: DIRECTOS, RESULTANTES, EJEMPLARES, INCIDENTALES, INDIRECTOS, ESPECIALES, PUNITIVOS O AGRAVADOS, DAOS POR PRDIDA DE BENEFICIOS O INGRESOS, IMPOSIBILIDAD DE CONSEGUIR LOS AHORROS ESPERADOS, INTERRUPCIN DE LA ACTIVIDAD COMERCIAL, PRDIDA DE INFORMACIN COMERCIAL, PRDIDA DE LA OPORTUNIDAD DE NEGOCIO O CORRUPCIN O PRDIDA DE DATOS, IMPOSIBILIDAD DE TRANSMITIR O RECIBIR CUALQUIER DATO, PROBLEMAS ASOCIADOS CON CUALQUIER APLICACIN QUE SE UTILICE JUNTO CON PRODUCTOS Y SERVICIOS DE RIM, COSTES DEBIDOS AL TIEMPO DE INACTIVIDAD, PRDIDA DE USO DE LOS PRODUCTOS Y SERVICIOS DE RIM O PARTE DE L O DE CUALQUIER SERVICIO DE USO, COSTE DE SERVICIOS SUSTITUTIVOS, COSTES DE COBERTURA, INSTALACIONES O SERVICIOS, COSTE DEL CAPITAL O CUALQUIER OTRA PRDIDA MONETARIA SIMILAR, TANTO SI DICHOS DAOS SE HAN PREVISTO O NO, Y AUNQUE SE HAYA AVISADO A RIM DE LA POSIBILIDAD DE DICHOS DAOS. EN LA MEDIDA MXIMA EN QUE LO PERMITA LA LEY DE SU JURISDICCIN, RIM NO TENDR NINGN OTRO TIPO DE OBLIGACIN O RESPONSABILIDAD CONTRACTUAL, EXTRACONTRACTUAL O CUALQUIER OTRA, INCLUIDA CUALQUIER RESPONSABILIDAD POR NEGLIGENCIA O RESPONSABILIDAD ESTRICTA. LAS LIMITACIONES, EXCLUSIONES Y DESCARGOS DE RESPONSABILIDAD SE APLICARN: (A) INDEPENDIENTEMENTE DE LA NATURALEZA DE LA CAUSA DE LA ACCIN, DEMANDA O ACCIN SUYA, INCLUIDA PERO NO LIMITADA AL INCUMPLIMIENTO DEL CONTRATO, NEGLIGENCIA, AGRAVIO, EXTRACONTRACTUAL, RESPONSABILIDAD ESTRICTA O CUALQUIER OTRA TEORA DEL DERECHO Y DEBERN SOBREVIVIR A UNO O MS INCUMPLIMIENTOS ESENCIALES O AL INCUMPLIMIENTO DEL PROPSITO ESENCIAL DE ESTE CONTRATO O CUALQUIER SOLUCIN CONTENIDA AQU; Y (B) A RIM Y A SUS EMPRESAS AFILIADAS, SUS SUCESORES, CESIONARIOS, AGENTES, PROVEEDORES (INCLUIDOS LOS PROVEEDORES DE SERVICIOS DE USO), DISTRIBUIDORES AUTORIZADOS POR RIM (INCLUIDOS TAMBIN LOS PROVEEDORES DE SERVICIOS DE USO) Y SUS RESPECTIVOS DIRECTORES, EMPLEADOS Y CONTRATISTAS INDEPENDIENTES. ADEMS DE LAS LIMITACIONES Y EXCLUSIONES MENCIONADAS ANTERIORMENTE, EN NINGN CASO NINGN DIRECTOR, EMPLEADO, AGENTE, DISTRIBUIDOR, PROVEEDOR, CONTRATISTA INDEPENDIENTE DE RIM O CUALQUIER AFILIADO DE RIM ASUMIR NINGUNA RESPONSABILIDAD DERIVADA DE O RELACIONADA CON LA DOCUMENTACIN. Antes de instalar, usar o suscribirse a cualquiera de los Productos y servicios de terceros, es su responsabilidad asegurarse de que su proveedor de servicios de uso ofrezca compatibilidad con todas sus funciones. Puede que algunos proveedores de servicios de uso no ofrezcan las funciones de exploracin de Internet con una suscripcin al servicio BlackBerry Internet Service. Consulte con su proveedor de servicios acerca de la disponibilidad, arreglos de itinerancia, planes de servicio y funciones. La instalacin o el uso de los Productos y servicios de terceros con productos y servicios de RIM puede precisar la obtencin de una o ms patentes, marcas comerciales, derechos de autor u otras licencias para evitar que se vulneren o violen derechos de terceros. Usted es el nico responsable de determinar si desea utilizar Productos y servicios de terceros y si se necesita para ello cualquier otra licencia de terceros. En caso de necesitarlas, usted es el nico responsable de su adquisicin. No instale o utilice Productos y servicios de terceros hasta que se hayan adquirido todas las licencias necesarias. Cualquier tipo de Productos y servicios de terceros que se proporcione con los productos y servicios de RIM se le facilita para su comodidad "TAL CUAL" sin ninguna condicin expresa e implcita, aprobacin, garanta de cualquier tipo por RIM y RIM no sume ninguna responsabilidad en relacin con ello. El uso de los Productos y servicios de terceros se regir y estar sujeto a la aceptacin de los trminos de licencias independientes aplicables en este caso con terceros, excepto en los casos cubiertos expresamente por una licencia u otro acuerdo con RIM. Algunas funciones mencionadas en esta documentacin requieren una versin mnima del software de BlackBerry Enterprise Server, BlackBerry Desktop Software y/o BlackBerry Device Software.

117

Gua de desarrollo

Aviso legal

Los trminos de uso de cualquier producto o servicio de RIM se presentan en una licencia independiente o en otro acuerdo con RIM que se aplica en este caso. NINGUNA PARTE DE LA PRESENTE DOCUMENTACIN EST PENSADA PARA PREVALECER SOBRE CUALQUIER ACUERDO EXPRESO POR ESCRITO O GARANTA PROPORCIONADA POR RIM PARA PARTES DE CUALQUIER PRODUCTO O SERVICIO DE RIM QUE NO SEA ESTA DOCUMENTACIN.

Research In Motion Limited 295 Phillip Street Waterloo, ON N2L 3W8 Canad Research In Motion UK Limited Centrum House 36 Station Road Egham, Surrey TW20 9LF Reino Unido Publicado en Canad

118

You might also like