Librería msound para Mobile Processing en acción
Existen un grupo de librerías para Mobile Processing que no pertenecen al nucleo, hechas por terceros para extender sus funcionalidades. Existe en un apartado de Referencias en la página oficial de Mobile Processing en donde se detallan estas librearías.
En esta ocasión se mostrarán los midlets corriendo en un n95, para ejemplificar el uso de la librería msound.
Cada tecla está asociada a una frecuencia diferente.
Presentación Introducción a Mobilie Processing
Importar contactos a partir de un .txt
Aquí esta el complemento, muy útil cuando cambiamos de teléfono. En el archivo de entrada, cada línea es un contacto, el primer campo es el nombre del contacto y el segundo el número telefónico correspondiente. Los campos se separan por tabuladores, este es un ejemplo del archivo de entrada “contactos.txt”:
pzo{phrrdw 3645688357
dwhvotiuul 9827914405
vfltjdlakf 0544231692
dkiimtwktg 2587469846
cdxibeuhgb 8662069239
jtjivwksvb 2151870224
dpbnjfpgzt 2950363356
esaooqfoun 9590050987
swmilkrg{d 0705686048
pdjzcgioeb 7049194677
{gvqwsmtmw 3441362136
ztqcnwibxg 1054659213
yblbwcebog 7803351735
n{qogrgwbd 8184444490
El código del midlet, es el siguiente:
/*Importa contactos
por Dennys Regalado Díaz
Utilidad, 4 de Abril del 2009
*/
import mjs.processing.mobile.mfiles.*;
import mjs.processing.mobile.mpim.*;
String fileName = "file:///root1/contactos.txt";
// Create the PIM object
MPIM mPIM;
MContact mContact;
MContactList mContactList;
String lines[];
PFont fuente;
int i;
// Open the contact list in read mode and get all the contacts
MContact[] contacts;
void setup(){
fuente = loadFont();
textFont(fuente);
textAlign(LEFT);
// For each contact show name an phone number
fill(0);
i=0;
try{
lines = MFiles.loadStrings(fileName);
}
catch(Exception e){
text("Error al intentar leer \"contactos.txt\"",width/2,height/2);
}
mPIM = new MPIM();
mContactList = mPIM.contactList(MPIM.WRITE);
}
void draw(){
background(255);
if(i< length(lines)){
mContact= mContactList.createContact();
String items[] = split(lines[i],"\t");
mContact.name(items[0]);
mContact.tel(items[1]);
mContact.save();
int value = (i*(width-20))/length(lines);
int percent = (i*100)/length(lines);
text(items[0]+"...",20,15);
text(percent+"%",width/2,height/2-40);
rect(10,height/2-30,value,10);
i++;
}
else{
textAlign(CENTER);
text("Hecho.",width/2,height/2);
text("Se importaron " +length(lines) + " contacto(s)",width/2,height/2 + 15);
text("de \"contactos.txt\"",width/2,height/2 + 35);
noLoop();
}
}
Exportar los contactos de mi teléfono a un archivo .txt
Aquí les dejo un pequeño sketch escrito en mobile processing para exportar la lista de contactos a un archivo de texto. La idea es que luego puedan enviar este archivo a su PC para respaldarlo.


Nota: cambien las variable fileName con la ruta de su teléfono!!!
Este es el código usando las librerias mfiles y mpim de Marlon:
por Dennys Regalado Díaz
Utilidades, 4 de Abril del 2009
*/
import mjs.processing.mobile.mfiles.*;
import mjs.processing.mobile.mpim.*;
String fileName = "file:///root1/contactos.txt";
// Create the PIM object
MPIM mPIM = new MPIM();
String lines[];
PFont fuente;
int i;
// Open the contact list in read mode and get all the contacts
MContact[] contacts;
void setup(){
fuente = loadFont();
textFont(fuente);
textAlign(LEFT);
// For each contact show name an phone number
fill(0);
i=0;
contacts = mPIM.contactList(MPIM.READ).contacts();
lines = new String[length(contacts)];
}
void draw(){
background(255);
if(i< length(contacts)){
lines[i] = contacts[i].name() + "\t"+contacts[i].tel();
int value = (i*(width-20))/length(contacts);
int percent = (i*100)/length(contacts);
text(contacts[i].name()+"...",20,15);
text(percent+"%",width/2,height/2-40);
rect(10,height/2-30,value,10);
// text(contacts[i].name(),10,15*i);
i++;
}
else{
textAlign(CENTER);
try{
MFiles.saveStrings(fileName,lines);
text("Hecho.",width/2,height/2);
text("Se exportaron " +length(contacts) + " contacto(s)",width/2,height/2 + 15);
text("a \"contactos.txt\"",width/2,height/2 + 35);
}
catch(Exception e){
text("Ocurrio un error en la escritura",width/2,height/2);
}
noLoop();
}
}
Cómo utilizar tu GPS para obtener un mapa de tu posición actual
mapa_yahoo_Juchitán de Zaragoza, Oaxaca
En este post se describe un sketch escrito en Mobile Processing para la navegación por GPS (ver nokia Maps). Empeceos con el GPS, gracias a la librería mlocation podemos accesar a las coordenas (latitud, longitud) de nuestra posición actual.
Después, hacemos uso del servicio de Yahoo! Maps, en el que podemos hacer consultas pasando como parámetros las coordenadas del GPS y obtenemos una imagen con el mapa correspondiente. Este servicio es gratuito, solo hay que registrarse para obtener un ID que se debe anexar a cada consulta.
La desventaja es que necesitamos un punto de acceso para conectarnos a Internet gratis, así que esto solo podrá ser útil en algunos lugares públicos, tiendas departamentales, hospitales, etc., que cuentan con este servicio.
Motivación

Código
PClient clientXML;
PClient clientMap;
PRequest requestXML;
PRequest requestMap;
PFont font;
PImage mapImage;
String xml;
String mapURL;
double[] coords = new double[2];
double latitude, longitude;
void setup(){
clientXML = new PClient(this,"local.yahooapis.com");
clientMap = new PClient(this,"gws.maps.yahoo.com");
font = loadFont();
textFont(font);
noLoop();
MLocation.location(coords);
latitude = coords[0];
longitude = coords[1];
}
void draw() {
background(0);
fill(255);
if( mapImage != null ) {
image(mapImage, width/2-mapImage.width/2, height/2- mapImage.height/2);
text("Imagen cargada",width/2,height/2);
}
else {
text("("+latitude+","+longitude+")",4,14);
text("Descargando mapa...",4,20,width-8,height-8);
requestXML = clientXML.GET("/MapsService/V1/mapImage?appid=ID--&latitude=" + latitude + "&longitude=" + longitude + "&zoom=2&image_height=" + height+ "&image_width=" + width);
}
}
void libraryEvent(Object library, int event, Object data) {
if (library == requestXML) {
if (event == PRequest.EVENT_CONNECTED) {
requestXML.readBytes();
}
else if (event == PRequest.EVENT_DONE) {
xml = new String((byte[]) data);
int start = xml.indexOf("instance\"\>;") + 10; int end = xml.indexOf(
int end = xml.indexOf("\
mapURL = xml.substring(start, end);
requestXML.close();
requestMap = clientMap.GET(mapURL.substring(25));
}
}
if (library == requestMap) {
if (event == PRequest.EVENT_CONNECTED) {
requestMap.readBytes();
}
else if (event == PRequest.EVENT_DONE) {
mapImage = loadImage((byte[]) data);
requestMap.close();
redraw();
}
}
}
Juego 5 o más con mobil processing
Esta es una versión mobil para el clásico juego 5 o más. El objetivo es conectar 5 o más esferas del mismo color formando una línea vertical, horizontal o en diagonal. Espero que lo disfruten tanto como yo disfrute escribiéndolo. Un par de cosas interesantes implementadas en este juego:
- El algoritmo BFS implementado con una cola simulada.
- La animación al mover una bola.
Lo probé en dos modelos de nokia 5300 y 5610.

LG cookie
Código de la cola simulada
int array[];
Queue(){
array = new int[0];
}
void push(int x){
array = append(array,x);
}
void pop(){
array = reverse(shorten(reverse(array)));
}
int front(){
if (!empty())
return array[0];
return -1;
}
boolean empty(){
return (length(array)==0);
}
}
Descargar el juego gratis desde aquí.
Mobile Processing para Linux

mobile processing
Una receta para instalar Mobile Processing en ubuntu 8.10, por Marlon J. Manrique. Muy interesante los sketches del Marlon, aún no tengo oportunidad de probarlos, estoy en espera de un nokia n95. Les recomiendo visitar su página
My First Midlet using Mobile Processing
Well, as you remember (Jugando contra reloj…) we write a simple application using timers for control the palyer’s turn of some game like scrabble, chess, etc.
Now the objective is take that implementation and write its midlet version.
There is some facts that I like to highligth in this section:
1. The program’s structure of processing and mobile-processing is the same, but not include all capabilities.
2. We have concern about keyCodes and events like keyPressed, keyReleased and so on. Because each manufacturer have his own keyboard distribution it’s necesary to use an utility midlet (Examples->keycode) to get the correct keyCodes.

3. The characteristics of your phone are important. You must check the CLDC and MIDP version of the java’s virtual machine. That is, if you could have a version that dosn’t support some class that you require, e.g. Bluetooth support JR-182.
4. The font creator tool generate a distinct font file, e.g. “is_not_the_same_extension.mvlw”.
Motivation
The application running on a nokia 2630b.

by Dennys Regalado Diaz <http://www.challenges.qumax.org/>
A simple clock for controlling turns in a game like scrabble.
First select keys "left" or "right" to select player that begins to play,
then press key "5" to start the game.
Switch player turn using key "5".
Created 11 January 2009
*/
PFont fontA;
PImage []player = new PImage[2];
int cont=0;
boolean pause,
end_of_game,
turno,
first_run,
iniciar;
Timer clock;
Cronos p1,p2;
void setup(){
fontA= loadFont("Verdana-Bold-42.mvlw");
player[0] = loadImage("garu.png");
player[1] = loadImage("pucca.png");
textFont(fontA);
textAlign(CENTER);
//establece el tiempo de actualizacion de 1 segundo
clock = new Timer(1000);
clock.start();
//Cronos(tiempo_inicial,posicion x, posicion y)
p1 =new Cronos(1200,width/2,height-10);
p2 =new Cronos(1200,width/2,height-10);
pause=false;
end_of_game=false;
turno =true;
iniciar = false;
first_run =true;
}
void draw(){
background(255);
image(player[1],0,15);
image(player[0],width-48,15);
if(iniciar){
if(!end_of_game && clock.terminado() && !pause){
if(turno)
p1.decrease();
else
p2.decrease();
clock.start();
}
if(turno)
p1.display();
else
p2.display();
if(p1.lost() || p2.lost())
end_of_game=true;
}
//Indica el turno actual
int select_y = 5;
int select_x = (turno ? 50 : width-10);
fill(0);
stroke(205,222,135);
//dibuja flecha indicadora
triangle(select_x-20,select_y,select_x-40,select_y,select_x-30,select_y+10);
}
void keyReleased(){
if(key == '0') //tecla "0"
pause=!pause;
else if(keyCode==53){ //tecla "5"
if(first_run){//inicia la cuenta regresiva
iniciar = true;
first_run=false;
}
else //cambio de turno
turno = !turno;
}
else if(first_run && keyCode==2) //tecla izquierda
turno = true;
else if(first_run && keyCode ==5)//tecla derecha
turno = false;
}
class Cronos{
int segundos;
int x,y;
color color_value;
Cronos(int inicial, int pos_x,int pos_y){
segundos = inicial;
x = pos_x;
y = pos_y;
color_value = color(0);
}
void increase(){
segundos++;
}
void decrease(){
segundos--;
}
void display(){
String texto= "";
texto += segundos/60 +":" +segundos%60;
fill(color_value);
text(texto,x,y);
}
int getSeconds(){
return segundos;
}
boolean lost(){//check if player lost
if (segundos == 0){
color_value = color(255,0,0);
return true;
}
else return false;
}
}
class Timer{
int t_inicial;
int lapso;
Timer(int milisegundos){
lapso = milisegundos;
}
void start(){
t_inicial = millis();
}
boolean terminado(){
return (millis()-t_inicial >= lapso);
}
}
Source code: clock.pde
JAD/JAR files: clock.jad / clock.jar
Ahora pueden probar esta nueva versión, en la que se puede establecer el tiempo en un rango de 5 a 59 minutos, el midlet ocupa la pantalla completa y se puede utilizar el botón central (FIRE) en vez de la tecla ‘5′.
Starting with Mobile Processing
Happy new year 2009!, these is one of the post that I must be published months ago, isn’t it? First at all I recomend you visit the oficial page of this project mobile.processing.org.
Let’s start with 3 easy steps:
1. Download the lastest version (1.5 works too) of java and install it.
2. Download the last release of Wireless Toolkit for CLDC (WTK) (mobile java version developing tool), install it and remember its location.

3. Download and install mobile processing for the official page mobile.processing.org. Run it, go to File->Preferences, on “mobile” tab set the path of WTK installation (see image).

Recomended lecture: Mobile Processing Step by Step
Now you have all you need for run and test examples. Note that you have a mobile emulator for running your midlets. Get fun!.

