O que é ADB e como instala-lo?

O que é ABD ?

ADB significa Android Debug Bridge, ele vem de uma parte do Android SDK. Básicamente ele dá acesso a uma interface via terminal para integração entre o usuário e o sistema de arquivo do telefone. Como o Android é baseado em Linux as vezes é necessário acessar o aparelho via linha de comando para executar certas operações avançadas em seu aparelho com root.
É possível executar esses comandos via alguns aplicativos existentes no próprio Market mas é bem complexo executar esses comandos em uma telinha pequena como a do celular. O ADB é a interface entre seu computador e o seu celular.

Como Instalar o ADB?

Downloads necessários:

SDK Android SDK Manager v20.0.3
http://www.telecelula.com.br/new/suporte_download_arquivo.asp?seguro=4EDA5332C26714999

Passo 1 Instalar o Android SDK

Instalar o Android SDK verifique o link acima para baixar o arquivo em nossa área de download caso nao tenha acesso a nossa área de download acesse: https://www.telecelula.com.br/new/download_Assinar.asp .Há versões para Windows, Linux e MacOS X. O arquivo disponibilizado acima é do Windows. Após o download do SDK, descompacte o arquivo baixado em seu computador, no nosso caso vamos descompactar na raiz do nosso C: e ele ficará em: C:\android-sdk-windows.

Passo 2 Baixando as SDK Platform Tools

Antigamente o ADB já vinha com o SDK platform tools por padrão em uma pasta chamada “tools” mas agora foi realocado para a subpasta “platform-tools” e precisa ser baixado como um pacote SDK

Vá até a pasta do SDK (C:\android-sdk-windows) e execute o arquivo SDK Manager (é importante estar conectado a internet). Quando executar esse arquivo pela primeira vez, aparecerá uma janela para escolher alguns pacotes para instalação. A primeira opção é “Android SDK Platform-tools”, marque-a e DESmarque todos os outros pacotes abaixo. Para marcar/desmarcar um pacote basta clicar sobre ele e depois clicar na opção Accept para instalar ou Reject para não instalar.

Depois de selecionar o “Android SDK Platform-tools” clique em install e o pacote será instalado. Assim que o processo terminar você terá a pasta “platform-tools”dentro da pasta do SDK (C:\android-sdk-windows). Essa pasta tem o ADB e suas dependencias.

Passo 3
Adicionando o local do ADB como variável

Agora que o ADB foi instalado é necessário configurar o local onde ele está como uma variavel de ambiente pois assim você não precisa entrar na pasta C:\android-sdk-windows\platform-tools\adb toda vez que for usar o ADB. Vou descrever apenas o método para o windows pois presumo que seja o sistema que a maioria use no fórum.

No Windows 7 clique no “Windows ORB” ou no símbolo do windows do lado inferior esquerdo da tela, depois clique com o botão direito sobre o ícone “Computador” e depois clique em “Propriedades”. Nas opções do lado esquerdo clique em “Configuração avançada de Sistemas”, no windows XP é só clicar com o botão direito sobre o “Meu Computador” e depois em propriedades.

Na janela que se abrir há uma aba chamada avançada, clique nela e depois há um botão no canto inferior direito da janela chamado “Variáveis de ambiente…” clique sobre ele.

Uma nova janela abrirá, na parte de baixo, em Variáveis de Sistema, procure pela variável Path e de um duplo clique nela.

Uma nova janela abrirá, NÃO DELETE nada que está lá, isso pode trazer MUITOS problemas para seu windows.

Vá até o final do campo “Valor da Variável” e ADICIONE a seguinte linha:

;c:\android-sdk-windows\tools;c:\android-sdk-windows\platform-tools

Passo 4 – Instalando os drivers USB

Primeiro temos que baixar os drives USB, para isso é necessário abrir novamente o SDK Manager que está na pasta SDK e em seguida clicar em “Available Packages” no lado esquerdo da janela

Expanda a opção “Third party Add-ons” e depois a opção “Google Inc. add-ons” e marque a opção “Google Usb Driver package, revision” Ondeé a revisão pertinente a aplicação SDK, a atual é 4.

Clique em “Install Selected” e uma nova janela aparecerá, clique em “Accept all” e depois no botão “install”. Aguarde enquanto os drivers são baixados e instalados.

Os drives USB estarão na pasta “c:\android-sdk-windows\extras\google\usb_driver\“.

Os drivers foram baixados e estão prontos para serem instalados. Você pode instala-los em sua máquina da seguinte forma:

• No aparelho, na tela inicial, aperte menu, selecione aplicações e depois Desenvolvimento, habilite a opção Depuração USB

• Conecte seu aparelho no PC via USB e o windows iniciará uma instalação de um novo hardware. Caso ele não encontre automáticamente os drivers, faça-o procurar os drivers na pasta onde foram baixados (c:\android-sdk-windows\usb_driver) e aguarde a instalação

• Assim que os drivers forem instalados você terá uma interface ADB instalada no seu gerenciador de dispositivos Como utilizar o ADB

Como utilizar o ADB

Se você seguiu tudo conforme descrito acima e não teve nenhum erro está tudo pronto para a utilização do ADB para manipular seu telefone. A melhor forma de mexer com o ADB é pela linha de comando, para certificar-se de que o ADB está instalado corretamente entre no prompt de comando com o seu telefone plugado no computador, digite “adb devices” e pressione enter aparecerá abaixo o serial number do aparelho.

TABELA DE COMANDOS

Table 1. Available adb commands

Category Command Description Comments
Target Device -d Direct an adb command to the only attached USB device. Returns an error if more than one USB device is attached.
-e Direct an adb command to the only running emulator instance. Returns an error if more than one emulator instance is running.
-s serial_number Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as “emulator-5556”). See Directing Commands to a Specific Emulator/Device Instance.
General devices Prints a list of all attached emulator/device instances. See Querying for Emulator/Device Instances for more information.
help Prints a list of supported adb commands.
version Prints the adb version number.
Debug logcat [option] [filter-specs] Prints log data to the screen.
bugreport Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting.
jdwp Prints a list of available JDWP processes on a given device. You can use the forward jdwp:pid port-forwarding specification to connect to a specific JDWP process. For example:
adb forward tcp:8000 jdwp:472
jdb -attach localhost:8000
Data install path_to_apk Pushes an Android application (specified as a full path to an APK file) to an emulator/device.
pull remote local Copies a specified file from an emulator/device instance to your development computer.
push local remote Copies a specified file from your development computer to an emulator/device instance.
Ports and Networking forward local remote Forwards socket connections from a specified local port to a specified remote port on the emulator/device instance. Port specifications can use these schemes:

  • tcp:port_number
  • local:unix_domain_socket_name
  • dev:character_device_name
  • jdwp:pid
ppp tty [parm]... Run PPP over USB.

  • tty — the tty for PPP stream. For example dev:/dev/omap_csmi_ttyl.
  • [parm]... — zero or more PPP/PPPD options, such as defaultroute, local, notty, etc.

Note that you should not automatically start a PPP connection.

Scripting get-serialno Prints the adb instance serial number string. See Querying for Emulator/Device Instances for more information.
get-state Prints the adb state of an emulator/device instance.
wait-for-device Blocks execution until the device is online — that is, until the instance state is device. You can prepend this command to other adb commands, in which case adb will wait until the emulator/device instance is connected before issuing the other commands. Here’s an example:

adb wait-for-device shell getprop

Note that this command does not cause adb to wait until the entire system is fully booted. For that reason, you should not prepend it to other commands that require a fully booted system. As an example, the install requires the Android package manager, which is available only after the system is fully booted. A command such as

adb wait-for-device install app.apk

would issue the install command as soon as the emulator or device instance connected to the adb server, but before the Android system was fully booted, so it would result in an error.

Server start-server Checks whether the adb server process is running and starts it, if not.
kill-server Terminates the adb server process.
Shell shell Starts a remote shell in the target emulator/device instance. See Issue shell commands for more information.
shell shell_command Issues a shell command in the target emulator/device instance and then exits the remote shell.

Issue shell commands


You can use the shell command to issue device commands through adb, with or without entering the adb remote shell on the emulator/device. To issue a single command without entering a remote shell, use the shell command like this:

adb [-d|-e|-s serial_number] shell shell_command

Or enter a remote shell on an emulator/device like this:

adb [-d|-e|-s serial_number] shell

When you are ready to exit the remote shell, press Control + D or type exit.

The shell command binaries are stored in the file system of the emulator or device, at /system/bin/.

Call activity manager (am)

Within an adb shell, you can issue commands with the activity manager (am) tool to perform various system actions, such as start an activity, force-stop a process, broadcast an intent, modify the device screen properties, and more. While in a shell, the syntax is:

am command

You can also issue an activity manager command directly from adb without entering a remote shell. For example:

adb shell am start -a android.intent.action.VIEW

Table 2. Available activity manager commands

Command Description
start [options] intent Start an Activity specified by intent.See the Specification for intent arguments.

Options are:

  • -D: Enable debugging.
  • -W: Wait for launch to complete.
  • --start-profiler file: Start profiler and send results to file.
  • -P file: Like --start-profiler, but profiling stops when the app goes idle.
  • -R count: Repeat the activity launch count times. Prior to each repeat, the top activity will be finished.
  • -S: Force stop the target app before starting the activity.
  • --opengl-trace: Enable tracing of OpenGL functions.
  • --user user_id | current: Specify which user to run as; if not specified, then run as the current user.
startservice [options] intent Start the Service specified by intent.See the Specification for intent arguments.

Options are:

  • --user user_id | current: Specify which user to run as; if not specified, then run as the current user.
force-stop package Force stop everything associated with package (the app’s package name).
kill [options] package Kill all processes associated with package (the app’s package name). This command kills only processes that are safe to kill and that will not impact the user experience.Options are:

  • --user user_id | all | current: Specify user whose processes to kill; all users if not specified.
kill-all Kill all background processes.
broadcast [options] intent Issue a broadcast intent.See the Specification for intent arguments.

Options are:

  • [--user user_id | all | current]: Specify which user to send to; if not specified then send to all users.
instrument [options] component Start monitoring with an Instrumentation instance. Typically the target component is the form test_package/runner_class.Options are:

  • -r: Print raw results (otherwise decode report_key_streamresult). Use with [-e perf true] to generate raw output for performance measurements.
  • -e name value: Set argument name to value. For test runners a common form is -e testrunner_flagvalue[,value...].
  • -p file: Write profiling data to file.
  • -w: Wait for instrumentation to finish before returning. Required for test runners.
  • --no-window-animation: Turn off window animations while running.
  • --user user_id | current: Specify which user instrumentation runs in; current user if not specified.
profile start process file Start profiler on process, write results to file.
profile stop process Stop profiler on process.
dumpheap [options] process file Dump the heap of process, write to file.Options are:

  • --user [user_id|current]: When supplying a process name, specify user of process to dump; uses current user if not specified.
  • -n: Dump native heap instead of managed heap.
set-debug-app [options] package Set application package to debug.Options are:

  • -w: Wait for debugger when application starts.
  • --persistent: Retain this value.
clear-debug-app Clear the package previous set for debugging with set-debug-app.
monitor [options] Start monitoring for crashes or ANRs.Options are:

  • --gdb: Start gdbserv on the given port at crash/ANR.
screen-compat {on|off} package Control screen compatibility mode of package.
display-size [reset|widthxheight] Override emulator/device display size. This command is helpful for testing your app across different screen sizes by mimicking a small screen resolution using a device with a large screen, and vice versa.Example:
am display-size 1280x800
display-density dpi Override emulator/device display density. This command is helpful for testing your app across different screen densities on high-density screen environment using a low density screen, and vice versa.Example:
am display-density 480
to-uri intent Print the given intent specification as a URI.See the Specification for intent arguments.
to-intent-uri intent Print the given intent specification as an intent: URI.See the Specification for intent arguments.

Call package manager (pm)

Within an adb shell, you can issue commands with the package manager (pm) tool to perform actions and queries on application packages installed on the device. While in a shell, the syntax is:

pm command

You can also issue a package manager command directly from adb without entering a remote shell. For example:

adb shell pm uninstall com.example.MyApp

Table 3. Available package manager commands.

Command Description
list packages [options] filter Prints all packages, optionally only those whose package name contains the text in filter.Options:

  • -f: See their associated file.
  • -d: Filter to only show disabled packages.
  • -e: Filter to only show enabled packages.
  • -s: Filter to only show system packages.
  • -3: Filter to only show third party packages.
  • -i: See the installer for the packages.
  • -u: Also include uninstalled packages.
  • --user user_id: The user space to query.
list permission-groups Prints all known permission groups.
list permissions [options] group Prints all known permissions, optionally only those in group.Options:

  • -g: Organize by group.
  • -f: Print all information.
  • -s: Short summary.
  • -d: Only list dangerous permissions.
  • -u: List only the permissions users will see.
list instrumentation [options] List all test packages.Options:

  • -f: List the APK file for the test package.
  • target_package: List test packages for only this app.
list features Prints all features of the system.
list libraries Prints all the libraries supported by the current device.
list users Prints all users on the system.
path package Print the path to the APK of the given package.
install [options] path Installs a package (specified by path) to the system.Options:

  • -l: Install the package with forward lock.
  • -r: Reinstall an existing app, keeping its data.
  • -t: Allow test APKs to be installed.
  • -i installer_package_name: Specify the installer package name.
  • -s: Install package on the shared mass storage (such as sdcard).
  • -f: Install package on the internal system memory.
  • -d: Allow version code downgrade.
  • -g: Grant all permissions listed in the app manifest.
uninstall [options] package Removes a package from the system.Options:

  • -k: Keep the data and cache directories around after package removal.
clear package Deletes all data associated with a package.
enable package_or_component Enable the given package or component (written as “package/class”).
disable package_or_component Disable the given package or component (written as “package/class”).
disable-user [options] package_or_component Options:

  • --user user_id: The user to disable.
grant package_name permission Grant a permission to an app. On devices running Android 6.0 (API level 23) and higher, may be any permission declared in the app manifest. On devices running Android 5.1 (API level 22) and lower, must be an optional permission defined by the app.
revoke package_name permission Revoke a permission from an app. On devices running Android 6.0 (API level 23) and higher, may be any permission declared in the app manifest. On devices running Android 5.1 (API level 22) and lower, must be an optional permission defined by the app.
set-install-location location Changes the default install location. Location values:

  • 0: Auto—Let system decide the best location.
  • 1: Internal—install on internal device storage.
  • 2: External—install on external media.

Note: This is only intended for debugging; using this can cause applications to break and other undesireable behavior.

get-install-location Returns the current install location. Return values:

  • 0 [auto]: Lets system decide the best location
  • 1 [internal]: Installs on internal device storage
  • 2 [external]: Installs on external media
set-permission-enforced permission[true|false] Specifies whether the given permission should be enforced.
trim-caches desired_free_space Trim cache files to reach the given free space.
create-user user_name Create a new user with the given user_name, printing the new user identifier of the user.
remove-user user_id Remove the user with the given user_id, deleting all data associated with that user
get-max-users Prints the maximum number of users supported by the device.

Take a screenshot

The screencap command is a shell utility for taking a screenshot of a device display. While in a shell, the syntax is:

screencap filename

To use the screencap from the command line, type the following:

$ adb shell screencap /sdcard/screen.png

Here’s an example screenshot session, using the adb shell to capture the screenshot and the pull command to download the file from the device:

$ adb shell
shell@ $ screencap /sdcard/screen.png
shell@ $ exit
$ adb pull /sdcard/screen.png

Record a video

The screenrecord command is a shell utility for recording the display of devices running Android 4.4 (API level 19) and higher. The utility records screen activity to an MPEG-4 file.

Note: Audio is not recorded with the video file.

A developer can use this file to create promotional or training videos. While in a shell, the syntax is:

screenrecord [options] filename

To use screenrecord from the command line, type the following:

$ adb shell screenrecord /sdcard/demo.mp4

Stop the screen recording by pressing Control + C, otherwise the recording stops automatically at three minutes or the time limit set by --time-limit.

To begin recording your device screen, run the screenrecord command to record the video. Then, run the pull command to download the video from the device to the host computer. Here’s an example recording session:

$ adb shell
shell@ $ screenrecord --verbose /sdcard/demo.mp4
(press Control + C to stop)
shell@ $ exit
$ adb pull /sdcard/demo.mp4

The screenrecord utility can record at any supported resolution and bit rate you request, while retaining the aspect ratio of the device display. The utility records at the native display resolution and orientation by default, with a maximum length of three minutes.

There are some known limitations of the screenrecord utility that you should be aware of when using it:

  • Some devices may not be able to record at their native display resolution. If you encounter problems with screen recording, try using a lower screen resolution.
  • Rotation of the screen during recording is not supported. If the screen does rotate during recording, some of the screen is cut off in the recording.

Table 4. screenrecord options

Options Description
--help Displays command syntax and options
--size widthxheight Sets the video size: 1280x720. The default value is the device’s native display resolution (if supported), 1280×720 if not. For best results, use a size supported by your device’s Advanced Video Coding (AVC) encoder.
--bit-rate rate Sets the video bit rate for the video, in megabits per second. The default value is 4Mbps. You can increase the bit rate to improve video quality, but doing so results in larger movie files. The following example sets the recording bit rate to 6Mbps:

screenrecord --bit-rate 6000000 /sdcard/demo.mp4
--time-limit time Sets the maximum recording time, in seconds. The default and maximum value is 180 (3 minutes).
--rotate Rotates the output 90 degrees. This feature is experimental.
--verbose Displays log information on the command-line screen. If you do not set this option, the utility does not display any information while running.

Read ART profiles for apps

Starting in Android 7.0 (API level 24) the Android Runtime (ART) collects execution profiles for installed apps, which are used to optimize app performance. You might want to examine the collected profiles to understand which methods are determined to be frequently executed and which classes are used during app startup.

To produce a text form of the profile information, use the command:

$ adb shell cmd package dump-profiles package

To retrieve the file produced, use:

$ adb pull /data/misc/profman/package.txt

Other shell commands

For a list of all the available shell programs, use the following command:

adb shell ls /system/bin

Help is available for most of the commands.

Table 5 lists some of the more common adb shell commands.

Table 5. Some other adb shell commands

Shell Command Description Comments
dumpsys Dumps system data to the screen. The Dalvik Debug Monitor Server (DDMS) tool offers an integrated debug environment that you may find easier to use.
dumpstate Dumps state to a file.
logcat [option]... [filter-spec]... Enables system and app logging and prints output to the screen.
dmesg Prints kernel debugging messages to the screen.
start Starts (restarts) an emulator/device instance.
stop Stops execution of an emulator/device instance.

 

Deixe um comentário