Curso de Desarrollo en android

19
UMSA-PGI 27/10/2012 CURSO DE DESARROLLO DE APLICACIONES ANDROID 1 Universidad Mayor de San Andrés Postgrado en Informática CURSO DE DESARROLLO DE APLICACIONES ANDROID Soporte de red, conexiones Sesión 13 Verificar conexión Podemos cambiar isConnectedOrConnecting() por isConnected() si deseamos Internet inmediatamente. Requiere el permiso public boolean estaOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnectedOrConnecting()) { return true; } return false; } android.permission.ACCESS_NETWORK_STATE

description

Curso de Desarrollo en android

Transcript of Curso de Desarrollo en android

Page 1: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 1

Universidad Mayor de San Andrés

Postgrado en InformáticaCURSO DE DESARROLLO DE APLICACIONES ANDROID

Soporte de red, conexionesSesión 13

Verificar conexión

Podemos cambiar isConnectedOrConnecting() por isConnected() si deseamos Internet inmediatamente.

Requiere el permiso

public boolean estaOnline() {ConnectivityManager cm = (ConnectivityManager)

getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo = cm.getActiveNetworkInfo();if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {

return true;}return false;

}

android.permission.ACCESS_NETWORK_STATE

Page 2: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 2

Contenido

AsyncTask

Parámetros Métodos Ejemplo

Tratamiento

XML

Modelos Aplicación de

ejemplo Implementaci

ón

Tratamiento

JSON

JSONObject JSONArray Leer y crear

Web services

SOAPRESTPeticiones HTTP

AsyncTask

Page 3: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 3

AsyncTask

Tarea asíncrona, permite el uso apropiado de interfaz de usuario dentro de un hilo de forma sencilla.

Implementación

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

...

}

Parámetros

ParamsDatos que pasaremos al comenzar la tarea.

ProgressParámetros que necesitaremos para actualizar la IU.

ResultDato que devolvemos una vez terminada la tarea.

Si no requerimos alguno colocamos Void.

Page 4: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 4

Métodos

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 después de que termine la tarea.

Métodos

Actualizar interfaz de usuarioSe usa en el método doInBackground(...)

Los parámetros de reciben en onProgressUpdate(...).

Ejecutar

publishProgress(...)

new MiTarea().execute(Params);

Page 5: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 5

Demostración

Aplicación de ejemplo “EjemploAsyncTask”

Tratamiento XML

Page 6: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 6

Modelos

SAX (Simple API for XML)

DOM (Document Object Model)

StAX (Streaming API for XML)

Aplicación de ejemplo

Uso de AsyncTask, Lector SAX y listas personalizadas.

Page 7: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 7

Implementación

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) {}

}...

}

Implementación

Definición de etiquetas

Obtención de contenido de etiquetas

RootElement root = new RootElement("contenido");Element item = root.getChild("evento");

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);

}});

Page 8: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 8

Implementación

Parsing con una codificación

Modo de uso

try {Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8,

root.getContentHandler());} catch (Exception ex) {

throw new RuntimeException(ex);}

listaEventos = sax.parse();

Demostración

Aplicación de ejemplo “XML”

Page 9: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 9

Tratamiento JSON

JSON

Formato de intercambio de datos muy condensado.

Android incluye las bibliotecas json.org que permiten trabajar fácilmente con archivos JSON

Page 10: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 10

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" }

},

{ "persona": {

"nombre": "Katherine",

"apellido": "Vasquez",

"sexo": "femenino" }

}]

JSONObjectJSONArray

Page 11: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 11

Leer JSON

Si tenemos un JSONArray se puede acceder a cada objeto con el método 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

Pueden adicionarse también objetos JSONArray.

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();

}

Page 12: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 12

Demostración

Aplicación de ejemplo “JSON”

Web Services

Page 13: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 13

Web Services

Cliente Servidor

REST

Utiliza casi siempre HTTP como método de comunicación.

XML o JSON para intercambiar datos.

Cada URL representa un objeto sobre el cual se pueden usar métodos POST, GET, PUT y DELETE.

Toda la infraestructura basada en XML

Cada objeto puede tener métodos definidos por el programador con los parámetros que sean necesarios.

SOAP

Page 14: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 14

Peticiones HTTP

GETDevuelve un recurso identificado en la URL pedida.

POSTIndica al servidor que se prepare para recibir información del cliente.

PUTEnvía el recurso identificado en la URL desde el cliente hacia el servidor.

DELETESolicita al servidor que borre el recurso identificado con el URL.

Inserción

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) {}

Page 15: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 15

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")) {// Eliminación correcta.

}} catch(Exception ex) {}

Page 16: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 16

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) {}

Page 17: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 17

Demostración

Aplicación de ejemplo “Inventarios”

Mas posibilidades

Page 18: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 18

Tecnología NFC

Se comunica mediante inducción en un campo magnético, esta tecnología inalámbrica trabaja en la banda de los 13,56Mhz y por ello no tiene restricciones ni requiere una licencia para su uso.

Tecnología NFC

Alcance máximo

20 cm

Taza de transferencia

424 Kbps

Page 19: Curso de Desarrollo en android

UMSA-PGI 27/10/2012

CURSO DE DESARROLLO DE APLICACIONES ANDROID 19

Tecnología NFC

Google Wallet

UMSA-PGIwww.pgi.umsa.bo