Acceso a cámara del móvil con Java ME
Disponemos de dos opciones que se diferencian en el objeto que va a contener los datos procedentes de la cámara. Las opciones son hacer que un form sea el contenedor de las imágenes procedentes de la cámara o bien un Canvas.La aplicación estará formada por un form inicial que nos da paso a obtener video representado en otro form o a través de un Canvas a partir de un menu.
El resultado es el video siguiente:
Código de la clase MIDlet
En primer lugar tenemos la clase que implementa el MIDlet. Su código es el siguiente:import java.io.IOException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.media.MediaException;
import javax.microedition.midlet.MIDlet;
/**
* @author fran
*/
public class captureMidlet extends MIDlet implements CommandListener {
private Command backCommand = null, exitCommand = null;
private initForm initForm = null;
private videoForm videoForm = null;
private videoCanvas videoCanvas=null;
private boolean canvas;
public captureMidlet() throws IOException, MediaException {
backCommand = new Command("Back", Command.BACK, 0);
exitCommand = new Command("Exit", Command.EXIT, 0);
initForm = new initForm("videoApp1");
initForm.addCommand(exitCommand);
initForm.setCommandListener(this);
videoForm = new videoForm("camera");
videoForm.addCommand(backCommand);
videoForm.setCommandListener(this);
videoCanvas=new videoCanvas(this);
videoCanvas.addCommand(backCommand);
}
public void startApp() {
setDisplayable(initForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
setDisplayable(initForm);
} else {
String labelTxt = c.getLabel().toString();
if (labelTxt.equals("Video en form")) {
setDisplayable(videoForm);
}else if(labelTxt.equals("video en canvas")){
setDisplayable(videoCanvas);
}
}
}
public void setDisplayable(Displayable d) {
Display.getDisplay(this).setCurrent(d);
}
}
Esta clase implementa el CommandListener para poder reaccionar a los eventos de los comandos que vamos a ir añadiendo. Como consecuencia de esto, aparece el método commandAction. Este métdo es el que se encarga de la gestión de los eventos lanzados al pulsar uncomando.
Como se puede ver hay un constructor en el que inicializamos los contenedores (dos para el video y un form inicial). Estos contenedores son clases en sí mismos para proporcionar un diseño intuitivo.
Además, disponemos de los métodos propios de un MIDlet: startApp(),pauseApp() y destroyApp(). Son los métodos que se ejecutan cuando se inicializa, se pausa y se destruye (cierra) la aplicación respectivamente.
El método setDisplayable se encarga de hacer visible en pantalla el contenedor apropiado en cada momento.
Código del form de inicio:
public class initForm extends Form {
private Command canvasCommand=null, formCommand=null;
public initForm(String title) {
super(title);
canvasCommand= new Command("video en canvas",Command.OK,1);
formCommand= new Command("Video en form", Command.OK,2);
this.addCommand(canvasCommand);
this.addCommand(formCommand);
}
}
Esta clase conforma el Form de inicio de la aplicación. Se le añaden los comandos que darán acceso a mostrar el video captado por la cámara en un Form o en un Canvas.
Código del form de Canvas:
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Item;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
/**
*
* @author fran
*/
public class videoCanvas extends Canvas {
private Player player = null;
private VideoControl videoControl = null;
private int width, height;
private Item mVideoItem;
private videoCanvas videoCanvas;
public videoCanvas(captureMidlet midlet) throws IOException, MediaException {
player = Manager.createPlayer("capture://video");
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
player.start();
width = this.getWidth();
height = this.getHeight();
videoControl.initDisplayCódigo del form de inicio:Mode(VideoControl.USE_DIRECT_VIDEO, this);
videoControl.setDisplaySize(width, height);
videoControl.setDisplaySize(width, height);
videoControl.setVisible(true);
this.setCommandListener(midlet);
}
protected void paint(Graphics g) {
int width = getWidth();
int height = getHeight();
g.setColor(0x00ff00);
g.drawRect(0, 0, width - 1, height - 1);
g.drawRect(1, 1, width - 3, height - 3);
}
}
En esta clase tenemos el código que permite acceder al video de la cámara. Hay que destacar videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this). En esta línea de código se establece el modo directo. Este modo tiene que ser representado en un Canvas.
Código del form para el video:
import java.io.IOException;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
/* * To change this template, choose Tools | Templates and open the template in * the editor. */
/** * * @author fran */
public class videoForm extends Form {
private Player player = null;
private VideoControl videoControl = null;
private int width, height;
private Item mVideoItem;
private videoCanvas videoCanvas;
public videoForm(String title) throws IOException, MediaException { super(title);
player = Manager.createPlayer("capture://video");
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl"); player.start();
width = this.getWidth();
height = this.getHeight();
mVideoItem = (Item) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null); videoControl.setDisplaySize(width, height); mVideoItem.setLayout(Item.LAYOUT_EXPAND); videoControl.setDisplaySize(width, height);
videoControl.setVisible(true);
this.append(mVideoItem); }
}
En esta clase se incluye el código para mostrar el video en un Form. La unica diferencia importante respecto a la anterior clase es videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null); en lugar del modo de video usado anteriormente. Vemos que él código cambia un poco respecto al anterior, pero es muy similar.
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
/* * To change this template, choose Tools | Templates and open the template in * the editor. */
/** * * @author fran */
public class videoForm extends Form {
private Player player = null;
private VideoControl videoControl = null;
private int width, height;
private Item mVideoItem;
private videoCanvas videoCanvas;
public videoForm(String title) throws IOException, MediaException { super(title);
player = Manager.createPlayer("capture://video");
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl"); player.start();
width = this.getWidth();
height = this.getHeight();
mVideoItem = (Item) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null); videoControl.setDisplaySize(width, height); mVideoItem.setLayout(Item.LAYOUT_EXPAND); videoControl.setDisplaySize(width, height);
videoControl.setVisible(true);
this.append(mVideoItem); }
}
En esta clase se incluye el código para mostrar el video en un Form. La unica diferencia importante respecto a la anterior clase es videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null); en lugar del modo de video usado anteriormente. Vemos que él código cambia un poco respecto al anterior, pero es muy similar.
Al instalar este código en un móbil puede ser que no se muestre a pantalla completa. Esto depende del módelo de móvil en cuestión. Para instalar la aplicación hemos de portar el archivo .jad y .jar al móbil en cuestión.
No hay comentarios:
Publicar un comentario