- How to Install adb on Windows 7, 8 and 10
- How to Install ADB on Windows?
- Add ADB to System Path for Windows 7, 8
- Add ADB to System Path in Windows 10
- List of Useful ADB Commands
- How to Use ADB or Fastboot From Any Directory on your Windows/Linux PC
- What is the PATH system variable?
- Adding adb and Fastboot to the Windows PATH (Method 1)
- Adding adb and Fastboot to the Windows PATH (Method 2)
- Step 1
- Step 2
- Step 3
- Step 4
- Step 5
- Adding adb and Fastboot to the Linux PATH
- Step 1
- Step 2
- Step 3
- Setup adb on windows
How to Install adb on Windows 7, 8 and 10
The Android Debug Bridge (ADB) is an important command-line tool for controlling your Android device from your computer. With ADB you can perform many useful commands to back-up your data, sideload .zip files you would otherwise flash in custom recovery, unlock your bootloader on Nexus devices, and several other uses for debugging your Android phone.
Installing ADB on a Windows machine is a fairly painless but involved process. This guide will walk you from start to finish.
How to Install ADB on Windows?
- Go to the Android SDK website and navigate to “SDK Tools Only”. Download the version for your platform.
Download SDK Tools
- Open the SDKManager.Exe and choose only the “Android SDK Platform Tools” for installation. If you’re on a Nexus phone, you should also choose “Google USB Driver”. When you click Install, it will begin downloading the necessary files to your computer.
Downloading Android SDK Platform Tools
- Enable USB debugging on your device. ADB will only work on your device when USB debugging is enabled. USB debugging is usually found under Developer Options, so if you have not enabled Developer Options yet, go to Settings>About Phone> tap on “Build Number” 7 times, and you will get an alert that Developer Options are enabled. You can now go into the Developer Options to turn on USB Debugging.
Allow USB Debugging
- Navigate to the folder on your PC where the SDK tools were installed. Shift + Right Click on the folder and select “Open Command Window Here”.
- Connect your Android phone to your computer via USB (Make sure that you are using Data cable, not the charging cable). If you are prompted on your device, then choose “file transfer (MTP)” mode. Now in the command terminal type:
List of Attached Devices
It should display your device as being connected. If there is no device shown in the command prompt, you may need to download USB drivers specific to your phone from the manufacturer’s website.
You should now configure your system-path so you can always run ADB commands from inside the command terminal without having to run it from the SDK tools folder. The methods are nearly the same but a little different between Windows 7, 8, and 10.
Add ADB to System Path for Windows 7, 8
- Go to Control Panel >System >Security and click the “Advanced System Settings” button, then click on “Environment Variables”.
Edit Environment Variables
- Find the variable called “Path” on it to highlight, then click “Edit“.
Edit Path of Environment Variables
Add your ADB folder to the end of the variable value, with no spaces, preceded by a semicolon. For example:
Add ADB to System Path in Windows 10
Follow the steps above until 3. Instead of adding the string to a pre-existing variable string, you are simply going to click “Add New” in the environment variable box that opens. Simply add your ADB folder and press enter.
List of Useful ADB Commands
- adb install C:\package.apk – Install an .apk package from your C:\ to your Android device.
- adb uninstall package.name – Uninstall an app package from your device – package name would be the specific app package name as seen in your device, for example, com.facebook.katana
- adb push C:\file /sdcard/file – Copies a file from your C:\ to your devices SD card.
- adb pull /sdcard/file C:\file – The reverse of ADB push.
- adb logcat – View the log from your Android device.
- adb shell – This will open an interactive Linux command line on your device.
- adb shell command – This will run a command on your device’s command line.
- adb reboot – This will reboot your device.
- adb reboot-bootloader – Reboots your device to the bootloader.
- adb reboot recovery – Reboots your device to recovery.
fastboot devices – ADB commands only work once your phone is fully booted, not from the bootloader. FastBoot allows you to push ADB commands to your device from the bootloader, useful for when you’re stuck in a recovery loop, for example.
How to Use ADB or Fastboot From Any Directory on your Windows/Linux PC
If you’ve followed our tutorial on how to setup the adb and fastboot platform tools on your computer, it might be annoying to have to navigate to the folder every time, especially if you use either tool quite frequently. Having to copy files to the platform tools folder is also annoying whenever you want to flash stuff on your device. For me it’s frustrating as I use an SSD and I dislike having to copy my files to my platform tools folder, and then delete them after. However, it’s possible to run the adb or fastboot tools from any directory on your Windows or Linux PC so you’ll never have to change directories to run any commands.
What is the PATH system variable?
PATH is used by Windows to specify the location of important executables. Usually, these are files located in the system directories, such as C:\Windows and C:\Windows\system32. This is why you can type “calc” in the command prompt to launch calculator, but not “chrome” to launch Google Chrome. This variable is sometimes changed by applications when you install them, such as Java. Java adds itself to the PATH variable on installation, meaning you can use Java from any directory. This is useful to people using Java applications so the program does not have to attempt to hard code the Java location.
We will be modifying the PATH system variable to allow us to use adb or Fastboot anywhere on our Windows computer. PATH also exists on Linux and usually contains the bin and sbin directories. I will cover how to add the platform tools to the Linux PATH variable too.
Note: Both tutorials require administrator/sudo access.В Adding to Windows has two methods. I strongly suggest the first, but both work fine and the second is better if you plan to use the PATH variable a lot.
Adding adb and Fastboot to the Windows PATH (Method 1)
This isn’t really adding it to the Windows PATH variable per se, but more adding it to a folder that is already in the PATH variable. Simply copy your adb.exe, fastboot.exe, AdbWinApi.dll and AdbWinUsbApi.dll to C:\Windows and you’re good to go. You should be able to run adb and fastboot from the command line now. This is by far the easiest, most fool proof method for setting this up. If for whatever reason it doesn’t work, follow method 2.
Adding adb and Fastboot to the Windows PATH (Method 2)
Step 1
Open Windows Explorer and right click “My PC”. Select “Properties” and you will be greeted with a screen showing some system information.
Step 2
Select “Advanced System Settings”.
Step 3
Select “Environment Variables”
Step 4
Look for the variable named “Path” and double click it.
Step 5
Click “Browse” and navigate to the folder where you extracted your adbВ files. Next “okay” out of all of the Windows you have open. Start a new PowerShell or command prompt and type “adb” to verify the location has been added. If not, reboot your PC and try again.
Please ensure before you click “Browse” that no field is highlighted. If a field is highlighted you will end up replacing it. Click somewhere in the list that doesn’t contain an entry to ensure that you do not replace a field.
Adding adb and Fastboot to the Linux PATH
I will be using Ubuntu for this tutorial, via command line only. You can edit the .bashrc file via the GUI, but you will need to navigate to the root of your home directory and press Ctrl+H. Make sure you have the platform-tools downloaded and extracted.
Step 1
Note the path of the adb tools you extracted. For me, I extracted them to /home/adam/adb/platform-tools.
Step 2
You’ll need to edit your .bashrcВ file. Go back to your home directory and run the following command.
If you prefer to use vi or gedit you can instead.
Step 3
Add the following line to the end of the .bashrc file. Be careful editing this file, do not add anything else or change anything else.
to check if it works. If it gives you an error (usually on 64-bit computers), install the packages glibc.i686 and libstdc++ and it should work.
You are now done, you should now be able to simply execute theВ adb or fastbootВ commands from anywhere on your Windows or Linux computer. As I said, this is incredibly useful and also allows for better organization so that you don’t need to put all of your flashable files in the same folders.
Setup adb on windows
Platform-tools: r31.0.2
ADB: 1.0.41 (31.0.2-7242960)
Fastboot: 31.0.2-7242960
Make_f2fs: 1.14.0 (2020-08-24)
Mke2fs: 1.45.4 (23-Sep-2019)
Последнее обновление утилит в шапке: 16.04.2021
ADB (Android Debug Bridge — Отладочный мост Android) — инструмент, который устанавливается вместе с Android-SDK и позволяет управлять устройством на базе ОС Android.
Работает на всех Android-устройствах, где данный функционал не был намеренно заблокирован производителем.
Здесь и далее: PC — ПК, компьютер к которому подключено устройство.
ADB — консольное приложение для PC, с помощью которого производится отладка Android устройств, в том числе и эмуляторов.
Работает по принципу клиент-сервер. При первом запуске ADB с любой командой создается сервер в виде системной службы (демона), которая будет прослушивать все команды, посылаемые на порт 5037.
Официальная страница
ADB позволяет:
- Посмотреть какие устройства подключены и могут работать с ADB.
- Просматривать логи.
- Копировать файлы с/на аппарат.
- Устанавливать/Удалять приложения.
- Удалять (очищать) раздел data.
- Прошивать (перезаписывать) раздел data.
- Осуществлять различные скрипты управления.
- Управлять некоторыми сетевыми параметрами.
Поставляется ADB в составе инструментария разработчика Андроид (Android SDK), который, в свою очередь входит в состав Android Studio.
Если что-то неправильно, то в списке подключенных устройств (List of devices attached) будет пусто.
Скрытые команды ADB
adb -d Команда посылается только на устройство подключенное через USB.
Внимание: Выдаст ошибку, если подключено больше одного устройства.
adb -e Команда посылается на устройство в эмуляторе.
Внимание: Выдаст ошибку, если подключено больше одного эмулятора.
adb -s Команда посылается на устройство с указанным серийным номером:
adb -p Команда посылается на устройство с указанным именем:
Если ключ -p не указан, используется значение переменной ANDROID_PRODUCT_OUT.
adb devices Список всех подсоединенных устройств.
adb connect [: ] Подсоединиться к андроид хосту по протококу TCP/IP через порт 5555 (по умолчанию, если не задан).
adb disconnect [ [: ]] Отсоединиться от андроид подключенного через TCP/IP порт 5555 (по умолчанию, если не задан).
Если не задан ни один параметр, отключиться от всех активных соединений.
adb push Копировать файл/папку PC->девайс.
adb pull [ ] Копировать файл/папку девайс->PC.
adb sync [ ] Копировать PC->девайс только новые файлы.
Ключи:
-l Не копировать, только создать список.
adb shell Запуск упрощенного unix shell.
Примеры использования
adb emu Послать команду в консоль эмулятора
adb install [-l] [-r] [-s] Послать приложение на устройство и установить его.
Пример: adb install c:/adb/app/autostarts.apk Установить файл autostarts.apk лежащий в папке /adb/app/ на диске с:
Ключи:
-l Блокировка приложения
-r Переустановить приложение, с сохранением данных
-s Установить приложение на карту памяти
Установка split apk
adb uninstall [-k] Удаление приложения с устройства.
Ключи:
-k Не удалять сохраненные данные приложения и пользователя.
adb wait-for-device Ждать подключения устройства.
adb start-server Запустить службу/демон.
adb kill-server Остановить службу/демон.
adb get-state Получить статус:
offline Выключен.
bootloader В режиме начальной загрузки.
device В режиме работы.
adb get-serialno Получить серийный номер.
adb status-window Непрерывный опрос состояния.
adb remount Перемонтировать для записи. Требуется для работы скриптов, которые изменяют данные на.
adb reboot bootloader Перезагрузка в режим bootloader.
adb reboot recovery Перезагрузка в режим recovery.
adb root Перезапуск демона с правами root
adb usb Перезапуск демона, прослушивающего USB.
adb tcpip Перезапуск демона, прослушивающего порт TCP.
adb ppp [параметры] Запуск службы через USB.
Note: you should not automatically start a PPP connection. refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
Параметры:
defaultroute debug dump local notty usepeerdns
FastBoot — консольное приложение для PC. Используется для действий над разделами
fastboot devices Список присоединенных устройств в режиме fastboot.
fastboot flash Прошивает файл .img в раздел устройства.
fastboot erase Стереть раздел.
Разделы: boot, recovery, system, userdata, radio
Пример: fastboot erase userdata Стирание пользовательских данных.
fastboot update Прошивка из файла имя_файла.zip
fastboot flashall Прошивка boot + recovery + system.
fastboot getvar Показать переменные bootloader.
Пример: fastboot getvar version-bootloader Получить версию bootloader.
fastboot boot [ ] Скачать и загрузить kernel.
fastboot flash:raw boot [ ] Создать bootimage и прошить его.
fastboot devices Показать список подключенных устройств.
fastboot continue Продолжить с автозагрузкой.
fastboot reboot Перезагрузить аппарат.
f astboot reboot-bootloader Перезагрузить девайсв режим bootloader.
Перед командами fastboot можно использовать ключи:
-w стереть данные пользователя и кэш
-s Указать серийный номер устройства.
-p
Указать название устройства.
-c Переопределить kernel commandline.
-i Указать вручную USB vendor id.
-b Указать в ручную базовый адрес kernel.
-n
Указать размер страниц nand. по умолчанию 2048.
Команду logcat можно использовать с машины разработки
$ adb logcat
или из удаленного shell
# logcat Каждое сообщение лога в Android имеет тэг и приоритет
Тэг – это строка указывающая компонент системы, от которого принято сообщение (например: View для системы view)
Приоритет – имеет одно из нижеследующих значений (в порядке от меньшего к большему):
V — Verbose (Низший приоритет).
D — Debug
I — Info
W — Warning
E — Error
F — Fatal
S — Silent (Наивысший приоритет, при котором ничего не выводится).
Получить список тэгов, используемых в системе, вместе с их приоритетами можно запустив logcat. В первых двух столбцах каждого из выведенных сообщений будут указаны / .
Пример выводимого logcat сообщения:
I/ActivityManager( 585): Starting activity: Intent
Для уменьшения вывода лога до приемлемого уровня нужно использовать выражения фильтра. Выражения фильтра позволяют указать системе нужные комбинации и , остальные сообщения система не выводит.
Выражения фильтра имеют следующий формат : . где указывает нужный тэг, указывает минимальный уровень приоритета для выбранного тэга. Сообщения с выбранным тэгом и приоритетом на уровне или выше указанного записываются в лог. Можно использовать любое количество пар : в одном выражении фильтра. Для разделения пар : используется пробел.
Пример ниже выводит в лог все сообщения с тэгом «ActivityManager» с приоритетом «Info» или выше, и сообщения с тэгом «MyApp» и приоритетом «Debug» или выше:
adb logcat ActivityManager:I MyApp:D *:S
Последний элемент в выражении фильтра *:S устанавливает приоритет «silent» для всех остальных тэгов, тем самым обеспечивая вывод сообщений только для «View» и «MyApp». Использование *:S – это отличный способ для вывода в лог только явно указанных фильтров (т.е. в выражении фильтра указывается «белый список» сообщений, а *:S отправляет все остальное в «черный список»).
При помощи следующего выражения фильтра отображаются все сообщения с приоритетом «warning» или выше для всех тэгов:
adb logcat *:W
Если logcat запускается на машине разработчика (не через удаленный adb shell), можно также установить значение выражения фильтра по умолчанию задав переменную окружения ANDROID_LOG_TAGS:
export ANDROID_LOG_TAGS=»ActivityManager:I MyApp:D *:S»
Следует обратить внимание что задав переменную окружения ANDROID_LOG_TAGS она не будет работать в эмуляторе/устройстве, если вы будете использовать logcat в удаленном shell или используя adb shell logcat.
Вышеописанная команда export работает в ОС *nix и не работает в Windows.
Контроль формата вывода лога
Сообщения лога в дополнение к тэгу и приоритету содержат несколько полей метаданных. Можно изменять формат вывода сообщений показывая только конкретные поля метаданных. Для этого используется параметр -v и указывается один из ниже перечисленных форматов вывода.
brief Показывать приоритет/тэг и PID процесса (формат по умолчанию).
process Показывать только PID.
tag Показывать только приоритет/тэг.
thread Показывать только процесс:поток и приоритет/тэг.
raw Показать необработанное сообщение, без полей метаданных.
time Показывать дату, время вызова, приоритет/тэг и PID процесса.
long Показывать все поля метаданных и отдельно сообщения с пустыми строками.
При запуске logcat можно указать формат вывода используя параметр -v:
adb logcat [-v