Curso de Android

De WikiEducator
Saltar a: navegación, buscar


Habilitar el modo de depuración por USB: Esta opción es una casilla que debéis marcar en "Ajustes->Aplicaciones->Depuración USB". A partir de ahora deberíamos acostumbrar-nos a tener siempre esta casilla marcada, ya que en caso de problemas con esta modalidad funcionando podremos conectarnos al aparato mediante el programa ADB para intentar salvar el dispositivo.

What is adb?

ADB ("adb"), or the Android Debug Bridge, is a development tool included with the Android SDK (Software Developer Kit), which allows for communication from an Android device (such as a phone or tablet) to a personal computer, and vice-versa. This communication can be made over a wifi connection. However more commonly, it is made via a USB cable. adb can also be used by developers for communicating from a computer to a virtual android machine that is also running on the computer.

adb is the "Swiss-army knife" of Android development. It provides numerous functions that can be accessed in detail via the command: adb --help

Popular adb commands

Among the most popular among CyanogenMod include the following, which can be typed from a Terminal program on the attached computer:

  • adb shell -- this command establishes a shell interface for establishing a command-line session with the device. In practical purposes, this allows a person to type "into" their devices, much as one would use a terminal program a Linux or Mac OS X. Individual shell commands can be sent to the device by typing adb shell <command_to_be_executed_on_the_device>
  • adb push <local> <remote> -- this command pushes a local file on the computer to a remote file on the device. You can include the full path to either the local or remote file.
  • adb pull <remote> [<local>] -- this command will pull a remote file on the device (you can include the path) to either a specified location on the computer or, if no destination is specified, to the current directory where the command was issued.
  • adb install <file> -- this is used to "side-load" apps (in their .apk format) to the device.

There are many more useful commands. Check out the full instruction list here.

Downloading and installing adb

Although adb can be downloaded as a simple binary, perhaps the best way to get adb is to install the Android SDK directly from Google. That will ensure that, as adb is updated with the rest of the SDK, you can always have the latest version. adb will be located in the /platform-tools directory inside the SDK directory.

New behavior as of Android 4.2.2

In Android 4.2.2, Google implemented some new security features for using adb. This requires you accept the shell session prompt from within your ROM once past whatever unlock mechanism you use for the lock screen. In order to access your device via adb within a booted ROM, you MUST download the latest Android SDK and kill any existing adb daemon sessions to proceed. Once you receive the prompt on your device, you may check the 'trust this computer' box to not be prompted again when connecting your device to that specific PC.

Troubleshooting adb

Plantilla:Paths

"Device not found" errors

Sometimes adb can't find your device. One solution is to run adb kill-server and then adb start-server as root or Administrator to restart the adb daemon with elevated privileges.

Also, you should make sure that the USB debugging or Android Debug Bridge option (this will vary depending on the version of Android) is checked in the Settings under Developer Options.

Plantilla:Note

Requisitos para usar adb

  • Si lo utilizamos para debuggear una aplicación se debe indicar en el Android Manifest añadiendo android:debuggable="true" al elemento <application>. Eclipse lo hace solo.

Despliegue de aplicaciones a dispositivo físico

A partir de la [1] documentación oficial de Android.
Desplegar una aplicación a un dispositivo físico es un proceso con dos partes:

Configuración del dispositivo

(Configuración de dispositivo físico Android para despliegue de aplicaciones de desarrollo)
  • En Android 4 la habilitación del USB Debug está en Ajustes > Opciones de Desarrollo.
  • Nota: A partir de Android 4.2, las opciones de desarrollo no están visibles por defecto: "To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options."

Configuración del dispositivo

Windows
  • Tendremos que descargar el driver adb para el dispositivo.
  • Puedes encontrar un driver genérico que se encuentra en la carpeta android-sdk-windows\usb_driver del SDK Android. Aunque lo más probable es que tengas que utilizar el driver del fabricante.
  • En la web de Android hay un listado de enlaces para la descarga de los drivers de los principales fabricantes.
  • Para los que no aparecen habrá que ir a sus webs o contactar con su servicio de soporte.
  • A veces también hace falta otro ejecutable adb distinto al que aparece en el Android SDK.
  • No siempre existen los drivers o funcionan como debieran ¡ojo!
Mac
  • No hace falta hacer nada. Filosofia MAC: O funciona directamente o no funciona.
Ubuntu
  • Tendremos que añadir el fichero 51-android.rules con los permisos y texto que figura a continuación:
root@juanda-PC:/etc/udev/rules.d# ls -l 51-android.rules 
-rw-r--r-- 1 root root 76 feb 24 11:33 51-android.rules
root@juanda-PC:/etc/udev/rules.d# cat 51-android.rules 
SUBSYSTEM=="usb", ATTR{idVendor}=="ID_DISPOSITIVO", MODE="0666", GROUP="plugdev"
root@juanda-PC:/etc/udev/rules.d#
  • Tendremos que conocer el identificador del dispositivo (ID_DISPOSITIVO), así que conectamos el dispositivo y observamos las trazas del fichero de logs del sistema:
tail -100f /var/log/syslog
Feb 24 11:12:27 juanda-PC kernel: [ 1918.767308] usb 3-1: new high-speed USB device number 6 using xhci_hcd
Feb 24 11:12:27 juanda-PC mtp-probe: checking bus 3, device 6: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-1"
Feb 24 11:12:27 juanda-PC kernel: [ 1918.784245] usb 3-1: ep 0x81 - rounding interval to 32768 microframes, ep desc says 0 microframes
Feb 24 11:12:27 juanda-PC kernel: [ 1918.784252] usb 3-1: ep 0x83 - rounding interval to 32768 microframes, ep desc says 0 microframes
Feb 24 11:12:27 juanda-PC kernel: [ 1918.784256] usb 3-1: ep 0x4 - rounding interval to 32768 microframes, ep desc says 0 microframes
Feb 24 11:12:27 juanda-PC kernel: [ 1918.784796] scsi11 : usb-storage 3-1:1.0
Feb 24 11:12:27 juanda-PC mtp-probe: bus: 3, device: 6 was not an MTP device
Feb 24 11:12:28 juanda-PC kernel: [ 1919.781950] scsi 11:0:0:0: Direct-Access     Linux    File-CD Gadget   0000 PQ: 0 ANSI: 2
Feb 24 11:12:28 juanda-PC kernel: [ 1919.782212] scsi 11:0:0:1: Direct-Access     Linux    File-CD Gadget   0000 PQ: 0 ANSI: 2
Feb 24 11:12:28 juanda-PC kernel: [ 1919.782607] sd 11:0:0:0: Attached scsi generic sg8 type 0
  • De las trazas observamos que el dispositivo se conecta como bus:3, device: 6
  • Ejecutamos lsusb para ver el vendor id del dispositivo, en nuestro caso 2207:0010:
juanda@juanda-PC:/etc/udev$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 003: ID 413c:2111 Dell Computer Corp. 
Bus 001 Device 004: ID 046d:c063 Logitech, Inc. DELL Laser Mouse
Bus 004 Device 002: ID 059f:104a LaCie, Ltd 
Bus 002 Device 003: ID 058f:6362 Alcor Micro Corp. Flash Card Reader/Writer
Bus 001 Device 006: ID 0cf3:e004 Atheros Communications, Inc. 
Bus 003 Device 006: ID 2207:0010
  • Actualizamos el fichero anterior:
juanda@juanda-PC:/etc/udev/rules.d$ cat 51-android.rules 
SUBSYSTEM=="usb", ATTR{id_vendor}=="2207", MODE="0666", GROUP="plugdev"
  • Para comprobar si todo hay ido bien, se puede hacer desde la línea de comandos:
  • Reiniciamos el servicio de udev:
juanda@juanda-PC:/etc/udev/rules.d$ sudo service udev restart
udev stop/waiting
udev start/running, process 9069
juanda@juanda-PC:/etc/udev/rules.d$
  • Paramos y arrancamos adb (android device bridge) y comprobamos la lista de dispositivos:
juanda@juanda-PC:/etc/udev/rules.d$ adb kill-server
juanda@juanda-PC:/etc/udev/rules.d$ adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
juanda@juanda-PC:/etc/udev/rules.d$ adb devices
List of devices attached 
emulator-5554	device
  • Es útil poner los comandos más habituales dentro del PATH:
juanda@juanda-PC:~$ cat .bashrc|grep -i PATH
PATH=$PATH:$HOME/Android/sdk/tools:$HOME/Android/sdk/platform-tools

Indicar que queremos desplegarlo en el dispositivo al ejecutar la aplicación

  • Cuando ejecutemos la aplicación veremos una pantalla similar a la siguiente:
Eclipse->Windows->Open Perspective->DDMS
  • Aparecerán los emuladores que tengamos corriendo y los dispositivos físicos que estén enchufados a la entrada USB del PC
  • En caso de tener un solo dispositivo disponible esta pantalla no aparecerá.

Error en funcionamiento de dispositivos físicos y emuladores

  • El error es el siguiente:
[2013-02-22 13:55:20 - adb] Unexpected exception 'Cannot run program "/home/juanda/Android/sdk/platform-tools/adb": java.io.IOException: error=2, No existe el archivo o el directorio' while attempting to get adb version from '/home/juanda/Android/sdk/platform-tools/adb'
  • Solución, instalar los siguientes paquetes:
sudo apt-get update
sudo apt-get install ia32-libs






Problema con libncurses.so.5 64-bit

Under 64bits version of Linux Mint 14 and maybe other Debian/Ubuntu flavours adb shows the following error:

./adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory

You can solve it by installing libncurses5 i386's version. Just type apt-get install libncurses5:i386 as root.

adb vía wifi

To update ADB use SDK Manager.

For some reason the SDK Manager does not automatically show the new release versions of Android SDK Tools and Android Platform-Tools, so if the versions of your Android SDK Tools and/or Android Platform-Tools are respectively older than 21.1 and 16.0.1, you will need to first delete them then reload the SDK Manager to get their new release versions to be displayed and available for installation.

Also, it appears that Android Support Libraries (under Extra) is also required for ADB to work, so you should install it as well.

Also, to get ADB-over-WiFi to work, first use ADB-over-USB to the same given PC/Laptop and grant access with "always" box checked.


Comandos habituales de Linux en Android

  • netcfg ->ifconfig

Actualización fichero /etc/hosts

  • Realmente el fichero está en /system/etc/hosts, pero en /etc hay un enlace duro.
  • Obtenemos el fichero hosts del movil:
juanda@dpto-01:~/Android/sdk/tools$ adb pull /etc/hosts
0 KB/s (25 bytes in 0.038s)
juanda@dpto-01:~/Android/sdk/tools$ cat hosts
127.0.0.1		    localhost

Lo modificamos:

juanda@dpto-01:~/Android/sdk/tools$ vi hosts 
juanda@dpto-01:~/Android/sdk/tools$ cat hosts
127.0.0.1    localhost
192.168.1.1  incidencias.jd  www.incidencias.jd
192.168.1.1  spp.jd  www.spp.jd
juanda@dpto-01:~/Android/sdk/tools$ adb push hosts /etc/hosts
failed to copy 'hosts' to '/etc/hosts': Read-only file system
juanda@dpto-01:~/Android/sdk/tools$
  • En muchos dispositivos la partición /system se monta como solo lectura así que hay que montarla con permisos de escritura.
  • A continuación todas las trazas al cambiarlo en mi sistema:
juanda@dpto-01:~/Android/sdk/tools$ adb shell
shell@android:/ $ su -
shell@android:/ # mount -o rw,remount /system                              
shell@android:/ # exit
shell@android:/ $ exit
juanda@dpto-01:~/Android/sdk/tools$ adb push hosts /etc/hosts
failed to copy 'hosts' to '/etc/hosts': Permission denied
juanda@dpto-01:~/Android/sdk/tools$ adb shell
shell@android:/ $ cd etc
shell@android:/etc $ su - 
shell@android:/system/etc # chmod 777 hosts
shell@android:/system/etc # exit
shell@android:/etc $ exit
juanda@dpto-01:~/Android/sdk/tools$ adb push hosts /etc/hosts
2 KB/s (103 bytes in 0.040s)
juanda@dpto-01:~/Android/sdk/tools$ adb shell
shell@android:/ $ su -
shell@android:/ # cd etc 
shell@android:/etc # chmod 644 hosts
shell@android:/etc # ls -l hosts
-rw-r--r-- root     root          103 2013-04-12 13:00 hosts
shell@android:/etc # mount -o ro,remount /system
shell@android:/etc # cat hosts
127.0.0.1    localhost
192.168.1.1  incidencias.jd  www.incidencias.jd
192.168.1.1  spp.jd  www.spp.jd
shell@android:/etc #