Sei sulla pagina 1di 19

UMSA-PGI

27/10/2012

Universidad Mayor de San Andrs

Postgrado en Informtica
CURSO DE DESARROLLO DE APLICACIONES ANDROID

Soporte de red,
conexiones
Sesin 13

Verificar conexin
public boolean estaOnline() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}

Podemos cambiar isConnectedOrConnecting() por


isConnected() si deseamos Internet inmediatamente.

Requiere el permiso
android.permission.ACCESS_NETWORK_STATE

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

Contenido
AsyncTask
Parmetros
Mtodos
Ejemplo

Tratamiento

Tratamiento

XML

JSON

Modelos
Aplicacin de
ejemplo
Implementaci
n

JSONObject
JSONArray
Leer y crear

Web
services
SOAP
REST
Peticiones
HTTP

AsyncTask

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

AsyncTask
Tarea asncrona, permite el uso apropiado de
interfaz de usuario dentro de un hilo de forma
sencilla.

Implementacin
public class MiTarea extends AsyncTask<Params, Progress, Result> {

...
}

Parmetros
Params
Datos que pasaremos al comenzar la tarea.

Progress
Parmetros que necesitaremos para actualizar
la IU.

Result
Dato que devolvemos una vez terminada la
tarea.
Si no requerimos alguno colocamos Void.

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

Mtodos
onPreExecute()
Se ejecuta antes de realizar la tarea.

doInBackground(Params)
Encarga de hacer la tarea.

onProgressUpdate(Progress)
Permite actualizar la interfaz mientras se ejecuta
la tarea.

onPostExecute(Result)
Se ejecuta despus de que termine la tarea.

Mtodos
Actualizar interfaz de usuario
Se usa en el mtodo doInBackground(...)
publishProgress(...)
Los parmetros de reciben en onProgressUpdate(...).

Ejecutar
new MiTarea().execute(Params);

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

Demostracin
Aplicacin de ejemplo EjemploAsyncTask

Tratamiento XML

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

Modelos
SAX (Simple API for XML)
DOM (Document Object Model)
StAX (Streaming API for XML)

Aplicacin de
ejemplo
Uso de AsyncTask,
Lector SAX y listas
personalizadas.

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

Implementacin
Clase Lector
Encargada de obtener los datos de Internet,
leernos y adicionarlo a la lista.
public class Lector {
private URL url;
private Evento evento;
public Lector(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
}
}
...
}

Implementacin
Definicin de etiquetas
RootElement root = new RootElement("contenido");
Element item = root.getChild("evento");

Obtencin de contenido de etiquetas


item.setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
evento = new Evento();
}
});
item.getChild("titulo").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
evento.setTitulo(body);
}
});
item.setEndElementListener(new EndElementListener() {
public void end() {
listaEventos.add(evento);
}
});

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

Implementacin
Parsing con una codificacin
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8,
root.getContentHandler());
} catch (Exception ex) {
throw new RuntimeException(ex);
}

Modo de uso
listaEventos = sax.parse();

Demostracin
Aplicacin de ejemplo XML

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

Tratamiento JSON

JSON
Formato de intercambio de datos muy
condensado.
Android incluye las bibliotecas json.org que
permiten trabajar fcilmente con archivos
JSON

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

UMSA-PGI

27/10/2012

Clases
JSONObject
Conjunto de asignaciones clave-valor. Los
nombres son nicos.

JSONArray
Secuencia de valores que pueden ser objetos
JSONObject, otros JSONArray, cadenas, enteros,
booleanos, doubles, longs o NULL.

Ejemplo JSON
[{ "persona": {
"nombre": "Juan",
"apellido": "Perez",
"sexo": "masculino" }

JSONArray

},
{

JSONObject

"persona": {

"nombre": "Katherine",
"apellido": "Vasquez",
"sexo": "femenino" }
}]

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

10

UMSA-PGI

27/10/2012

Leer JSON
Si tenemos un JSONArray se puede acceder a
cada objeto con el mtodo
getJSONObject(posicion).
JSONArray jsonArray = new JSONArray(texto);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String nombre = jsonObject.getString("nombre"),
String apellido = jsonObject.getString("apellido"));
}

Crear JSON
JSONObject object = new JSONObject();
try {
object.put("nombre", "Juan Perez");
object.put("edad", new Integer(45));
object.put("estatura", new Double(152.32));
object.put("apodo", "Chato");
} catch (JSONException e) {
e.printStackTrace();
}

Pueden adicionarse tambin objetos JSONArray.

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

11

UMSA-PGI

27/10/2012

Demostracin
Aplicacin de ejemplo JSON

Web Services

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

12

UMSA-PGI

27/10/2012

Web Services
Cliente

Servidor

REST

SOAP

Utiliza casi siempre


HTTP como
mtodo de
comunicacin.
XML o JSON para
intercambiar datos.
Cada URL
representa un
objeto sobre el cual
se pueden usar
mtodos POST,
GET, PUT y DELETE.

Toda la
infraestructura
basada en XML
Cada objeto puede
tener mtodos
definidos por el
programador con
los parmetros que
sean necesarios.

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

13

UMSA-PGI

27/10/2012

Peticiones HTTP
GET
Devuelve un recurso identificado en la URL pedida.

POST
Indica al servidor que se prepare para recibir
informacin del cliente.

PUT
Enva el recurso identificado en la URL desde el
cliente hacia el servidor.

DELETE
Solicita al servidor que borre el recurso identificado
con el URL.

Insercin
HttpClient cliente = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.43.241:8080/...");
post.setHeader("content-type", "application/json");
try {
JSONObject object = new JSONObject();
object.put("nombre", "Juan");
object.put("telefono", new Integer(123456));
StringEntity entity = new StringEntity(object.toString());
post.setEntity(entity);
HttpResponse respuesta = cliente.execute(post);
String res = EntityUtils.toString(respuesta.getEntity());
if(res.equals("true")) {
// Se inserto correctamente
}
} catch(Exception ex) {
}

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

14

UMSA-PGI

27/10/2012

Actualizar
HttpClient cliente = new DefaultHttpClient();
HttpPut put = new HttpPut("http://192.168.43.241:8080/...");
put.setHeader("content-type", "application/json");
try {
JSONObject object = new JSONObject();
object.put("id", new Integer(777));
object.put("nombre", "Juan");
object.put("telefono", new Integer(123546));
StringEntity entity = new StringEntity(dato.toString());
put.setEntity(entity);
HttpResponse respuesta = cliente.execute(put);
String res = EntityUtils.toString(respuesta.getEntity());
if(res.equals("true")) {
// actualizacion correcta.
}
} catch(Exception ex) {
}

Eliminar
HttpClient httpClient = new DefaultHttpClient();
HttpDelete del = new HttpDelete("http://192.168.43.241:8080/.../id");
del.setHeader("content-type", "application/json");
try {
HttpResponse respuesta = httpClient.execute(del);
String res = EntityUtils.toString(respuesta.getEntity());
if(res.equals("true")) {
// Eliminacin correcta.
}
} catch(Exception ex) {
}

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

15

UMSA-PGI

27/10/2012

Obtener un elemento
HttpClient cliente = new DefaultHttpClient();
HttpGet get = new HttpGet("http://192.168.43.241:8080/.../id");
get.setHeader("content-type", "application/json");
try {
HttpResponse respuesta = cliente.execute(get);
String res = EntityUtils.toString(respuesta.getEntity());
JSONObject object = new JSONObject(res);
int id = object.getInt("id");
String nombre = object.getString("nombre");
int telefono = object.getInt("telefono");
...
} catch(Exception ex) {
}

Obtener todos
HttpClient cliente = new DefaultHttpClient();
HttpGet get = new HttpGet("http://192.168.43.241:8080/...");
get.setHeader("content-type", "application/json");
try {
HttpResponse respuesta = cliente.execute(get);
String res = EntityUtils.toString(respuesta.getEntity());
JSONArray array = new JSONArray(res);
String[] personas = new String[array.length()];
for(int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
int id = object.getInt("id");
String nombre = object.getString("nombre");
int telefono = object.getInt("telefono");
personas[i] = id + "-" + nombre + "-" + telefono;
}
// adicionamos los datos.
} catch(Exception ex) {
}

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

16

UMSA-PGI

27/10/2012

Demostracin
Aplicacin de ejemplo Inventarios

Mas posibilidades

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

17

UMSA-PGI

27/10/2012

Tecnologa NFC
Se comunica mediante induccin en un
campo magntico, esta tecnologa
inalmbrica trabaja en la banda de los
13,56Mhz y por ello no tiene restricciones ni
requiere una licencia para su uso.

Tecnologa NFC
Alcance mximo

20 cm
Taza de transferencia

424 Kbps

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

18

UMSA-PGI

27/10/2012

Tecnologa NFC
Google Wallet

UMSA-PGI
www.pgi.umsa.bo

CURSO DE DESARROLLO DE APLICACIONES


ANDROID

19

Potrebbero piacerti anche