More than one device emulator ошибка

$ adb --help

-s SERIAL  use device with given serial (overrides $ANDROID_SERIAL)

$ adb devices
List of devices attached 
emulator-5554   device
7f1c864e    device

$ adb shell -s 7f1c864e
error: more than one device and emulator

Penny Liu's user avatar

Penny Liu

15k5 gold badges78 silver badges93 bronze badges

asked Feb 1, 2013 at 20:46

Jackie's user avatar

adb -d shell (or adb -e shell).

This command will help you in most of the cases, if you are too lazy to type the full ID.

From http://developer.android.com/tools/help/adb.html#commandsummary:

-d — Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.

-e — Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.

answered Nov 23, 2013 at 13:40

Sazzad Hissain Khan's user avatar

4

Another alternative would be to set environment variable ANDROID_SERIAL to the relevant serial, here assuming you are using Windows:

set ANDROID_SERIAL=7f1c864e
echo %ANDROID_SERIAL%
"7f1c864e"

Then you can use adb.exe shell without any issues.

answered Feb 28, 2014 at 8:39

monotux's user avatar

monotuxmonotux

3,65528 silver badges29 bronze badges

3

To install an apk on one of your emulators:

First get the list of devices:

-> adb devices
List of devices attached
25sdfsfb3801745eg        device
emulator-0954   device

Then install the apk on your emulator with the -s flag:

-> adb -s "25sdfsfb3801745eg" install "C:Usersjoel.joelDownloadsrelease.apk"
Performing Streamed Install
Success

Ps.: the order here matters, so -s <id> has to come before install command, otherwise it won’t work.

Hope this helps someone!

Community's user avatar

answered Apr 10, 2019 at 19:56

pelican's user avatar

pelicanpelican

5,7768 gold badges40 silver badges67 bronze badges

I found this question after seeing the ‘more than one device’ error, with 2 offline phones showing:

C:Program Files (x86)Androidandroid-sdkandroid-tools>adb devices
List of devices attached
SH436WM01785    offline
SH436WM01785    offline
SH436WM01785    sideload

If you only have one device connected, run the following commands to get rid of the offline connections:

adb kill-server
adb devices

answered Dec 31, 2014 at 1:37

Danny Beckett's user avatar

Danny BeckettDanny Beckett

20.4k24 gold badges106 silver badges134 bronze badges

3

The best way to run shell on any particular device is to use:

adb -s << emulator UDID >> shell

For Example:
adb -s emulator-5554 shell

Theblockbuster1's user avatar

answered Jun 27, 2019 at 10:28

Shivam Bharadwaj's user avatar

As per https://developer.android.com/studio/command-line/adb#directingcommands

What worked for my testing:

UBUNTU BASH TERMINAL:

$ adb devices
List of devices attached 
646269f0    device
8a928c2 device
$ export ANDROID_SERIAL=646269f0
$ echo $ANDROID_SERIAL
646269f0
$ adb reboot bootloader

WINDOWS COMMAND PROMPT:

$ adb devices
List of devices attached 
646269f0    device
8a928c2 device
$ set ANDROID_SERIAL=646269f0
$ echo $ANDROID_SERIAL$
646269f0
$ adb reboot bootloader

This enables you to use normal commands and scripts as if there was only the ANDROID_SERIAL device attached.

Alternatively, you can mention the device serial every time.

$ adb -s 646269f0 shell

answered Jun 27, 2022 at 3:16

zeitgeist's user avatar

zeitgeistzeitgeist

80011 silver badges18 bronze badges

This gist will do most of the work for you showing a menu when there are multiple devices connected:

$ adb $(android-select-device) shell
1) 02783201431feeee device 3) emulator-5554
2) 3832380FA5F30000 device 4) emulator-5556
Select the device to use, <Q> to quit:

To avoid typing you can just create an alias that included the device selection as explained here.

answered Jun 3, 2016 at 19:54

Diego Torres Milano's user avatar

3

User @janot has already mentioned this above, but this took me some time to filter the best solution.

There are two Broad use cases:

1) 2 hardware are connected, first is emulator and other is a Device.
Solution : adb -e shell....whatever-command for emulator and adb -d shell....whatever-command for device.

2) n number of devices are connected (all emulators or Phones/Tablets) via USB/ADB-WiFi:

Solution:
Step1) run adb devices THis will give you list of devices currently connected (via USB or ADBoverWiFI)
Step2) now run adb -s <device-id/IP-address> shell....whatever-command
no matter how many devices you have.

Example
to clear app data on a device connected on wifi ADB I would execute:
adb -s 172.16.34.89:5555 shell pm clear com.package-id

to clear app data connected on my usb connected device I would execute:
adb -s 5210d21be2a5643d shell pm clear com.package-id

answered Sep 7, 2018 at 7:28

sud007's user avatar

sud007sud007

5,7844 gold badges56 silver badges63 bronze badges

For Windows, here’s a quick 1 liner example of how to install a file..on multiple devices

FOR /F "skip=1"  %x IN ('adb devices') DO start adb -s %x install -r myandroidapp.apk

If you plan on including this in a batch file, replace %x with %%x, as below

FOR /F "skip=1"  %%x IN ('adb devices') DO start adb -s %%x install -r myandroidapp.apk

answered Mar 14, 2018 at 19:19

zingh's user avatar

zinghzingh

3943 silver badges11 bronze badges

1

Create a Bash (tools.sh) to select a serial from devices (or emulator):

clear;
echo "====================================================================================================";
echo " ADB DEVICES";
echo "====================================================================================================";
echo "";

adb_devices=( $(adb devices | grep -v devices | grep device | cut -f 1)#$(adb devices | grep -v devices | grep device | cut -f 2) );

if [ $((${#adb_devices[@]})) -eq "1" ] && [ "${adb_devices[0]}" == "#" ]
then
    echo "No device found";
    echo ""; 
    echo "====================================================================================================";
    device=""
    // Call Main Menu function fxMenu;
else
    read -p "$(
        f=0
        for dev in "${adb_devices[@]}"; do
            nm="$(echo ${dev} | cut -f1 -d#)";
            tp="$(echo ${dev} | cut -f2 -d#)";
            echo " $((++f)). ${nm} [${tp}]";
        done

        echo "";
        echo " 0. Quit"
        echo "";

        echo "====================================================================================================";
        echo "";
        echo ' Please select a device: '
    )" selection

    error="You think it's over just because I am dead. It's not over. The games have just begun.";
    // Call Validation Numbers fxValidationNumberMenu ${#adb_devices[@]} ${selection} "${error}" 
    case "${selection}" in
        0)
            // Call Main Menu function fxMenu;
        *)  
            device="$(echo ${adb_devices[$((selection-1))]} | cut -f1 -d#)";
            // Call Main Menu function fxMenu;
    esac
fi

Then in another option can use adb -s (global option -s use device with given serial number that overrides $ANDROID_SERIAL):

adb -s ${device} <command>

I tested this code on MacOS terminal, but I think it can be used on windows across Git Bash Terminal.

Also remember configure environmental variables and Android SDK paths on .bash_profile file:

export ANDROID_HOME="/usr/local/opt/android-sdk/"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/tools:$PATH"

answered Mar 30, 2017 at 4:33

equiman's user avatar

equimanequiman

7,7102 gold badges44 silver badges47 bronze badges

2

you can use this to connect your specific device :

   * adb devices
  --------------
    List of devices attached
    9f91cc67    offline
    emulator-5558   device

example i want to connect to the first device «9f91cc67»

* adb -s 9f91cc67 tcpip 8080
---------------------------
restarting in TCP mode port: 8080

then

* adb -s 9f91cc67 connect 192.168.1.44:8080
----------------------------------------
connected to 192.168.1.44:8080

maybe this help someone

answered Apr 27, 2022 at 18:36

Hasni's user avatar

HasniHasni

1871 silver badge10 bronze badges

Here’s a shell script I made for myself:

#! /bin/sh

for device in `adb devices | awk '{print $1}'`; do
  if [ ! "$device" = "" ] && [ ! "$device" = "List" ]
  then
    echo " "
    echo "adb -s $device $@"
    echo "------------------------------------------------------"
    adb -s $device $@
  fi
done

answered Oct 2, 2019 at 23:38

Francois Dermu's user avatar

Francois DermuFrancois Dermu

4,4272 gold badges22 silver badges13 bronze badges

For the sake of convenience, one can create run configurations, which set the ANDROID_SERIAL:

screenshot

Where the adb_wifi.bat may look alike (only positional argument %1% and "$1" may differ):

adb tcpip 5555
adb connect %1%:5555

The advance is, that adb will pick up the current ANDROID_SERIAL.
In shell script also ANDROID_SERIAL=xyz adb shell should work.

This statement is not necessarily wrong:

-s SERIAL  use device with given serial (overrides $ANDROID_SERIAL)

But one can as well just change the ANDROID_SERIAL right before running the adb command.


One can even set eg. ANDROID_SERIAL=192.168.2.60:5555 to define the destination IP for adb.
This also permits to run adb shell, with the command being passed as «script parameters».

answered Feb 28, 2022 at 22:50

Martin Zeitler's user avatar

(master) $ adb -s emulator-5554 reverse tcp:8081 tcp:8081
error: more than one device/emulator
(master) $ adb devices -l
List of devices attached
emulator-5554          device product:sdk_gphone_x86 model:Android_SDK_built_for_x86 device:generic_x86 transport_id:2

Trying to deploy a react-native app to an emulated device. The build, gradle etc runs fine but when trying to connect to the emulator it shows an error more than one device/emulator despite there only being one device when running adb devices

Literally no idea how to solve this, Android Studio 3.1, emulated device is a Nexus 5x running Android 8. Have restarted, upgraded etc but still get this message.

I’ve connect my device via TCPIP at 5555 port.

Result of adb devices

adb devices
List of devices attached
192.168.0.107:5555      device

Device IP: 192.168.0.107:5555

Running scrcpy gives the result:

INFO: scrcpy 1.10 <https://github.com/Genymobile/scrcpy>
D:scrcpyscrcpy-server.jar: 1 file pushed. 1.6 MB/s (22546 bytes in 0.013s)
adb.exe: error: more than one device/emulator
ERROR: "adb reverse" returned with value 1
WARN: 'adb reverse' failed, fallback to 'adb forward'
27183
INFO: Initial texture: 720x1280
[server] ERROR: Exception on thread Thread[main,5,main]
java.lang.IllegalStateException
        at android.media.MediaCodec.native_dequeueOutputBuffer(Native Method)
Press any key to continue...

I tried using scrcpy -s 192.168.0.107:5555 as the ip address was returned as the device serial when using adb devices

Which gave the same issue.

Then I used adb shell getprop ro.serialno to get my device’s serial no ; 8HUW4HV4Y9SSR4S8

Then with this new serial no I tried: scrcpy -s 8HUW4HV4Y9SSR4S8 which gave a new error:

INFO: scrcpy 1.10 <https://github.com/Genymobile/scrcpy>
adb: error: failed to get feature set: device '8HUW4HV4Y9SSR4S8' not found
ERROR: "adb push" returned with value 1
Press any key to continue...

This might be because the device is not connected via usb and the default serial returned is the Local ip address.

I’ve tried all previous solutions. Did not work.

На чтение 5 мин. Опубликовано 15.12.2019

Используйте -s ПЕРЕД командой, чтобы указать устройство, например:

adb -d shell (или adb -e shell , если вы подключаетесь к эмулятору).

Эта команда поможет вам в большинстве случаев, если вам слишком ленив, чтобы ввести полный идентификатор.

-d — Направьте команду adb на только подключенное USB-устройство. Возвращает ошибку при подключении более одного USB-устройства.

-e — Направить команду adb на единственный запущенный эмулятор. Возвращает ошибку при запуске более одного эмулятора.

Другой альтернативой было бы установить переменную среды ANDROID_SERIAL для соответствующего серийного номера, при условии, что вы используете Windows:

Затем вы можете использовать adb.exe shell без каких-либо проблем.

Я нашел этот вопрос, увидев ошибку «более одного устройства», с двумя автономными телефонами, показывающими:

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

Этот gist будет выполнять большую часть работы за то, что вы показываете меню при подключении нескольких устройств:

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

Создайте bash (adb +)

сделано используйте его с помощью

Пользователь @janot уже упоминал об этом выше, но мне потребовалось некоторое время, чтобы отфильтровать лучшее решение.

Существует два варианта использования:

1) 2 устройства подключены, первый — эмулятор, другой — устройство.
Решение: adb -e shell. whatever-command для эмулятора и adb -d shell. whatever-command для устройства.

2) подключено n устройств (все эмуляторы или телефоны/планшеты) через USB/ADB-WiFi:

Решение: Шаг 1) запустите adb devices Это даст вам список подключенных устройств (через USB или ADBoverWiFI).
Шаг 2) Теперь запустите adb -s shell. whatever-command от того, сколько у вас устройств.

12 Answers 12

Use the -s option BEFORE the command to specify the device, for example:

adb -d shell (or adb -e shell if you’re connecting to an emulator).

This command will help you in most of the cases, if you are too lazy to type the full ID.

-d — Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.

-e — Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.

Another alternative would be to set environment variable ANDROID_SERIAL to the relevant serial, here assuming you are using Windows:

Then you can use adb.exe shell without any issues.

I found this question after seeing the ‘more than one device’ error, with 2 offline phones showing:

If you only have one device connected, run the following commands to get rid of the offline connections:

This gist will do most of the work for you showing a menu when there are multiple devices connected:

To avoid typing you can just create an alias that included the device selection as explained here.

User @janot has already mentioned this above, but this took me some time to filter the best solution.

There are two Broad use cases:

1) 2 hardware are connected, first is emulator and other is a Device.
Solution : adb -e shell. whatever-command for emulator and adb -d shell. whatever-command for device.

2) n number of devices are connected (all emulators or Phones/Tablets) via USB/ADB-WiFi:

Solution: Step1) run adb devices THis will give you list of devices currently connected (via USB or ADBoverWiFI)
Step2) now run adb -s shell. whatever-command no matter how many devices you have.

Не следует вводить:

adb -d shell

Эта команда поможет вам в большинстве случаев, если вам слишком ленив, чтобы ввести полный идентификатор

Целевое устройство
-d Направить только команду adb на только подключенное USB-устройство.
-e Направить команду adb на единственный исполняемый экземпляр эмулятора.

Оба возвращают ошибку, если запущено более одного экземпляра каждого типа.

Другой альтернативой было бы установить переменную среды ANDROID_SERIAL для соответствующего серийного номера, при условии, что вы используете Windows:

Тогда вы можете использовать adb.exe shell без каких-либо проблем.

Я нашел этот вопрос, увидев ошибку «более одного устройства», с двумя автономными телефонами, показывающими:

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

Выполнение команд adb на всех подключенных устройствах

Создайте bash (adb +)

Сделать это с помощью

Этот принцип будет выполнять большую часть работы для вас, показывая меню при подключении нескольких устройств:

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

Создайте Bash (tools.sh), чтобы выбрать серию из устройств (или эмулятора):

Затем в другом варианте можно использовать adb -s (глобальный параметр -s использовать устройство с заданным серийным номером, который переопределяет $ ANDROID_SERIAL):

Я тестировал этот код на терминале MacOS, но я думаю, что он может использоваться в окнах через терминал Git Bash.

Также помните, как настроить параметры среды и пути Android SDK в файле .bash_profile :

7 ответов

janot
01 фев. 2013, в 23:00

Поделиться

adb -d shell (или adb -e shell, если вы подключаетесь к эмулятору).

Эта команда поможет вам в большинстве случаев, если вам слишком ленив, чтобы ввести полный идентификатор.

Из http://developer.android.com/tools/help/adb.html#commandsummary:

-d — Направьте команду adb на только подключенное USB-устройство. Возвращает ошибку при подключении более одного USB-устройства.

-e — Направить команду adb на единственный запущенный эмулятор. Возвращает ошибку при запуске более одного эмулятора.

Sazzad Hissain Khan
23 нояб. 2013, в 15:20

Поделиться

Другой альтернативой было бы установить переменную среды ANDROID_SERIAL для соответствующего серийного номера, при условии, что вы используете Windows:

set ANDROID_SERIAL="7f1c864e"
echo %ANDROID_SERIAL%
"7f1c864e"

Затем вы можете использовать adb.exe shell без каких-либо проблем.

monotux
28 фев. 2014, в 09:34

Поделиться

Я нашел этот вопрос, увидев ошибку «более одного устройства», с двумя автономными телефонами, показывающими:

C:Program Files (x86)Androidandroid-sdkandroid-tools>adb devices
List of devices attached
SH436WM01785    offline
SH436WM01785    offline
SH436WM01785    sideload

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

adb kill-server
adb devices

Danny Beckett
31 дек. 2014, в 03:11

Поделиться

Этот gist будет выполнять большую часть работы за то, что вы показываете меню при подключении нескольких устройств:

$ adb $(android-select-device) shell
1) 02783201431feeee device 3) emulator-5554
2) 3832380FA5F30000 device 4) emulator-5556
Select the device to use, <Q> to quit:

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

Diego Torres Milano
03 июнь 2016, в 21:02

Поделиться

Выполнение команд adb на всех подключенных устройствах

Создайте bash (adb +)

adb devices | while read line
do
if [ ! "$line" = "" ] && [ `echo $line | awk '{print $2}'` = "device" ]
then
    device=`echo $line | awk '{print $1}'`
    echo "$device $@ ..."
    adb -s $device $@
fi

сделано
используйте его с помощью

adb +//+ команда

Shivaraj Patil
03 апр. 2015, в 13:06

Поделиться

Создайте Bash (tools.sh), чтобы выбрать серию из устройств (или эмулятора):

clear;
echo "====================================================================================================";
echo " ADB DEVICES";
echo "====================================================================================================";
echo "";

adb_devices=( $(adb devices | grep -v devices | grep device | cut -f 1)#$(adb devices | grep -v devices | grep device | cut -f 2) );

if [ $((${#adb_devices[@]})) -eq "1" ] && [ "${adb_devices[0]}" == "#" ]
then
    echo "No device found";
    echo ""; 
    echo "====================================================================================================";
    device=""
    fxMenu;
else
    read -p "$(
        f=0
        for dev in "${adb_devices[@]}"; do
            nm="$(echo ${dev} | cut -f1 -d#)";
            tp="$(echo ${dev} | cut -f2 -d#)";
            echo " $((++f)). ${nm} [${tp}]";
        done

        echo "";
        echo " 0. Quit"
        echo "";

        echo "====================================================================================================";
        echo "";
        echo ' Please select a device: '
    )" selection

    error="You think it over just because I am dead. It not over. The games have just begun.";
    fxValidationNumberMenu ${#adb_devices[@]} ${selection} "${error}" 
    case "${selection}" in
        0)
            fxMenu;;
        *)  
            device="$(echo ${adb_devices[$((selection-1))]} | cut -f1 -d#)";
            fxMenu;;
    esac
fi

Затем в другой опции можно использовать adb -s (глобальная опция — использовать устройство с заданным серийным номером, который переопределяет $ANDROID_SERIAL):

adb -s ${device} <command>

Я тестировал этот код на терминале MacOS, но я думаю, что его можно использовать в окнах через Git Bash Terminal.

Также помните, как настраивать переменные окружения и пути Android SDK в файле .bash_profile:

export ANDROID_HOME="/usr/local/opt/android-sdk/"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/tools:$PATH"

Equiman
30 март 2017, в 06:14

Поделиться

Ещё вопросы

  • 1Создать новый фрейм данных на основе строк с определенным значением
  • 1ByteArrayOutputStream для шортов вместо байтов
  • 0некоторые персонажи ведут себя необычно в функции htmlentities
  • 1Как измерить время отклика на действия в приложениях Android?
  • 1Отдых не может быть разрешен к типу
  • 1Как панды заменяют значения NaN средним значением, используя groupby [duplicate]
  • 0Реализация класса List Ошибка выделения памяти с указателем
  • 0C ++: файловый ввод / вывод с трудностями при открытии и работе с ним
  • 1Как загрузить открытый набор данных s3 в коллаборацию Google?
  • 0ОШИБКА: cout c ++ необъявленный
  • 0Добавление 1 дня к метке времени в PHP
  • 0Изображение после sql результата Combobox PHP
  • 0ngRepeat с $ scope. $ apply создает дубликаты в директиве
  • 1как передать объект коллекции в response.sendRedirect
  • 0Сортировка списка с помощью jquery UI
  • 0Mysql запрос оптимизации или сократить запрос
  • 0Установка MySQL в Red Hat Linux с использованием замазки SSH
  • 0Microsoft Visual Studio C ++ 2010 Exp — Компиляция в порядке, но не работает
  • 1Функция apply (), вызываемая на Function.prototype.bind в JavaScript?
  • 1Невозможно отсортировать данные с Comparator в Android
  • 1Обработка пользовательских сообщений об ошибках в веб-API
  • 0PHP-файл с HTML в нем комментирует PHP
  • 1Сегментация изображения в openCV
  • 0Как работает символ $ в jquery? [Дубликат]
  • 0Невозможно использовать цепной локатор в транспортире
  • 1Уведомления не получаются на устройство, но получают успех на FCM, в чем проблема?
  • 1Проблема с определением размеров JTextFields
  • 0Запрет прокрутки скрипта jquery от запуска дважды
  • 0как управлять стилем HTML кода в Qprinter
  • 1Получить статус погоды нескольких мест внутри для петли Android
  • 0Проблемы понимания ассоциаций в Sequelize для энергичной загрузки
  • 1Офлайновые фрагменты в объемных данных
  • 1Как найти этот Выходной и следующий Выходной с текущей даты?
  • 0Переместить следующий узел назад
  • 1Потокобезопасный объект доступа к данным C #
  • 0C ++: при возврате адреса переменной члена класса компилятор заставляет его иметь тип const *
  • 0Угловое расширение директивы
  • 1Ссылки на перевод Google не работают последовательно из Android WebView
  • 0Инициировать событие jQuery (bPopup) для выбранного значения раскрывающегося списка.
  • 0нг-включить не включая шаблон
  • 0SQL-запрос ORDER BY с предложением WHERE
  • 0Javascript Если заявление не работает в автозаполнении
  • 1Ошибка зависимости весны в моем файле POM
  • 1Plotly Python: выравнивание осей X на сгруппированной гистограмме с несколькими осями Y
  • 0CSS выровнять div с текстовым полем
  • 0Идентификация элементов по постоянному классу и динамическому идентификатору
  • 0Вставка CSS-идентификатора в jQuery
  • 0jqGrid с использованием navGrid с position = right не работает
  • 0Проблема с запросом MySQL — сопоставление нескольких идентификаторов в объединенной таблице
  • 1Платеж Android в приложении пропущен, чтобы пометить отзыв при возврате

  • Mordhau ошибка a pak file could not be loaded
  • Modulenotfounderror no module named requests ошибка
  • Mordhau the pack file ошибка
  • Modulenotfounderror no module named pip ошибка
  • Mora газовый котел коды ошибок