Curso para adquirir las capacidades necesarias para desarrollar bajo la plataforma Android.
Para más información, visita nuestra página web en:
http://www.slashmobility.com
4. Introducción a Android: releases Versión Android Fecha release Android 1.5 (Cupcake) 30 abril de 2009 Android 1.6 (Donut) 15 septiembre de 2009 Android 2.0 (Eclair) 26 octubre de 2009 Android 2.2 (FroYo) Mayo de 2010 Gingerbread Finales de 2010
5. Introducción a Android: un poco de historia (II) Prototipo HTC Dream Nexus One Xperia x10 HTC Liquid GeeksPhone Samsung I7500
20. Arquitectura de las aplicaciones: Componentes de aplicación Principales componentes para el desarrollo de aplicaciones en Android:
21.
22.
23.
24.
25.
26.
27. Services: control de los servicios Para iniciar un servicio: startService(new Intent(MyService.MY_ACTION)); Para parar un servicio iniciado: ComponentName service = startService(new Intent(this, BaseballWatch.class)); // Stop a service using the service name. stopService(new Intent(this, service.getClass()));
30. Para recuperar todos los registros: Cursor allRows = getContentResolver().query(MyProvider.CONTENT_URI, null, null, null, null); Para consultar todos los registros tales que la columna KEY_COL3 tiene un determinado valor, y ordenada por la columna KEY_COL5: String where = KEY_COL3 + “=” + requiredValue; String order = KEY_COL5; Cursor someRows = getContentResolver().query(MyProvider.CONTENT_URI, null, where, null,order); Content Providers: consultas
48. En el código de la Activity, se crea el contenido a partir de un recurso XML: public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); //recurso main.xml, añade una vista con un widget TextView ... TextView myTextView = (TextView)findViewById(R.id.myTextView); //Podemos acceder al TextView buscándolo por Id, ahora podemos trabajar con el } Interfaces de usuario: Creación de vista por XML
49. Interfaces de usuario: Creación de vista por XML (II) En el archivo /res/layout/main.xml: < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > <!-- crea un layout con la distribución de los elementos visuales --> < TextView android:id = "@+id/myTestView" android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:src = "@drawable/jupiter" /> <!-- crea un widget TextView --> </ LinearLayout >
50.
51.
52.
53.
54. Interfaces de usuario: componentes compuestos (II) TextView EditText con un Button ListView Spinner
58. /* Creates the menu items */ public boolean onCreateOptionsMenu(Menu menu ) { menu.add(0, MENU_NEW_GAME , 0, "New Game" ); menu.add(0, MENU_QUIT , 0, "Quit" ); return true ; } /* Handles item selections */ public boolean onOptionsItemSelected(MenuItem item ) { switch (item.getItemId()) { case MENU_NEW_GAME : newGame (); return true ; case MENU_QUIT : quit (); return true ; } return false ; } Menus: Options Menu (II) Creación de Option Menu vía código:
59.
60. Menus: Context Menu (II) public void onCreateContextMenu(ContextMenu menu , View v , ContextMenuInfo menuInfo ) { super .onCreateContextMenu(menu, v, menuInfo); menu.add(0, EDIT_ID , 0, "Edit" ); menu.add(0, DELETE_ID , 0, "Delete" ); } public boolean onContextItemSelected(MenuItem item ) { AdapterContextMenuInfo info = ( AdapterContextMenuInfo ) item.getMenuInfo(); switch (item.getItemId()) { case EDIT_ID : editNote(info.id); return true ; case DELETE_ID : deleteNote(info.id); return true ; default : return super .onContextItemSelected(item); } } Creación de Context Menu vía código:
61.
62. Menus: Submenus (II) public boolean onCreateOptionsMenu(Menu menu ) { boolean result = super .onCreateOptionsMenu(menu); SubMenu fileMenu = menu.addSubMenu( "File" ); SubMenu editMenu = menu.addSubMenu( "Edit" ); fileMenu.add( "new" ); fileMenu.add( "open" ); fileMenu.add( "save" ); editMenu.add( "undo" ); editMenu.add( "redo" ); return result; } Creación de SubMenu vía código:
63.
64.
65.
66.
67.
68. Entorno de desarrollo: Hello Android! package com.android.helloandroid; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello, Android"); setContentView(tv); } }
69.
70.
71.
72.
73. Almacenamiento de datos: Preferences (II) import android.app.Activity; import android.content.SharedPreferences; public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile" ; . . . @ Override protected void onCreate(Bundle state) { super .onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean( "silentMode" , false ); setSilent (silent); } @Override protected void onStop(){ super .onStop(); // Save user preferences. We need an Editor object to // make changes. All objects are from android.context.Context SharedPreferences settings = getSharedPreferences( PREFS_NAME , 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean( "silentMode" , mSilentMode ); // Don't forget to commit your edits!!! editor.commit(); } }
74.
75.
76.
77.
78. Almacenamiento de datos: SQLite creación de tablas private static final String DATABASE_NAME = “myDatabase.db”; private static final String DATABASE_TABLE = “mainTable”; private static final String DATABASE_CREATE = “ create table “ + DATABASE_TABLE + “ ( _id integer primary key autoincrement,” + “column_one text not null );”; SQLiteDatabase myDatabase; private void createDatabase() { myDatabase = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null ); myDatabase.execSQL(DATABASE_CREATE); }
79. Almacenamiento de datos: SQLite querys // Return all rows for columns one and three, no duplicates String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3}; Cursor allRows = myDatabase.query( true , DATABASE_TABLE, result_columns, null , null , null , null , null , null ); // Return all columns for rows where column 3 equals a set value // and the rows are ordered by column 5. String where = KEY_COL3 + “=” + requiredValue; String order = KEY_COL5; Cursor myResult = myDatabase.query(DATABASE_TABLE, null , where, null , null , null , order);
80. Almacenamiento de datos: SQLite resultados int GOLD_HOARDED_COLUMN = 2; Cursor myGold = myDatabase.query(“GoldHoards”, null , null , null , null , null , null ); float totalHoard = 0f; // Make sure there is at least one row. if (myGold.moveToFirst()) { // Iterate over each cursor. do { float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN); totalHoard += hoard; } while (myGold.moveToNext()); } float averageHoard = totalHoard / myGold.getCount();
81. Almacenamiento de datos: SQLite Añadir un nuevo registro // Create a new row of values to insert. ContentValues newValues = new ContentValues(); // Assign values for each row. newValues.put(COLUMN_NAME, newValue); [ ... Repeat for each column ... ] // Insert the row into your table myDatabase.insert(DATABASE_TABLE, null , newValues);
82. Almacenamiento de datos: SQLite Modificar un registro // Define the updated row content. ContentValues updatedValues = new ContentValues(); // Assign values for each row. updatedValues.put(COLUMN_NAME, newValue); [ ... Repeat for each column ... ] String where = KEY_ID + “=” + rowId; // Update the row with the specified index with the new values. myDatabase.update(DATABASE_TABLE, updatedValues, where, null );