Команды adb для Android пользователей. Установка и использование ADB и fastboot. Команды для работы с ADB Версии adb

Инстаграм

Если вы хотите узнать, как пользоваться Adb Run, то, скорее всего, уже знакомы с главной программой - Adb. Если нет, тогда рассмотрим эти два инструмента для пользователей Android. Для чего нужны утилиты, как их настраивать и пользоваться?

Программа

Итак, что же такое Adb? Это программа, которая получила свое название благодаря аббревиатуре. ADB - это Android debug bridge. Инструмент для откладки, поиска неполадок в утилитах, разблокировки гаджетов на этой операционной системе. Это основные возможности программы, но если вы хорошо разбираетесь в этой теме, то узнаете еще с десяток скрытых опций.

Установка

Чтобы понять, как пользоваться Adb Run, нужно установить на ПК ADB. Для этого её необходимо скачать с официального сайта разработчика. В принципе, многие сайты дают возможность загрузить эту утилиту себе на компьютер, поэтому с поиском никаких проблем не возникнет.

Подключение

Чтобы понять, для чего нужна ADB, а соответственно и Adb Run, рассмотрим основные команды. Например, если вы не уверенны, что компьютер правильно видит телефон и будет с ним корректно работать, можете ввести команду adb devices. Так вы сможете убедиться, что подключение стабильное.

После того как вы используете команду, программа выведет сообщение о том, что List of devices attached. Если похожей фразы вы не увидели, то скорее всего проблема либо с кабелем, либо с драйверами. Придется перепроверить работоспособность устройства и выяснить причины того, почему ПК не видит смартфон.

Если вы узнали, что кабель оказался нерабочим, можете попробовать присоединить гаджет через беспроводную сеть. Подключение по Wi-Fi проходит с помощью ADB Wireless. Кроме того, на устройстве должны быть установлены права Root.

После вводим команду adb connect ip:port. Вместо ip:port вводите то значение, которое установлено для адреса вашей сети.

Возможности

Поскольку вопрос о том, как пользоваться Adb Run, связан с использованием ADB, стоит понять, какие же возможности скрывает основная утилита. К примеру, благодаря коду можно установить приложение, которое находится на ПК. Для этого нужно написать adb install, а затем указать путь, где лежит

Точно также можно передать обычный документ с компьютера на телефон. Алгоритм тот же, изменилась только команда. Вводим adb push, а после указываем адрес местоположения файлика, который должен перенестись на гаджет. Если нужно сделать обратную операцию, вводим adb pull. Только первым адресом указывается папка на телефоне, а вторым - место, куда нужно сохранить передаваемый документ на ПК.

Adb Run

Это инструмент, который упрощает работу. Особенно удобно тем, кто поймет, как пользоваться программой Adb Run. Утилита призвана упростить работу с ADB, делает функционал последней программы понятнее. Суть дополнительного инструмента в том, что она автоматизирует обычные пользовательские команды и в разы упрощает действия с консолью. Также Adb Run может сбросить графический ключ.

Выглядит программа как консоль. Состоит из 14 пунктов, а переходы по меню и разделам происходят за счет выбора нужной цифры и кнопки подтверждения Enter.

Подготовка

Прежде чем узнать, как пользоваться Adb Run этой программой, важно помнить об откладке по USB. Об этом шаге часто забывают, после чего программа просто не видит телефон. Чтобы это сделать, нужно перейти в настройки, найти там опцию «О телефоне».

В последних версиях операционной системы нужно найти строчку с серийным номером и несколько раз кликнуть по ней. Внизу появляется уведомление, сначала о том, что вы на правильном пути, после - что вы стали разработчиком. Когда вы увидите такое сообщение, можете возвращаться в настройки, там должен появиться пункт «Параметры разработчика». В нем и можно включить откладку.

Обзор

Небольшой обзор утилиты и то, как пользоваться Adb Run для «Андроид». Сразу первый пункт - это проверка правильности подключения гаджета. Если вы забыли об откладке, то программа сразу же выявит это. Первый пункт называется Device attached. Выбрав его, вы узнаете, подключен ли телефон к системе.

Далее - пункт Move . Вместо того чтобы вводить команды, которые были описаны ранее, достаточно будет выбрать между двумя пунктами. Первый отвечает за передачу файлов с компьютера на телефон, второй - за обратный процесс.

Третий пункт Install отвечает за загрузку приложений на гаджет. Тут доступно пять пунктов. Среди них есть копирование программы, установка обычная или на карту памяти. Есть возможность удалять утилиты с телефона через ПК или перемещать их.

Пункт Reboot перезагружает девайс. Делает это тремя вариантами, среди которых есть обычная перезагрузка, переход в режим загрузчика или к меню Recovery. Следующая строка под пятым номером отвечает за прошивку девайса. Fastboot - это меню, в котором есть 10 пунктов. Причем все они узкоспециальные, если вы не знаете, что нужно выбирать, придется рассматривать каждый подпункт.

В следующем пункте - Unlock Gesture Key - вы можете узнать, как пользоваться Adb Run с Windows 10, если нужно разблокировать графический ключ. Часто пользователи, используя такой метод защиты, забывают его, но когда случаются сбои, на помощь приходит именно эта утилита. В шестом меню указаны пункты с разными вариантами графического ключа. Нужно выбрать тот, который вы забыли.

Пункт семь - Manual - нужен тем, кто хочет самостоятельно вводить команды. Возможно есть такие директивы, которых нет в списке представленных. Для этого и нужен этот пункт меню. Тут же есть специальное меню для владельцев смартфонов HTC. В нем можно разблокировать Bootloader, сменить CID и получить S-OFF.

Восьмой пункт проверяет обновления утилиты. Девятый - творческий вариант для тех, кто устал от анимации при включении устройства. Если вы хотите заменить её или отключить, то вам нужно в меню Intsall Bootanimation.

Десятый пункт дает информацию о всех существующих блоках устройства. Тут есть разделы, возможно, скрытые, либо те, до которых трудно добраться. Run Script - это одиннадцатое меню для использования скриптов. Backup - пункт двенадцатый, который создает резервную копию гаджета всего. Удобно, если нужно сделать Reboot.

Следующее меню отвечает за odex-ирование прошивки. Если вам неизвестен этот процесс, лучше самостоятельно не экспериментировать. Четырнадцатый пункт работает над скриншотами. Последнее меню нужен для выхода из утилиты.

Выводы

Как пользоваться Adb Run на Windows XP, понятно. Разницы с тем, как работает эта программа на Windows 7 или 10, вообще нет. Поэтому проблем никаких возникнуть не должно. Вышеописанная инструкция подходит на все случаи жизни.

Для владельцев Linux тоже есть свой вариант, который легко использовать. Нужно просто установить специальную версию.

Android Debug Bridge (adb) is a versatile command-line tool that lets you communicate with a device. The adb command facilitates a variety of device actions, such as installing and debugging apps, and it provides access to a Unix shell that you can use to run a variety of commands on a device. It is a client-server program that includes three components:

  • A client , which sends commands. The client runs on your development machine. You can invoke a client from a command-line terminal by issuing an adb command.
  • A daemon (adbd) , which runs commands on a device. The daemon runs as a background process on each device.
  • A server , which manages communication between the client and the daemon. The server runs as a background process on your development machine.

adb is included in the Android SDK Platform-Tools package. You can download this package with the SDK Manager , which installs it at android_sdk /platform-tools/ . Or if you want the standalone Android SDK Platform-Tools package, you can .

For information on connecting a device for use over ADB, including how to use the Connection Assistant to troubleshoot common problems, see Run apps on a hardware device .

How adb works

When you start an adb client, the client first checks whether there is an adb server process already running. If there isn"t, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.

The server then sets up connections to all running devices. It locates emulators by scanning odd-numbered ports in the range 5555 to 5585, the range used by the first 16 emulators. Where the server finds an adb daemon (adbd), it sets up a connection to that port. Note that each emulator uses a pair of sequential ports — an even-numbered port for console connections and an odd-numbered port for adb connections. For example:

Emulator 1, console: 5554
Emulator 1, adb: 5555
Emulator 2, console: 5556
Emulator 2, adb: 5557
and so on...

As shown, the emulator connected to adb on port 5555 is the same as the emulator whose console listens on port 5554.

Once the server has set up connections to all devices, you can use adb commands to access those devices. Because the server manages connections to devices and handles commands from multiple adb clients, you can control any device from any client (or from a script).

Enable adb debugging on your device

To use adb with a device connected over USB, you must enable USB debugging in the device system settings, under Developer options .

On Android 4.2 and higher, the Developer options screen is hidden by default. To make it visible, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options at the bottom.

On some devices, the Developer options screen might be located or named differently.

You can now connect your device with USB. You can verify that your device is connected by executing adb devices from the android_sdk /platform-tools/ directory. If connected, you"ll see the device name listed as a "device."

Note: When you connect a device running Android 4.2.2 or higher, the system shows a dialog asking whether to accept an RSA key that allows debugging through this computer. This security mechanism protects user devices because it ensures that USB debugging and other adb commands cannot be executed unless you"re able to unlock the device and acknowledge the dialog.

For more information about connecting to a device over USB, read Run Apps on a Hardware Device .

Connect to a device over Wi-Fi

adb usually communicates with the device over USB, but you can also use adb over Wi-Fi after some initial setup over USB, as described below. If you"re developing for Wear OS, however, you should instead see the guide to debugging a Wear OS app , which has special instructions for using adb with Wi-Fi and Bluetooth.

  1. Connect your Android device and adb host computer to a common Wi-Fi network accessible to both. Beware that not all access points are suitable; you might need to use an access point whose firewall is configured properly to support adb.
  2. If you are connecting to a Wear OS device, turn off Bluetooth on the phone that"s paired with the device.
  3. Connect the device to the host computer with a USB cable.
  4. Set the target device to listen for a TCP/IP connection on port 5555. adb tcpip 5555
  5. Disconnect the USB cable from the target device.
  6. Find the IP address of the Android device. For example, on a Nexus device, you can find the IP address at Settings > About tablet (or About phone ) > Status > IP address . Or, on a Wear OS device, you can find the IP address at Settings > Wi-Fi Settings > Advanced > IP address .
  7. Connect to the device by its IP address. adb connect device_ip_address
  8. Confirm that your host computer is connected to the target device: $ adb devices List of devices attached device_ip_address:5555 device

You"re now good to go!

If the adb connection is ever lost:

  1. Make sure that your host is still connected to the same Wi-Fi network your Android device is.
  2. Reconnect by executing the adb connect step again.
  3. Or if that doesn"t work, reset your adb host: adb kill-server

    Then start over from the beginning.

Query for devices

Before issuing adb commands, it is helpful to know what device instances are connected to the adb server. You can generate a list of attached devices using the devices command.

Adb devices -l

In response, adb prints this status information for each device:

  • Serial number: A string created by adb to uniquely identify the device by its port number. Here"s an example serial number: emulator-5554
  • State: The connection state of the device can be one of the following:
    • offline: The device is not connected to adb or is not responding.
    • device: The device is now connected to the adb server. Note that this state does not imply that the Android system is fully booted and operational because the device connects to adb while the system is still booting. However, after boot-up, this is the normal operational state of an device.
    • no device: There is no device connected.
  • Description: If you include the -l option, the devices command tells you what the device is. This information is helpful when you have multiple devices connected so that you can tell them apart.

The following example shows the devices command and its output. There are three devices running. The first two lines in the list are emulators, and the third line is a hardware device that is attached to the computer.

$ adb devices List of devices attached emulator-5556 device product:sdk_google_phone_x86_64 model:Android_SDK_built_for_x86_64 device:generic_x86_64 emulator-5554 device product:sdk_google_phone_x86 model:Android_SDK_built_for_x86 device:generic_x86 0a388e93 device usb:1-1 product:razor model:Nexus_7 device:flo

Emulator not listed

The adb devices command has a corner-case command sequence that causes running emulator(s) to not show up in the adb devices output even though the emulator(s) are visible on your desktop. This happens when all of the following conditions are true:

  1. The adb server is not running, and
  2. You use the emulator command with the -port or -ports option with an odd-numbered port value between 5554 and 5584, and
  3. The odd-numbered port you chose is not busy so the port connection can be made at the specified port number, or if it is busy, the emulator switches to another port that meets the requirements in 2, and
  4. You start the adb server after you start the emulator.

One way to avoid this situation is to let the emulator choose its own ports, and don"t run more than 16 emulators at once. Another way is to always start the adb server before you use the emulator command, as explained in the following examples.

Example 1: In the following command sequence, the adb devices command starts the adb server, but the list of devices does not appear.

Stop the adb server and enter the following commands in the order shown. For the avd name, provide a valid avd name from your system. To get a list of avd names, type emulator -list-avds . The emulator command is in the android_sdk /tools directory.

$ adb kill-server $ emulator -avd Nexus_6_API_25 -port 5555 $ adb devices List of devices attached * daemon not running. starting it now on port 5037 * * daemon started successfully *

Example 2: In the following command sequence, adb devices displays the list of devices because the adb server was started first.

To see the emulator in the adb devices output, stop the adb server, and then start it again after using the emulator command and before using the adb devices command, as follows:

$ adb kill-server $ emulator -avd Nexus_6_API_25 -port 5557 $ adb start-server $ adb devices List of devices attached emulator-5557 device

For more information about emulator command-line options, see Using Command Line Parameters .

Send commands to a specific device

If multiple devices are running, you must specify the target device when you issue the adb command. To specify the target, use the devices command to get the serial number of the target. Once you have the serial number, use the -s option with the adb commands to specify the serial number. If you"re going to issue a lot of adb commands, you can set the $ANDROID_SERIAL environment variable to contain the serial number instead. If you use both -s and $ANDROID_SERIAL , -s overrides $ANDROID_SERIAL .

In the following example, the list of attached devices is obtained, and then the serial number of one of the devices is used to install the helloWorld.apk on that device.

$ adb devices List of devices attached emulator-5554 device emulator-5555 device $ adb -s emulator-5555 install helloWorld.apk

Note: If you issue a command without specifying a target device when multiple devices are available, adb generates an error.

If you have multiple devices available, but only one is an emulator, use the -e option to send commands to the emulator. Likewise, if there are multiple devices but only one hardware device attached, use the -d option to send commands to the hardware device.

Install an app

You can use adb to install an APK on an emulator or connected device with the install command:

Adb install path_to_apk

You must use the -t option with the install command when you install a test APK. For more information, see .

For more information about how to create an APK file that you can install on an emulator/device instance, see Build and Run Your App .

Note that, if you are using Android Studio, you do not need to use adb directly to install your app on the emulator/device. Instead, Android Studio handles the packaging and installation of the app for you.

Set up port forwarding

You can use the forward command to set up arbitrary port forwarding, which forwards requests on a specific host port to a different port on a device. The following example sets up forwarding of host port 6100 to device port 7100:

Adb forward tcp:6100 tcp:7100

The following example sets up forwarding of host port 6100 to local:logd:

Adb forward tcp:6100 local:logd

Copy files to/from a device

Use the pull and push commands to copy files to and from an device. Unlike the install command, which only copies an APK file to a specific location, the pull and push commands let you copy arbitrary directories and files to any location in a device.

from the device, do the following:

Adb pull remote local

To copy a file or directory and its sub-directories to the device, do the following:

Adb push local remote

Replace local and remote with the paths to the target files/directory on your development machine (local) and on the device (remote). For example:

Adb push foo.txt /sdcard/foo.txt

Stop the adb server

In some cases, you might need to terminate the adb server process and then restart it to resolve the problem (e.g., if adb does not respond to a command).

To stop the adb server, use the adb kill-server command. You can then restart the server by issuing any other adb command.

Issuing adb commands

You can issue adb commands from a command line on your development machine or from a script. The usage is:

Adb [-d | -e | -s serial_number ] command

If there"s only one emulator running or only one device connected, the adb command is sent to that device by default. If multiple emulators are running and/or multiple devices are attached, you need to use the -d , -e , or -s option to specify the target device to which the command should be directed.

You can see a detailed list of all supported adb commands using the following command:

Adb --help

Issue shell commands

You can use the shell command to issue device commands through adb, or to start an interactive shell. To issue a single command use the shell command like this:

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

To start an interactive shell on a device use the shell command like this:

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

To exit an interactive shell, press Control + D or type exit .

Note: With Android Platform-Tools 23 and higher, adb handles arguments the same way that the ssh(1) command does. This change has fixed a lot of problems with command injection and makes it possible to now safely execute commands that contain shell metacharacters , such as adb install Let\"sGo.apk . But, this change means that the interpretation of any command that contains shell metacharacters has also changed. For example, the adb shell setprop foo "a b" command is now an error because the single quotes (") are swallowed by the local shell, and the device sees adb shell setprop foo a b . To make the command work, quote twice, once for the local shell and once for the remote shell, the same as you do with ssh(1) . For example, adb shell setprop foo ""a b"" .

Android provides most of the usual Unix command-line tools. For a list of available tools, use the following command:

Adb shell ls /system/bin

Help is available for most of the commands via the --help argument. Many of the shell commands are provided by toybox . General help applicable to all toybox commands is available via toybox --help .

  • -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.
startservice [ options ] intent Start the Service specified by intent .
  • --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.
  • --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.
  • [--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 .
  • -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_flag value [, 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 .
  • --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 app package to debug.
  • -w: Wait for debugger when app 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.
  • --gdb: Start gdbserv on the given port at crash/ANR.
screen-compat {on | off} package Control screen compatibility mode of package . display-size Override 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 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. to-intent-uri intent Print the given intent specification as an intent: URI.

Specification for intent arguments

For activity manager commands that take an intent argument, you can specify the intent with the following options:

A action Specify the intent action, such as android.intent.action.VIEW . You can declare this only once. -d data_uri Specify the intent data URI, such as content://contacts/people/1 . You can declare this only once. -t mime_type Specify the intent MIME type, such as image/png . You can declare this only once. -c category Specify an intent category, such as android.intent.category.APP_CONTACTS . -n component Specify the component name with package name prefix to create an explicit intent, such as com.example.app/.ExampleActivity . -f flags Add flags to the intent, as supported by setFlags() . --esn extra_key Add a null extra. This option is not supported for URI intents. -e | --es extra_key extra_string_value Add string data as a key-value pair. --ez extra_key extra_boolean_value Add boolean data as a key-value pair. --ei extra_key extra_int_value Add integer data as a key-value pair. --el extra_key extra_long_value Add long data as a key-value pair. --ef extra_key extra_float_value Add float data as a key-value pair. --eu extra_key extra_uri_value Add URI data as a key-value pair. --ecn extra_key extra_component_name_value Add a component name, which is converted and passed as a ComponentName object. --eia extra_key extra_int_value [, extra_int_value ...] Add an array of integers. --ela extra_key extra_long_value [, extra_long_value ...] Add an array of longs. --efa extra_key extra_float_value [, extra_float_value ...] Add an array of floats. --grant-read-uri-permission Include the flag FLAG_GRANT_READ_URI_PERMISSION . --grant-write-uri-permission Include the flag FLAG_GRANT_WRITE_URI_PERMISSION . --debug-log-resolution Include the flag FLAG_DEBUG_LOG_RESOLUTION . --exclude-stopped-packages Include the flag FLAG_EXCLUDE_STOPPED_PACKAGES . --include-stopped-packages Include the flag FLAG_INCLUDE_STOPPED_PACKAGES . --activity-brought-to-front Include the flag FLAG_ACTIVITY_BROUGHT_TO_FRONT . --activity-clear-top Include the flag FLAG_ACTIVITY_CLEAR_TOP . --activity-clear-when-task-reset Include the flag FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET . --activity-exclude-from-recents Include the flag FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS . --activity-launched-from-history Include the flag FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY . --activity-multiple-task Include the flag FLAG_ACTIVITY_MULTIPLE_TASK . --activity-no-animation Include the flag FLAG_ACTIVITY_NO_ANIMATION . --activity-no-history Include the flag FLAG_ACTIVITY_NO_HISTORY . --activity-no-user-action Include the flag FLAG_ACTIVITY_NO_USER_ACTION . --activity-previous-is-top Include the flag FLAG_ACTIVITY_PREVIOUS_IS_TOP . --activity-reorder-to-front Include the flag FLAG_ACTIVITY_REORDER_TO_FRONT . --activity-reset-task-if-needed Include the flag FLAG_ACTIVITY_RESET_TASK_IF_NEEDED . --activity-single-top Include the flag FLAG_ACTIVITY_SINGLE_TOP . --activity-clear-task Include the flag FLAG_ACTIVITY_CLEAR_TASK . --activity-task-on-home Include the flag FLAG_ACTIVITY_TASK_ON_HOME . --receiver-registered-only Include the flag FLAG_RECEIVER_REGISTERED_ONLY . --receiver-replace-pending Include the flag FLAG_RECEIVER_REPLACE_PENDING . --selector Requires the use of -d and -t options to set the intent data and type. URI component package You can directly specify a URI, package name, and component name when not qualified by one of the above options. When an argument is unqualified, the tool assumes the argument is a URI if it contains a ":" (colon); it assumes the argument is a component name if it contains a "/" (forward-slash); otherwise it assumes the argument is a package name.

Call package manager (pm)

Within an adb shell, you can issue commands with the package manager (pm) tool to perform actions and queries on app 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 .
  • -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 .
  • -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.
  • -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.
  • -r: Reinstall an existing app, keeping its data.
  • -t: Allow test APKs to be installed. Gradle generates a test APK when you have only run or debugged your app or have used the Android Studio Build > Build APK command. If the APK is built using a developer preview SDK (if the targetSdkVersion is a letter instead of a number), you must include the -t option with the install command if you are installing a test APK.
  • -i installer_package_name: Specify the installer package name.
  • --install-location location: Sets the install location using one of the following values:
    • 0: Use the default install location
    • 1: Install on internal device storage
    • 2: Install on external media
  • -f: Install package on the internal system memory.
  • -d: Allow version code downgrade.
  • -g: Grant all permissions listed in the app manifest.
  • --fastdeploy: Quickly update an installed package by only updating the parts of the APK that changed.
uninstall [ options ] package Removes a package from the system.
  • -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
  • --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, the permission can 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, the permission can 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: on external media.

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

get-install-location Returns the current install location. Return values:
  • 0 : Lets system decide the best location
  • 1 : Installs on internal device storage
  • 2 : Installs on external media
set-permission-enforced permission 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.

Call device policy manager (dpm)

To help you develop and test your device management (or other enterprise) apps, you can issue commands to the device policy manager (dpm) tool. Use the tool to control the active admin app or change a policy"s status data on the device. While in a shell, the syntax is:

Dpm command

You can also issue a device policy manager command directly from adb without entering a remote shell:

Adb shell dpm command

Table 4. Available device policy manager commands

Command Description
set-active-admin [ options ] component Sets component as active admin.
set-profile-owner [ options ] component Sets component as active admin and its package as profile owner for an existing user.
  • --user user_id: Specify the target user. You can also pass --user current to select the current user.
set-device-owner [ options ] component Sets component as active admin and its package as device owner.
  • --user user_id: Specify the target user. You can also pass --user current to select the current user.
  • --name name: Specify the human-readable organization name.
remove-active-admin [ options ] component Disables an active admin. The app must declare android:testOnly in the manifest. This command also removes device and profile owners.
  • --user user_id: Specify the target user. You can also pass --user current to select the current user.
clear-freeze-period-record Clears the device"s record of previously-set freeze periods for system OTA updates. This is useful to avoid the device"s scheduling restrictions when developing apps that manage freeze-periods. See Manage system updates .

Supported on devices running Android 9.0 (API level 28) and higher.

force-network-logs Forces the system to make any existing network logs ready for retrieval by a DPC. If there are connection or DNS logs available, the DPC receives the onNetworkLogsAvailable() callback. See Network activity logging .
force-security-logs Forces the system to make any existing security logs available to the DPC. If there are logs available, the DPC receives the onSecurityLogsAvailable() callback. See Log enterprise device activity .

This command is rate-limited. Supported on devices running Android 9.0 (API level 28) and higher.

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. You can use this file to create promotional or training videos or for debugging and testing.

In a shell, use the following syntax:

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 (Command + C on Mac); 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.

Limitations of the screenrecord utility:

  • Audio is not recorded with the video file.
  • Video recording is not available for devices running Wear OS.
  • Some devices might 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 5. screenrecord options

Options Description
--help Displays command syntax and options
--size width x height Sets the video size: 1280x720 . The default value is the device"s native display resolution (if supported), 1280x720 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

Reset test devices

If you test your app across multiple test devices, it may be useful to reset your device between tests, for example, to remove user data and reset the test environment. You can perform a factory reset of a test device running Android 10 (API level 29) or higher using the testharness adb shell command, as shown below.

Adb shell cmd testharness enable

When restoring the device using testharness , the device automatically backs up the RSA key that allows debugging through the current workstation in a persistent location. That is, after the device is reset, the workstation can continue to debug and issue adb commands to the device without manually registering a new key.

Additionally, to help make it easier and more secure to keep testing your app, using the testharness to restore a device also changes the following device settings:

  • The device sets up certain system settings so that initial device setup wizards do not appear. That is, the device enters a state from which you can quickly install, debug, and test your app.
  • Settings:
    • Disables lock screen
    • Disables emergency alerts
    • Disables auto-sync for accounts
    • Disables automatic system updates
  • Other:
    • Disables preinstalled security apps

If you app needs to detect and adapt to the default settings of the testharness command, you can use the ActivityManager.isRunningInUserTestHarness() .

sqlite

sqlite3 starts the sqlite command-line program for examining sqlite databases. It includes commands such as .dump to print the contents of a table, and .schema to print the SQL CREATE statement for an existing table. You can also execute SQLite commands from the command line, as shown below.

Большинство пользователей Android ничего не знают об ADB . Полное название - Android Debug Bridge , расшифровывается, как «Отладочный Мост Android». ADB является частью Android SDK. При помощи ADB можно выполнять различные действия над вашим Android планшетом или смартфоном, такие как: перепрошивку, копирование файлов с компьютера на Андроид и обратно, восстановление системы и другие.

ADB для Android — что это такое?

Вам наверняка известно, что операционная система Android основана на модифицированном ядре Linux. Поэтому и с ней возникает необходимость использовать командную строку. Именно программа adb помогает устанавливать связь между компьютером и Android. Она является составляющей среды разработки Android SDK, поэтому чтобы установить Android Debug Bridge, вам нужно скачать Android SDK с официального сайта . Есть версии для всех популярных операционных систем: Windows, Mac OS и Linux. То есть, проще говоря, adb позволяет при помощи компьютера управлять телефоном или планшетом .

Также я советую следующие инструкции:

Основные команды adb Андроид

Подключите ваше устройство к ПК по USB. Убедитесь, что установлены все драйвера и включена отладка по USB.

Работать с Android Debug Bridge лучше всего через командную строку Windows. Для этого в Windows XP нажмите «Пуск» и в поле ввода «Найти программы и файлы» введите «cmd», после этого нажмите «Enter». Если у вас Windows 7 и выше, нажмите «Пуск» и в поле «Выполнить» введите «cmd» и снова нажмите клавишу «Enter».

adb devices

Самая распространенная команда adb. При помощи нее можно определить, видит ли ваш ПК подключенное устройство. Если вы всё сделали нормально, то появится такая строка: «List of devices attached». После нее вы увидите серийный номер вашего смартфона или планшета и его состояние: «online» либо «offline».

Если пишет «offline», это значит, что аппарат находится в спящем режиме, если «online», то девайс готов выполнять ваши команды.

Благодаря этой команде вы можете устанавливать приложения на вашем смартфоне или планшете. Для этого нужно прописать путь, где находится APK файл:

adb intsall D:\papka_s_faylom\nazvanie_prilogeniya.apk

Чтобы не писать длинных путей, скопируйте файл в директорию android-tools. Тогда путь станет таким:

adb intsall nazvanie_prilogeniya.apk

adb uninstall

Вводить нужно аналогично предыдущей команде. При этом приложение удалится.

У этой команды есть интересная фишка. Если вы добавите ключ -k ,то при удалении игры или программы их данные и кэш не удалятся, а останутся на Android устройстве.

Благодаря этой команде вы можете перекидывать файлы с компьютера на Android. Для этого вам нужно знать полный путь, где хранится файл и куда его перемещать.

adb push D:\papka_s_faylom\nazvanie_fayla/sdcard/Android

Чтобы не писать длинных путей, скопируйте файл в директорию android-tools. Тогда вводить нужно:

adb push nazvanie_fayla/sdcard/Android

Эта команда копирует файлы с Android на компьютер. Вам нужно знать путь, где находится файл на смартфоне или планшете и указать место, где вы хотите сохранить файл. Если вы не укажете последнее, то файл сохранится в директории android-tools.

adb pull /sdcard/nazvanie_fayla\D:\papka_gde_sohranity

Эта команда перезагрузит ваш Android телефон или планшет.

Благодаря этой команде вы можете напрямую загрузиться в режиме bootloader.

adb reboot recovery

Не все девайсы поддерживают данную команду. При помощи нее можно попасть в режим восстановления.

adb connect

При помощи этой команды можно подключить устройство к Wi-Fi сети. Для этого нужно знать ip адресс и порт устройства.

adb connect ip:port

При помощи этой команды вы получаете полный доступ ко всем файлам на вашем устройстве.

Второй способ использования adb shell — это выполнение единичной команды Android shell с помощью такой конструкции:

adb shell <команда>

Если вы переведете ваш телефон или планшет под управлением Андроид в режим bootloader, то команды adb больше срабатывать не будут. Здесь нужно использовать команды fastboot.

Чтобы проверить, видят ли ПК и Android друг друга, используем команду:

После её ввода должен появится серийный номер вашего аппарата.

При вводе этой команды можно разблокировать загрузчик телефонов и планшетов Asus и HTC. Когда ваше устройство находится в режиме bootloader, введите:

Также все ваши установленные программы и персональные данные будут потеряны.

При помощи этой команды можно вывести содержимое log файла: изменения, ошибки и т.д. Данные будут слишком быстро прокручиваться, поэтому верным решением будет сохранить их в один TXT-файл. Для этого введите:

adb logcat > filename.txt

adb sideload

Команда пригодится для владельцев устройств линейки Google Nexus. При помощи нее можно обновить прошивку девайса. Скачайте её на компьютер, подключите к нему Nexus, зайдите в режим Recovery, выберите пункт «Apply update from ADB» и после этого введите команду:

adb sideload name.zip

name.zip – это имя zip файла c прошивкой.

adb backup и adb restore

Команда adb backup создает бэкап, а adb restore проводит восстановление из бэкапа.

В данной статье вы узнаете что такое ADB для чего он нужен пользователям, а также как управлять им с помощью команд в Android терминале. Ну что же начнем изучать adb команды android…

Знакомимся с ADB

ADB (android debug bridge) - это средство , выявления ошибок, удаление , выполнить , прошивки устройств на Android и многого другого. Официальную документацию на английском языке можете прочитать на данном сайте .

Где скачать ADB?

Скачать ADB можно с официального .

Либо воспользоваться специальной программой Adb Run , облегчающая взаимодействие с ADB.

Позаботьтесь чтобы на ПК были установлены драйвера , а на Android включена отладка по USB и компьютер прошел .

Adb команды Android

Команды Adb можно разделить 3 типа, непосредственно для команды Adb и FastBoot () и Linux команды (Android).

Проверка подключения Android к компьютеру. ADB DEVICES

Чтобы убедиться, что Android подключен к компьютеру необходимо ввести adb команду:

Пример как использовать:

На данном скрине видно что Android подсоединен

Если у вас не появилось похожее сообщение, то возможно, необходимо проверить, наличие драйверов на ПК, целостность кабеля, работоспособность порта USB.

Подключение Android по WI-FI. ADB Connect

Для того, чтобы подключить Android по WI-FI сети, необходимо получить ip адрес и порт устройства, в этом вам поможет приложение ADB Wireless (необходим Root) которую можно скачать в Google Play

После этого ввести команду adb:

adb connect ip:port

Пример как использовать:

adb connect 192.168.0.14:5555

Более подробно о том как подключить Android через WI-FI — Отладка по USB по Wi-FI .

Установка приложений на Android. ADB Install

Для того, чтобы установить какое-либо приложение с компьютера на Android, необходимо ввести команду:

adb install

Пример как с помощью команды adb install установить приложение необходимо написать:

adb intsall C:\papka_gde_hranitsya_proga.apk

То есть написать команду adb install путь к приложению и название приложения.

Отправить какой-либо файл на Android. ADB PUSH

Чтобы отправить с компьютера на Android любой файл существует следующая команда:

adb push

Пример, чтобы с помощью команды Adb отправить файл с ПК на Android необходимо написать adb push команду:

adb push C:\papka_gde_hranitsya_file\imja_file /sdcard

То есть написать adb push команду путь к файлу, название файла и место где сохранить данный файл.

Отправить / Принять файл c Android на Компьютер.
ADB PULL

Для того чтобы принять абсолютно любой файл с устройства Android на компьютер существует команда:

adb pull

Для того чтобы с помощью команды Adb принять файл с Android девайса на ваш ПК необходимо написать:

adb pull /sdcard/xxx/Keks_s_Pameloy_Anderson.avi C:\papka_gde_budet_hranitsya_file

То есть написать команду adb pull и путь к файлу который находится на Android, название файла и место где сохранить данный файл на ПК.

Перезагрузка Android. ADB Reboot

Для перезагрузки Android, после каких-либо выполненных операций, либо перезагрузить в специальный режим, существует команда:

adb reboot

Команды перезагрузят Android в нормальный режим (обычная перезагрузка):

adb reboot или adb reboot normal

загрузки Bootloader :

adb reboot bootloader

Команда перезагрузит Android в режим Recovery :

adb reboot recovery

Управление Android. ADB SHELL

Перейти в управление Android , после чего можно использовать linux команды ОС Android.

Весь потенциал Android раскрывается после того когда вы переходите в управление Android где доступны многие команды linux.

adb shell

Команды в терминале Android
(Linux команды)

Команда суперпользователь . SU

Суперпользователь или Root. Позволяет выполнять абсолютно все действия, от создания, модифицирования, изменения, до удаления конкретных системных файлов, для этого введите команду:

До ввода команды: su пользователь является гостем в системе (многие действия заблокированы) и обозначается в начале терминала знаком доллар $ после ввода команды su становится админом и в терминале обозначается как американский номер #

Команда перейти в папку. CD

Для того чтобы перемещаться между разделам и каталогами в Android, существует специальная команда:

Чтобы перейти с раздела /sdcard в раздел /sdcard/xxx/porno/hot_girl

cd /sdcard/xxx/porno/hot_girl

Для того чтобы вернуться с раздела на каталог выше, либо обратно в /sdcard:
если находимся в каталоге /sdcard/xxx/porno/hot_girl — hot_girl

окажемся в каталоге:

/sdcard/xxx/porno/

если необходимо подняться в /sdcard то:

cd ../ ../ (столько раз сколько это необходимо)

Внимание в Android и других Unix системах файлы Primer , либо primer или PrimER абсолютно разные файлы!

Переместить / Переименовать файл либо каталог. MV

Перемещение и переименование файла, каталога (папки) или файла осуществляется только одной командой:

Пример переименовать файл:

mv /sdcard/xxx/hot_porno/Alenka.avi /sdcard/xxx/hot_porno/kruto.avi

Пример переименовать папку:

mv -r /sdcard/xxx/hot_porno /sdcard/xxx/super

Пример как Переместить файл:

mv /sdcard/xxx/hot_porno/Alenka.avi /sdcard/xxx/Alenka.avi

Пример как Переместить папку:

mv -r /sdcard/xxx/hot_porno /sdcard/hot_porno

Просмотреть что внутри каталога. LS

Какие каталоги и файлы содержаться в каталоге где вы находитесь, используют следующую linux команду:

Пример как использовать, узнать какие файлы в папке /sdcard/xxx/hot porno:

ls /sdcard/xxx/hot_porno/

вы получите в окне следующее сообщение:

Alenka.avi

Pamela.avi

Anderson.avi

Пример как использовать:

ls -a /sdcard/xxx/hot_porno/

выдаст следующие сообщение:

.Skruty_file_Hot.avi

Pamela Anderson.avi

Skrutiy_File.avi

Копировать файл или папку (каталог). CP

Скопировать какой-либо файл или папку и переместить куда-либо:

Пример Скопировать файл:

cp /sdcard/xxx/hot_porno/Alenka.avi /sdcard/xxx/Alenka.avi

Пример Скопировать папку:

cp -r /sdcard/xxx/hot_porno /sdcard/hot_porno

Создать каталог (папку). MKDIR

Для того, чтобы создать где-либо папку, используйте команду:

Пример как использовать:

mkdir /sdcrad/android_papka

Удалить каталог (папку) или файл. RM

Если необходимо удалить какой либо файл или папку linux команда:

Пример как удалить файл:

rm /sdcard/xxx/hot_porno/Alenka.avi

Пример как удалить папку:

rm - r /sdcard/xxx/hot_porno

Вывести содержимое файла на экран. CAT

Если перед вами стоит задача вывести на экран содержимое текстового файла:

Пример как использовать:

cat /sdcard/books/Толстой_книга_война_и_мир.txt

и получим:

Еh bien, mon prince. Genes et Lucques ne sont plus que des apanages, des поместья, de la famille Buonaparte. Non, je vous previens, que si vous ne me dites pas, que nous avons la guerre, si vous vous permettez encore de pallier toutes les infamies, toutes les atrocodes de cet Antichrist (ma parole, j`y crois) - je ne vous connais plus, vous n`etes plus mon ami, vous n`etes plus мой верный раб, comme vous dites.

Показать полный путь. PWD

Для того чтобы понять в каком разделе и каталоге сейчас находитесь:

Если находимся в каком-либо каталоге и надо узнать полный путь (например находимся в системном разделе, каталог app):

выдаст сообщение:

/system/app/

Создать пустой файл. TOUCH

Чтобы создать текстовый файл:

Создадим файл 666.txt в каталоге /sdcard:

touch /sdcard/666.txt

Создание резервной копии с раздела и восстановление.
DD IF

Создания резервной копии на Sd карту

dd if=dev/block/mmcblk0p1 of=sdcard/efs.img

Восстановления раздела с резервной копии с Sd карты

dd if=/sdcard/efs.img of=/dev/block/mmcblk0p1

Просмотр занимаемого места. DU

Для того, чтобы понять сколько занимает что-либо:

Пример как использовать:

Выставление permission, прав файлам и директориям

Чтобы узнать какие права у файлов и директорий нужно написать такую команду

Права Доступа (permission)

И так мы знаем, что существуют пользователи, группы. Теперь поговорим о правах доступа. Для чего этого необходимо? Например у вас есть директория в которой находятся личные файлы. Чтобы вы, владелец , например могли редактировать, просматривать файлы, группа , только видеть данные, файлы, а остальные пользователи которые не входят ни в одну из групп и не являются владельцами, вообще не могли ничего сделать, вот поэтому и необходимы права доступа.

Права на файл могут обозначаться цифрами и буквами:

Значения прав в цифрах суммируются:

  • полные права (rwx) 7 = 4 + 2 +1
  • чтение и запись (rw-) 6 = 4 + 2 + 0
  • чтение и выполнение (r-x) 5 = 4 + 0 + 1
  • только чтение 4 (r—) = 4 + 0 + 0
  • только запись 2 (-w-) = 0 + 2 + 0
  • права отсутствуют (—) 0 = 0 + 0 + 0

Для каждого файла и директории назначаются отдельно права для владельца, группы и остальных пользователей.

Изменять права доступа на файл или директорию командой chmod можно как числами, так буквами.

Назначение прав доступа цифрами

Для того, чтобы изменить права файлу или директорию командой chmod используя цифры введите команду:

Sudo chmod 755 text.txt

Для директорий необходимо после chmod добавить ключ -R .

Назначение прав доступа буквами

Для новичков изменять права доступа букавами будет слегка сложней, но данные знания пригодятся.

Как вы знаете что есть владелец, группа, остальные пользователи, они обозначаются следующим образом:

Права доступа можно назначать, убирать или присваивать:

Установить права на файл «rwxr-xr-x» (755):

Sudo chmod u=rwx,g=rx,o=rx text.txt

Добавить права на выполнение владельцу, удалить выполнение для группы, удалить запись и выполнение для остальных:

Sudo chmod u+x,g-x,o-wx text.txt

Добавить возможность всем (пользователь, группа. остальных) читать:

Sudo chmod a+r text.txt

Для изменения прав доступ директориям необходимо использовать ключ -R:

Sudo chmod -R a+r imya_papki

Жесткие и символические ссылки

В Linux в том числе Android существует такое понятие как ссылки — что на нормальном привычном языке звучит «ярлык». Бывают два типа ссылок это:

  • Жесткие ссылки
  • Символические ссылки или симлинки

В чем различия жестких и символических ссылок?

Символические ссылки - создают ярлык которые указывают точное место файла или папки куда ярлык ссылается. Если файл или папку переместить, символическая ссылка будет битая. Чтобы наглядно понять что такое символическая ссылка — в Windows XP или Windows 7 есть ярлыки программ на рабочем столе, которые ссылаются в папку с программой, а точней exe-шник.

Практически каждый владелец Android устройства, который решил улучшить своего любимца путем замены прошивки или ядра операционной системы, сталкивается с программой adb .

Для большинства новичков именно эта программа становится непреодолимым препятствием и мы сегодня расскажем вам, как установить и начать работу с этим замечательным приложением, которое поможет вам, например, получить root права на вашем устройстве, прошить новую версию Android или даже восстановить ваш телефон или планшет к первоначальному состоянию после неудачного вмешательства в систему.

Так что же такое ADB, полюбившийся всем моддерам и хакерам, где его взять, и зачем он нам нужен?

Что такое ADB .

Аббревиатура ADB расшифровывается как Android Debug Bridge (отладочный мост Андроид). ADB является составной частью , который можно скачать отсюда .

Так как операционная система Android является разновидностью Linux , для ее настройки часто возникает необходимость работы через командную строку. Конечно, существуют программы – эмуляторы терминала, которые позволяют выполнять команды прямо на устройстве но, во-первых, на маленьком экране телефона делать это неудобно, а во-вторых, иногда требуется доступ к устройству через компьютер, и в этих и многих других случаях программа adb просто незаменима. Программа adb устанавливает связь между устройством и компьютером и позволяет прямо на компьютере выполнять различные манипуляции с системой Android .

Как установить ADB.

Прежде всего, рекомендуем вам скачать самую последнюю версию , на момент написания этого руководства доступна версия r11 , на ее примере построено все дальнейшее описание, и в более ранних версиях, местоположение необходимых программ после установки SDK , может отличаться от описанного здесь.

1. Скачиваем , его можно найти по ссылке указанной ранее. Имеется несколько разновидностей SDK , для Microsoft Windows, Mac OS и Linux .

Нам потребуется разновидность для Microsoft Windows . И здесь есть два варианта – скачать установщик или zip архив с Android SDK. Установщик нам не нужен, тем более он не позволит установить SDK в Windows 7 , и поэтому скачиваем zip архив.

В архиве находится папка android-sdk-windows , которая и содержит сам SDK . Распаковываем ее на компьютер. В нашем примере, мы разместили папку в корне диска С. Если вы сделаете то же самое, путь к SDK будет у нас такой: C:\android-sdk-windows

В более ранних версиях SDK внутри этой папки в папке tools располагалась нужная нам программа adb , но позднее она была перемещена разработчиками в папку platform-tools .

Однако, если вы зайдете в эту папку, вы не найдете внутри нее программу adb , поэтому переходим к следующему этапу установки.

2. Устанавливаем SDK Platform Tools .
Убеждаемся, что наш компьютер подключен к интернету и запускаем находящуюся в папке android-sdk-windows , программу SDK Manager . После запуска программы появится такое окно:

Нам нужно скачать и установить Android SDK Platform-tools и Android SDK Tools .

С помощью двойного клика по пункту или нажатием на «Accept » и «Reject » отмечаем эти два пункта в списке и снимаем отметку со всех остальных пунктов, как показано на приведенном выше скриншоте. Затем нажимаем «Install » и ждем пока скачаются и установятся нужные нам компоненты.

Теперь мы имеем установленную adb на своем компьютере, но для работы с нашим телефоном или планшетом нужно будет установить их драйвер и для дальнейшего удобства с программой, неплохо было бы прописать путь к ней и другим компонентам в систему Windows.

3. Если мы зайдем в папку C:\android-sdk-windows\platform-tools\ , то теперь сможем там обнаружить программу adb .

После этого, нам нужно отредактировать системную переменную PATH, чтобы каждый раз при запуске программы и вводе команд не набирать путь к программе, который выглядит так:

C:\android-sdk-windows\platform-tools\adb

Если вы ни разу не редактировали системные переменные, создайте точку восстановления системы, чтобы потом можно было вернуть ее в первоначальное состояние.

Если у вас установлена Windows 7 , клацаем правой клавишей мыши по ярлыку «Компьютер », выбираем «свойства » и в открывшемся окне выбираем «Дополнительные параметры системы ».

Если у вас Windows XP , клацаем правой кнопкой мыши по «Мой компьютер » и затем по «Свойства »

В следующем окне на вкладке «Дополнительно » нажимаем на кнопку «Переменные среды ». В списке «Системные переменные » выбираем переменную «path » и нажимаем кнопку «Изменить… »

Откроется окно редактирования переменной, и в пункте «значение переменной » в самый конец строки, после точки с запятой добавляем путь к папке tools и папке platform-tools :

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

(если в конце строки не было точки с запятой, добавьте её – каждый путь в этой строке должен отделяться от другого точкой с запятой )

Если вы установили в другую папку, пропишите в конце строки ваш путь к папкам tools и platform-tools .

Установка драйверов устройства.

Некоторые устройства, например телефоны и планшеты компании Samsung имеют собственное программное обеспечение для синхронизации с компьютером, и если оно у вас установлено на компьютере, то драйвер устройства уже установлен у вас в системе.

Но для таких устройств, как Nexus One , которые поставляются без каких либо дополнительных программ и драйверов, для работы с Android SDK , драйверы установить необходимо.

Для этого идем в папку, в которую мы устанавливали SDK и запускаем SDK Manager .

Точно так же, как мы устанавливали Android SDK Platform-tools и Android SDK Tools , находим и выбираем в списке «Google Usb Driver package ». Нажимаем «Install » и ждем пока программа скачает драйверы. Драйверы для 32 и 64 разрядной Windows будут скачаны в следующую папку:

C:\1\android-sdk-windows\extras\google\usb_driver

Теперь можно установить драйверы для вашего устройства. Для этого в меню настроек телефона или планшета выбираем пункт «Приложения » (Applications), и в нем включаем «Отладка USB » (USB debugging).

Подключаем наше устройство к компьютеру. Компьютер обнаружит новое оборудование и предложит установить драйверы. Устанавливаем драйверы из папки, куда они были скачаны ранее.

После установки драйверов в диспетчере устройств появится новое устройство «ADB Interface » и мы можем убедиться в этом открыв его, нажав правой клавишей мыши по иконке «Компьютер » -> «Свойства » -> «Диспетчер устройств »

Кроме того, вы можете попробовать установить на компьютер универсальный ADB драйвер .

Как запустить ADB

Работать с программой adb лучше всего через командную строку Windows . Для вызова командной строки на компьютере с Windows XP , нажимаем «Пуск » и в поле ввода «Выполнить » набираем cmd и нажимаем «Enter».

На компьютере с Windows 7 , нажимаем «Пуск » и в поле ввода «Найти программы и файлы» набираем cmd и нажимаем «Enter».

Откроется окно командной строки, и для того чтобы, например посмотреть какие устройства у нас подключены к компьютеру, набираем в нем команду

adb devices .

Программа adb отобразит список устройств, подключенных в настоящий момент к компьютеру.