Как через adb установить apk
Platform-tools: r34.0.4 rev.2
ADB: 1.0.41 (34.0.4-10411341)
Fastboot: 34.0.4-10411341
Make_f2fs (casefold): 1.16.0 (2023-04-11)
Mke2fs: 1.46.6 (1-Feb-2023)
Последнее обновление утилит в шапке: 27.07.2023
- Посмотреть какие устройства подключены и могут работать с ADB.
- Просматривать логи.
- Копировать файлы с/на аппарат.
- Устанавливать/Удалять приложения.
- Удалять (очищать) раздел data.
- Прошивать (перезаписывать) раздел data.
- Осуществлять различные скрипты управления.
- Управлять некоторыми сетевыми параметрами.
Если что-то неправильно, то в списке подключенных устройств (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> <путь на андроид> Копировать файл/папку PC->девайс.
adb pull <путь на андроид> [<путь на PC>] Копировать файл/папку девайс->PC.
adb sync [<каталог>] Копировать PC->девайс только новые файлы.
Ключи:
-l Не копировать, только создать список.
adb shell Запуск упрощенного unix shell.
Примеры использования
adb emu <команда> Послать команду в консоль эмулятора
adb install [-l] [-r] [-s] <название_приложения.apk> Послать приложение на устройство и установить его.
Пример: adb install c:/adb/app/autostarts.apk Установить файл autostarts.apk лежащий в папке /adb/app/ на диске с:
Ключи:
-l Блокировка приложения
-r Переустановить приложение, с сохранением данных
-s Установить приложение на карту памяти
Установка split apk
adb uninstall [-k] <название_приложения.apk> Удаление приложения с устройства.
Ключи:
-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 <tty> [параметры] Запуск службы через USB.
Note: you should not automatically start a PPP connection. <tty> 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> Прошивка из файла имя_файла.zip
fastboot flashall Прошивка boot + recovery + system.
fastboot getvar <имя_переменной> Показать переменные bootloader.
Пример: fastboot getvar version-bootloader Получить версию bootloader.
fastboot boot <kernel> [<ramdisk>] Скачать и загрузить kernel.
fastboot flash:raw boot <kernel> [<ramdisk>] Создать bootimage и прошить его.
fastboot devices Показать список подключенных устройств.
fastboot continue Продолжить с автозагрузкой.
fastboot reboot Перезагрузить аппарат.
f astboot reboot-bootloader Перезагрузить девайсв режим bootloader.
Перед командами fastboot можно использовать ключи:
-w стереть данные пользователя и кэш
-s <серийный номер> Указать серийный номер устройства.
-p <product> Указать название устройства.
-c <cmdline> Переопределить kernel commandline.
-i <vendor id> Указать вручную USB vendor id.
-b <base_addr> Указать в ручную базовый адрес kernel.
-n <page size> Указать размер страниц 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 <format>]
Пример, который показывает сообщения в формате thread:
adb logcat -v thread
Нужно отметить, что можно использовать только один формат с параметром -v.
Просмотр альтернативного буфера лога
Система логов Android держит несколько кольцевых буферов для лога сообщений и не все сообщения отправляются в основной буфер. Для отображения дополнительных сообщений лога нужно запустить logcat с параметром -b.
Таким образом можно посмотреть один из альтернативных буферов:
radio Просмотр буфера с сообщениями связанными с радио/телефоном.
events Просмотр буфера с сообщениями связанными с событиями.
main Просмотр основного буфера (по умолчанию).
Пример ниже показывает буфер с радио и телефонными сообщениями:
adb logcat -b radio
Просмотр stdout и stderr
По умолчанию система Android шлет вывод stdout и stderr (System.out и System.err) в /dev/null (удаляет). В процессах, которые выполняются в виртуальной машине Dalvik (Dalvik VM) может осуществляться запись копии вывода в лог файл. В этом случае система записывает сообщения в лог используя тэги stdout и stderr с приоритетом I.
Для перенаправления вывода нужно остановить эмулятор/устройство, затем выполнить команду shell setprop для включения перенаправления вывода. Пример того как это делается:
$ adb shell stop
$ adb shell setprop log.redirect-stdio true
$ adb shell start
Система сохраняет эту настройку, пока работает эмулятор/устройство. Чтобы использовать эту настройку по умолчанию в эмуляторе/устройстве, нужно добавить эту команду в /data/local.prop в эмуляторе/устройстве.
Список параметров команды logcat
-b <buffer> Загрузить альтернативный буфер лога для просмотра, такой как event или radio. Основной буфер используется по умолчанию.
-c Очистить (сбросить) лог и выйти.
-d Вывести лог на экран и выйти.
-f <filename> Записать сообщения лога в файл <filename>. По умолчанию в stdout.
-g Вывести размер указанного буфера лога и выйти.
-n <count> Установить максимальное количество ротаций лога (количество хранимых сжатых фрагментов лога) <count>. По умолчанию 4. Требует параметр -r.
-r <kbytes> Выполнять ротацию каждые <kbytes> вывода (разделять лог на фрагменты по <kbytes>). По умолчанию 16. Требует параметр -f.
-s Устанавливает silent фильтром по умолчанию.
-v <format> Устанавливает формат вывода сообщений лога. По умолчанию brief.
How To Install Apk Using Adb Commands
Now, the described method requires you to have direct access to your device but consider a situation where accidentally some system file gets damaged. This causes your UI to crash and leaving you with no way to access your phone. The only way to resolve the issue is to install a third-party UI app so that the device starts working again. This is where ADB comes in. It allows you to control your device using a computer. It is the only way in which you can install apps on your device in a situation like this. Well, this is just one of many scenarios where ADB could be a lifesaver. Therefore, it would only do you good if you knew more about ADB and learned how to use it and that’s exactly what we are going to do. We are going to discuss what is ADB and how it works. We will also take you through the various steps involved in the process of setting up and then using ADB to install apps on your device.
How to Install APK Using ADB Commands#
What is ADB?#
ADB stands for Android Debug Bridge. It is a command-line tool that is a part of the Android SDK (Software Development Kit). It allows you to control your Android smartphone using a PC provided that your device is connected to the computer via a USB cable. You can use it to install or uninstall apps, transfer files, get information about network or Wi-Fi connection, check battery status, take screenshots or screen recording and so much more. It has a set of codes that allow you to perform various operations on your device. As a matter of fact, ADB is a very powerful tool that is capable of performing advanced operations that a good amount of practice and training to master. The more you explore the world of coding, the more useful ADB will become for you. However, for the sake of keeping things simple, we are just going to cover some basics and mainly teach you how to install an APK using ADB.
How to Install APK Using ADB Commands What is ADB? How does it work? What are the various Pre-requisites for using ADB? How to Download and Install ADB on Windows? How to Use ADB to install APK on your device? Other Important ADB Commands
How does it work?#
ADB uses USB debugging to take control of your device. When connected to a computer using a USB cable, ADB client is able to detect the connected device. It uses a command line or command prompt as the medium to relay the commands and information between the computer and the Android device. There are special codes or commands which allow you to control the processes and operations on your Android device.
What are the various Pre-requisites for using ADB?#
Now, before you can install APK using ADB commands, you need to make sure the following pre-requisites are met.
- The first thing that you need is to make sure that the device’s driver is installed on your PC. Every Android smartphone comes with its own device driver that automatically gets installed when you connect your phone to your PC. If your device does not have one then you need to download the driver separately. For Google devices like Nexus, you can find just install Google USB Driver which is a part of SDK (we will discuss this later). Other companies like Samsung, HTC, Motorola, etc. provide drivers on their respective sites.
- The next thing that you need is to enable USB debugging on your Android smartphone. The option to do so can be found under Developer options. First, enable the Developer Options from the Settings menu.
After that, you need to enable USB debugging from the Developer options. a. Open Settings and click on the System option.
b. Now, tap on Developer options.
c. Scroll down and under the Debugging section, you will find the setting for USB debugging. Simply toggle on the switch and you are good to go.
- Last but not least, you need to download and install ADB on your computer. We will discuss this in the next section and guide you through the entire installation process.
How to Download and Install ADB on Windows?#
As mentioned earlier, ADB is a part of the Android SDK and thus, you need to download the entire setup package for the tool kit. Follow the steps given below to download and install ADB on Windows 10:
Click here to go to the downloads page for Android SDK platform tools.
Now, click on the “Download SDK Platform-Tools for Windows” button. You can select the other options as well depending upon the operating system that you are using.
Agree to the Terms and Conditions and click on the Download button.
Once the zip file is downloaded, extract it at a location where you want to save the tool kit files.
You will be able to see the ‘ADB’ present in the folder along with other tools. The installation process is now complete. We will now be moving to the next step that is using ADB to install APK on your device.
How to Use ADB to install APK on your device?#
Before you proceed to install APK using ADB commands, you need to make sure that ADB is set up properly and the device connected is being detected properly.
To do this, connect your Android device to the computer and then open the folder containing the SDK platform tools.
In this folder, hold down Shift and then right-click. From the menu select the “Open Command window here” option. If the option to open the command window is not available, then click on the “Open PowerShell window here”.
Now, in the Command Prompt window/PowerShell window type the following code: “.\adb devices” and press Enter.
This will display the name of your device in the command window.
If it does not, then there is a problem with the device’s driver.
There is a simple solution to this problem. Go to the search bar on your computer and open Device Manager.
Your Android device will be listed there. Right-click on it and simply tap on the update driver option.
Next, click on the option to look for Drivers online. If there are any new drivers available then they will automatically get downloaded and installed on your computer.
Now, go back to command prompt/PowerShell window and type the same command provided above and press Enter. You will now be able to see the name of the device displayed on the screen. This confirms that ADB has been successfully set up and your device is connected properly. You can now perform any operations on your phone using the ADB commands. These commands need to be entered in the Command Prompt or PowerShell window. In order to install an APK on your device via ADB, you need to have the APK file stored on your computer. Let us assume that we are installing the APK file for the VLC media player. Follow the steps given below to install the app on your device:
The first thing that you need to do is move the APK file to the folder containing the SDK platform tools. This will make it easier as you would not have to type the entire path for the location of the APK file separately.
Next, open the command prompt window or PowerShell window and type in the following command: “adb install ” where the app name is the name of the APK file. In our case, it will be “VLC.apk”
Once the installation is complete, you will be able to see the message “Success” displayed on your screen. Recommended:
Fix Screen Burn-in on AMOLED or LCD display How to Turn Off Safe Mode on Android
Thus, you have now successfully learned how to install APK using ADB commands. However, as mentioned above ADB is a powerful tool and can be used to perform various other operations. All that you need to know is the correct code and syntax and you will be able to do so much more. In the next section, we have a little bonus for you. We will be listing down certain selected important commands that you can try and have fun experimenting with.
Install an apk file from command prompt?
I want to install a file using the Windows command line. First I want to build after compiling all the .jar files to create an .apk file for an Android application without using Eclipse.
Does anyone know how this can be done without the use of Eclipse & only by making use of command line.
14 Answers 14
You can use the code below to install application from command line
this apk is installed in the internal memory of current opened emulator.
this apk is installed in the sd-card of current opened emulator.
You can also install an apk to specific device in connected device list to the adb.
Refer also to adb help for other options.
You can build on the command line with ant. See this guide.
Then, you can install it by using adb on the command line.
The -r flag is to replace the existing application.
Use the Android Debug Bridge command line tool adb eg: adb install filename.apk .
A good reference for adb is Here
You can install an apk to a specific device/emulator by entering the device/emulator identifier before the keyword ‘install’ and then the path to the apk. Note that the -s switch, if any, after the ‘install’ keyword signifies installing to the sd card. Example:
The simple way to do that is by command
and if you want to target connect device you can add parameter » -d «
if you have more than one device/emulator connected you will get this error
adb: error: connect failed: more than one device/emulator — waiting for device — error: more than one device/emulator
to avoid that you can list all devices by below command
you will get results like below
chose one of these devices and add parameter to adb command as » -s a3b09hh3e » as below
also as a hint if the path of the apk long and have a spaces, just add it between double quotes like
What is adb?
Android Debug Bridge (adb) is a command-line tool that lets you communicate with an Android device. It facilitates a variety of device actions, such as installing and debugging apps. There are several other facilities that adb provides. For more information about adb, visit here.
How adb works?
When you start an adb client it locates the connected devices (emulator or actual device connected through USB). Once the devices are located, you can run the adb commands to control those devices. adb is included in the Android SDK Platform-Tools package (if you’ve Android Studio installed). 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 download it here.
How to run adb commands?
Considering you have Android Studio installed in your Mac, you have two ways to run adb commands —
To be able to run adb commands directly from any directory in the terminal, perform the following steps —
What you’re doing here is you’re changing the global PATH variable to the platform_tools path. The system will use this path to run all the adb commands. You can now run any adb command in your terminal.
If you don’t want to set the global PATH variable, you must be in the paltform_tools folder on your terminal to run adb commands. The adb executable is generally found at
Now onwards, make sure you prefix all the adb commands with ./
For eg: ./adb devices
You may get an error saying adb command not found. The above setup should resolve your issue. If you still face the same problem, refer to this Stack Overflow link and follow the approaches mentioned by the people.
How to install apk on your device/emulator using adb command?
Run adb devices command on your terminal. This command prints all the connected devices and emulators with your Mac. Here is the sample data printed by this command —
G070VM0583750P7T device
emulator-5554 device
You get a serial number of the device along with its status (offline/device/no-device). In the above example, G070VM0583750P7T is the serial number of my Fire TV. You can also run adb devices -l to get more info about the connected devices.
Run adb -s <serial_number> install <apk_path> to install your apk on the device. Make sure you replace <serial_number> with the actual serial number of the device printed by adb devices command. Also <apk_path> should be replaced by the local path of your apk.
If you have only one device/emulator connected to your Mac, simply run adb install <apk_path>. This will install the apk on the only connected device.