В состав Android SDK входит эмулятор Android-устройства — виртуальное устройство, работающее на вашем компьютере. Эмулятор Android позволяет разрабатывать и тестировать приложения для Android без использования физического устройства.
На этой странице описаны функции командной строки, которые можно использовать с эмулятором Android. Информацию об использовании пользовательского интерфейса эмулятора Android см. в разделе «Запуск приложений в эмуляторе Android» .
Запустите эмулятор
Используйте команду emulator для запуска эмулятора, это альтернатива запуску вашего проекта или запуску его через AVD Manager .
Вот базовый синтаксис командной строки для запуска виртуального устройства из терминала:
emulator -avd avd_name [ {-option [value]} … ]
Или
emulator @avd_name [ {-option [value]} … ]
Например, если вы запустите эмулятор из Android Studio, работающей на Mac, стандартная командная строка будет выглядеть примерно так:
/Users/janedoe/Library/Android/sdk/emulator/emulator -avd Pixel8_API_34 -netdelay none -netspeed full -qt-hide-window -grpc-use-token -idle-grpc-timeout
Обратите внимание, что аргументы -qt-hide-window -grpc-use-token -idle-grpc-timeout используются только для запуска окна эмулятора в Android Studio. Если вы хотите запустить эмулятор в отдельном окне, не используйте эти дополнительные параметры.
Вы можете указать параметры запуска при запуске эмулятора, но не после его запуска.
Чтобы получить список имен AVD, введите следующую команду:
emulator -list-avds
Используйте эту опцию для отображения списка имен AVD из домашнего каталога Android. Вы можете переопределить домашний каталог по умолчанию, установив переменную среды ANDROID_SDK_HOME , которая указывает корневой каталог пользователя, где хранится вся конфигурация и содержимое AVD.
Вы можете установить переменную среды в окне терминала перед запуском виртуального устройства или через пользовательские настройки в операционной системе. Например, в файле .bashrc в Linux.
Чтобы остановить эмулятор Android, закройте окно эмулятора.
Установите приложение
Помимо установки приложения через Android Studio или пользовательский интерфейс эмулятора , вы можете установить приложение на виртуальное устройство, используя утилиту adb .
Чтобы использовать adb для установки, запуска и тестирования вашего приложения, выполните следующие общие шаги:
- Соберите и упакуйте ваше приложение в APK-файл, как описано в разделе «Сборка и запуск приложения» .
- Запустите эмулятор из командной строки, как описано в предыдущем разделе, используя все необходимые параметры запуска.
- Установите приложение с помощью
adb. - Запустите и протестируйте свое приложение на эмуляторе.
Во время работы эмулятора вы можете использовать консоль эмулятора для выполнения необходимых команд.
Чтобы удалить приложение, сделайте это так же, как и на устройстве Android.
Виртуальное устройство сохраняет приложение и данные о его состоянии после перезапусков в разделе пользовательских данных на диске ( userdata-qemu.img ). Чтобы очистить эти данные, запустите эмулятор с параметром -wipe-data или очистите данные в диспетчере AVD. Дополнительную информацию о разделе пользовательских данных и других хранилищах см. в следующем разделе.
Примечание: Утилита adb рассматривает виртуальное устройство как реальное физическое устройство. По этой причине вам может потребоваться использовать флаг -d с некоторыми распространенными командами adb , такими как install . Флаг -d позволяет указать, какое из нескольких подключенных устройств использовать в качестве цели команды. Если вы не укажете -d , эмулятор выберет первое устройство в своем списке.
Разберитесь с каталогами и файлами по умолчанию.
Эмулятор использует связанные файлы, из которых наиболее важными являются системный и файловый каталоги AVD. Понимание структуры каталогов и файлов эмулятора полезно при указании параметров командной строки, хотя обычно нет необходимости изменять каталоги или файлы по умолчанию.
Эмулятор Android использует гипервизор ( QEMU ).
Системный каталог AVD
В системном каталоге находятся образы системы Android, которые эмулятор использует для имитации операционной системы. В этом каталоге находятся файлы, доступные только для чтения и специфичные для каждой платформы, используемые всеми AVD одного типа, включая файлы уровня API, архитектуры процессора и варианта Android. Расположение файлов по умолчанию следующее:
- macOS и Linux -
~/Library/Android/sdk/system-images/android- apiLevel / variant / arch / - Windows -
C:\Users\ user \Library\Android\sdk\system-images\android- apiLevel \ variant \ arch \
Где:
-
apiLevel— это числовой уровень API или буква для предварительных версий. Например,android-Vобозначает предварительную версию Android VanillaIceCream. После выпуска он стал уровнем API 35, обозначенным какandroid-35. -
variant— это имя, соответствующее конкретным функциям, реализованным в образе системы. Например,google_apisилиandroid-wear. -
arch— это целевая архитектура процессора. Например,x86.
Используйте параметр -sysdir , чтобы указать другой системный каталог для AVD.
Эмулятор считывает следующие файлы из системного каталога:
Таблица 1. Файлы системного каталога, считываемые эмулятором Android.
| Файл | Описание | Возможность указать другой файл |
|---|---|---|
kernel-qemu или kernel-ranchu | Двоичный образ ядра для AVD. kernel-ranchu основан на эмуляторе QEMU. | -kernel |
ramdisk.img | Образ загрузочного раздела. Это подмножество файла system.img , загружаемое ядром изначально, до монтирования образа системы. Обычно он содержит всего несколько исполняемых файлов и скриптов инициализации. | -ramdisk |
system.img | Исходная версия образа системы, доступная только для чтения. В частности, это раздел, содержащий системные библиотеки и данные, соответствующие уровню и варианту API. | -system |
userdata.img | Начальная версия раздела данных, который отображается как data/ в эмулируемой системе и содержит все доступные для записи данные для AVD. Эмулятор использует этот файл при создании нового AVD или при использовании опции ‑wipe-data . Для получения дополнительной информации см. описание файла userdata-qemu.img в следующем разделе. | -initdata-init-data |
Каталог данных AVD
Каталог данных AVD, также называемый каталогом содержимого, является специфическим для конкретного экземпляра AVD и содержит все изменяемые данные для этого AVD.
Местоположение по умолчанию следующее, где name — это имя AVD:
- macOS и Linux -
~/.android/avd/ name .avd/ - Windows 10 и выше -
C:\Users\ user \.android\ name .avd\
Используйте параметр -datadir , чтобы указать другой каталог данных AVD.
В таблице ниже перечислены наиболее важные файлы, содержащиеся в этом каталоге:
Таблица 2. Важные файлы в каталоге данных AVD.
| Файл | Описание | Возможность указать другой файл |
|---|---|---|
userdata-qemu.img | Содержимое раздела данных, который в эмулируемой системе отображается как Каждый экземпляр виртуального устройства использует записываемый образ пользовательских данных для хранения данных, специфичных для пользователя и сессии. Например, он использует образ для хранения данных об установленных приложениях, настройках, базах данных и файлах уникального пользователя. У каждого пользователя есть свой каталог | -data |
cache.img | Образ раздела кэша, который отображается в эмулируемой системе как cache/ . Он пуст при первом создании AVD или использовании параметра -wipe-data . В нем хранятся временные файлы для загрузки, и он заполняется менеджером загрузок, а иногда и самой системой. Например, браузер использует его для кэширования загруженных веб-страниц и изображений во время работы эмулятора. При выключении виртуального устройства файл удаляется. Вы можете сохранить файл, используя параметр -cache . | -cache |
sdcard.img | (Необязательно) Образ раздела SD-карты, позволяющий имитировать SD-карту на виртуальном устройстве. Вы можете создать файл образа SD-карты в AVD Manager или с помощью инструмента При определении AVD в диспетчере AVD можно выбрать использование автоматически управляемого файла SD-карты или файла, созданного с помощью инструмента Вы можете просматривать, отправлять и удалять файлы с имитированной SD-карты, используя пользовательский интерфейс эмулятора или утилиту Чтобы скопировать файлы на SD-карту перед загрузкой, смонтируйте образ как циклическое устройство, а затем скопируйте файлы. Или используйте утилиту, например, пакет Эмулятор рассматривает файл как набор байтов, поэтому формат SD-карты не имеет значения. Параметр | -sdcard |
Список каталогов и файлов, используемых эмулятором.
Узнать местоположение файлов можно двумя способами:
- При запуске эмулятора из командной строки используйте параметр
-debug init-verboseили -debug. Посмотрите на вывод. - Используйте команду
-help- optionemulator, чтобы вывести список каталогов по умолчанию. Например:emulator -help-datadir
Use '-datadir <dir>' to specify a directory where writable image files will be searched. On this system, the default directory is: /Users/me/.android See '-help-disk-images' for more information about disk image files.
Параметры запуска из командной строки
В этом разделе перечислены параметры, которые можно указать в командной строке при запуске эмулятора.
Примечание: Эмулятор Android постоянно находится в разработке для повышения его надежности. Для получения информации о проблемах, связанных с различными параметрами командной строки, и для сообщения об ошибках, см. систему отслеживания ошибок Android .
Часто используемые варианты
В таблице ниже перечислены параметры запуска командной строки, которые вы, возможно, будете использовать чаще всего:
Таблица 3. Часто используемые параметры командной строки.
| Параметр командной строки | Описание |
|---|---|
| Быстрая загрузка | |
-no-snapshot-load | Выполняет холодную перезагрузку и сохраняет состояние эмулятора при выходе. |
-no-snapshot-save | При возможности выполняет быструю загрузку, но не сохраняет состояние эмулятора при выходе. |
-no-snapshot | Полностью отключает функцию быстрой загрузки и не загружает и не сохраняет состояние эмулятора. |
| Аппаратное обеспечение устройства | |
-camera-back mode-camera-front mode | Задает режим эмуляции для камеры, направленной назад или вперед. Это переопределяет любые настройки камеры в AVD.
Например: emulator @Pixel8_API_34 -camera-back webcam0 |
-webcam-list | Отображает список веб-камер на вашем компьютере для разработки, доступных для эмуляции. Например:emulator @Pixel8_API_34 -webcam-list
List of web cameras connected to the computer:
Camera 'webcam0' is connected to device 'webcam0'
on channel 0 using pixel format 'UYVY' В примере первая Начиная с версии SDK Tools 25.2.4, требуется указать имя AVD. |
| Образы дисков и память | |
-memory size | Указывает физический размер оперативной памяти, от 1536 до 8192 МБ. Например: emulator @Pixel8_API_34 -memory 2048 Это значение переопределяет настройку AVD. |
-sdcard filepath | Указывает имя файла и путь к образу раздела SD-карты. Например: emulator @Pixel8_API_34 -sdcard C:/sd/sdcard.img Если файл не найден, эмулятор всё равно запустится, но без SD-карты. Команда выдаст предупреждение « Нет образа SD-карты» . Если вы не укажете этот параметр, по умолчанию будет использоваться файл |
-wipe-data | Удаляет пользовательские данные и копирует данные из исходного файла данных. Эта опция очищает данные для виртуального устройства и возвращает его в то же состояние, в котором оно было определено изначально. Все установленные приложения и настройки удаляются. Например:emulator @Pixel8_API_34 -wipe-data По умолчанию файл пользовательских данных называется |
| Отлаживать | |
-debug tags | Включает или отключает отображение отладочных сообщений для одного или нескольких тегов. Разделяйте несколько тегов пробелом, запятой или столбцом. Например:$ emulator @Pixel8_API_34 -debug init,metrics Чтобы отключить тег, поставьте перед ним дефис (-). Например, следующая опция отображает все отладочные сообщения, кроме тех, которые относятся к сетевым сокетам и метрикам: Для получения списка тегов и описаний используйте параметр emulator -help-debug-tags Вы можете определить теги отладки по умолчанию в переменной среды ANDROID_VERBOSE=socket,gles Это эквивалентно использованию: или |
-debug- tag-debug-no- tag | Включает определенный тип отладочных сообщений. Используйте форму no , чтобы отключить определенный тип отладочных сообщений. Например:emulator @Pixel8_API_34 -debug-all -debug-no-metrics Для получения списка тегов используйте команду |
-logcat logtags | Включает отображение сообщений Logcat для одного или нескольких тегов и записывает их в окно терминала. Например, следующая команда включает сообщения об ошибках от всех компонентов:emulator @Pixel8_API_34 -logcat *:e
В следующем примере отображаются сообщения компонентов GSM на уровне информативного журнала: emulator @Pixel8_API_34 -logcat '*:s GSM:i' Если вы не укажете параметр Для получения дополнительной информации о Logcat и |
-show-kernel | Отображает отладочные сообщения ядра в окне терминала. Например:emulator @Pixel8_API_34 -show-kernel Одно из применений этой опции — проверка корректности процесса загрузки. |
-verbose | Выводит сообщения об инициализации эмулятора в окно терминала. Например:emulator @Pixel8_API_34 -verbose Эта опция отображает, какие файлы и настройки фактически выбраны при запуске виртуального устройства, определенного в AVD. Эта опция аналогична указанию параметра |
| Сеть | |
-dns-server servers | Использует указанные DNS-серверы. servers — это список из четырех имен DNS-серверов или IP-адресов, разделенных запятыми. Например:emulator @Pixel8_API_34 -dns-server 192.0.2.0, По умолчанию эмулятор пытается определить используемые вами DNS-серверы и создает специальные псевдонимы в эмулируемой сети брандмауэра, чтобы разрешить системе Android напрямую подключаться к этим серверам. Используйте параметр |
-http-proxy proxy | Устанавливает все TCP-соединения через указанный HTTP/HTTPS-прокси. Если вашему эмулятору необходимо получать доступ к интернету через прокси-сервер, вы можете использовать эту опцию или переменную среды http_proxy для настройки соответствующего перенаправления. Например:emulator @Pixel8_API_34 -http-proxy myserver:1981
Префикс Если этот параметр не указан, эмулятор ищет переменную среды |
-netdelay delay | Устанавливает эмуляцию задержки сети на одно из следующих значений
Например: emulator @Pixel8_API_34 -netdelay gsm Эмулятор поддерживает ограничение скорости сети, а также более высокие задержки соединения. Это можно определить либо через конфигурацию темы оформления, либо с помощью параметров |
-netfast | Отключает ограничение скорости сети. Например:emulator @Pixel8_API_34 -netfast Этот параметр аналогичен параметрам |
-netspeed speed | Задает параметры эмуляции скорости сети. Указывает максимальную скорость загрузки и выгрузки данных в сети, используя одно из следующих значений
Например: emulator @Pixel8_API_34 -netspeed edge Эмулятор поддерживает ограничение скорости сети, а также более высокие задержки соединения. Это можно определить либо через конфигурацию темы оформления, либо с помощью параметров |
-port port | Задает номер TCP-порта, используемого для консоли и adb . Например:emulator @Pixel8_API_34 -port 5556 Значение по умолчанию для первого экземпляра виртуального устройства, запущенного на вашем компьютере, равно 5554. Виртуальное устройство обычно занимает пару смежных портов: консольный порт и порт Назначение портов часто аналогично указанию Параметр Обратите внимание, что если значение |
-ports | Задает TCP-порты, используемые для консоли и adb . Например:emulator @Pixel8_API_34 -ports 5556,5559 Допустимый диапазон портов — от 5554 до 5682, что позволяет одновременно использовать 64 виртуальных устройства. Опция Мы рекомендуем по возможности использовать параметр Для получения дополнительной информации о настройке портов консоли и |
-tcpdump filepath | Захватывает сетевые пакеты и сохраняет их в файл. Например:emulator @Pixel8_API_34 -tcpdump /path/dumpfile.cap Используйте эту опцию, чтобы начать захват всех сетевых пакетов, передаваемых через виртуальную сеть Ethernet эмулятора. После этого вы можете использовать такой инструмент, как Wireshark, для анализа трафика. Обратите внимание, что этот параметр перехватывает все пакеты Ethernet и не ограничивается только TCP-соединениями. |
| Система | |
-accel mode | Настраивает ускорение виртуальной машины эмулятора. Например:emulator @Pixel8_API_34 -accel auto Ускоренная эмуляция работает только для образов систем x86 и x86_64. В Linux она использует KVM. В Windows и Mac она использует процессор Intel и драйвер Intel HAXM. Этот параметр игнорируется, если вы не эмулируете устройство x86 или x86_64. Допустимые значения для
Для получения дополнительной информации см. раздел «Настройка аппаратного ускорения для эмулятора Android» . |
-accel-check | Проверяет, установлен ли необходимый гипервизор для ускорения работы виртуальной машины эмулятора (HAXM или KVM). Например:emulator -accel-check Для получения дополнительной информации см. раздел «Проверка наличия установленного гипервизора» . |
-engine engine | Указывает используемый эмулятор:
Например: emulator @Pixel8_API_34 -engine auto Автоматическое определение должно выбирать значение, обеспечивающее наилучшую производительность при эмуляции конкретного AVD. Используйте параметр |
-gpu mode | Выбирает режим эмуляции графического процессора. Например:emulator @Pixel8_API_34 -gpu swiftshader_indirect Для получения дополнительной информации см. раздел «Настройка графического ускорения» . |
-no-accel | Отключает ускорение виртуальной машины эмулятора при использовании образа системы x86 или x86_64. Это полезно только для отладки и аналогично указанию параметра -accel off . Например:emulator @Pixel8_API_34 -no-accel Для получения дополнительной информации см. раздел «Настройка аппаратного ускорения для эмулятора Android» . |
-nojni-no-jni | Отключает расширенные проверки Java Native Interface (JNI) в среде выполнения Android Dalvik или ART. Например:emulator @Pixel8_API_34 -nojni При запуске виртуального устройства расширенные проверки JNI включены по умолчанию. Для получения дополнительной информации см. раздел «Советы по JNI» . |
-selinux {disabled|permissive} | Устанавливает модуль безопасности Security-Enhanced Linux ( SELinux ) в режим disabled или permissive в операционной системе Linux. Например:me-linux$ emulator @Pixel8_API_34 -selinux permissive По умолчанию SELinux находится в режиме |
-timezone timezone | Устанавливает часовой пояс для виртуального устройства вместо emulator @Pixel8_API_34 -timezone Europe/Paris По умолчанию эмулятор использует часовой пояс вашего компьютера для разработки. Используйте эту опцию, чтобы указать другой часовой пояс или если автоматическое определение работает некорректно. Значение
Указанный часовой пояс должен быть в базе данных zoneinfo . |
-version | Отображает номер версии эмулятора. Например:emulator @Pixel8_API_34 -version Или emulator -version |
| UI | |
-no-boot-anim | Отключает анимацию загрузки при запуске эмулятора для более быстрой загрузки. Например:emulator @Pixel8_API_34 -no-boot-anim На более медленных компьютерах эта опция может значительно ускорить процесс загрузки. |
-screen mode | Задает режим эмуляции сенсорного экрана. Например:emulator @Pixel8_API_34 -screen no-touch
|
Расширенные параметры
Параметры запуска из командной строки, представленные в следующей таблице, доступны, но редко используются обычным разработчиком приложений.
В описаниях под рабочим каталогом понимается текущий каталог в терминале, где вы вводите команды. Информацию о системном каталоге AVD и каталоге данных, а также о файлах, хранящихся в них, см. в разделе о каталогах и файлах по умолчанию .
Некоторые из этих вариантов подходят для сторонних разработчиков приложений, а некоторые используются преимущественно разработчиками платформ. Разработчики приложений создают приложения для Android и запускают их на определенных AVD. Разработчики платформ работают с системой Android и запускают ее внутри эмулятора без предварительно созданного AVD.
Таблица 4. Расширенные параметры командной строки
| Расширенные параметры | Краткое описание |
|---|---|
-bootchart timeout | Включает функцию загрузки с указанием времени ожидания в секундах. Некоторые образы системы Android имеют модифицированную систему инициализации, которая включает в себя функцию загрузки. С помощью этой опции вы можете передать системе период ожидания загрузки. Если в вашей системе инициализации функция загрузки не активирована, эта опция ничего не делает. Эта опция в первую очередь полезна разработчикам платформы, а не разработчикам сторонних приложений. Например: emulator @Pixel8_API_34 -bootchart 120 |
-cache filepath | Указывает файл образа раздела кэша. Предоставляет имя файла и абсолютный путь или путь относительно каталога данных для настройки файла постоянного кэша. Если файл не существует, эмулятор создаст его как пустой файл. Например: emulator @Pixel8_API_34 -cache ~/.android/avd/Pixel8_API_34.avd/cache_persistent.img Если вы не используете эту опцию, по умолчанию будет создан временный файл с именем |
-cache-size size | Задает размер раздела кэша в МБ. Например: emulator @Pixel8_API_34 -cache-size 1000 Если этот параметр не указан, значение по умолчанию составляет 66 МБ. Обычно большинству разработчиков приложений этот параметр не нужен, за исключением случаев, когда им необходимо загружать очень большие файлы, превышающие размер кэша по умолчанию. Для получения дополнительной информации о файле кэша см. раздел «Каталог данных AVD» . |
-data filepath | Задает образ файла раздела пользовательских данных. Укажите имя файла и абсолютный путь или путь относительно рабочего каталога для создания постоянного файла пользовательских данных. Если файл не существует, эмулятор создает образ из файла Например: emulator @Pixel8_API_34 -data ~/.android/avd/Pixel8_API_34.avd/userdata-test.img Если вы не используете эту опцию, по умолчанию будет создан файл с именем |
-datadir dir | Указывает каталог данных, используя абсолютный путь. Для получения дополнительной информации см. раздел «Каталог данных AVD» . Например: emulator @Pixel8_API_34 -datadir ~/.android/avd/Pixel8_API_34.avd/mytest |
-force-32bit | Использует 32-битный эмулятор на 64-битных платформах. Иногда эта опция полезна для тестирования или отладки. Например, возникла проблема, когда эмулятор иногда не запускался на 64-битной Windows, но работал на 32-битной. Эта опция помогла провести сравнения для отладки проблемы. Вот пример: emulator @Pixel8_API_34 -force-32bit |
-help-disk-images | Получает справку об образах дисков. Эта опция предоставляет информацию, актуальную как для разработчиков приложений, так и для разработчиков платформ. Например: emulator -help-disk-images |
-help-char-devices | Получает справку по спецификациям символьного emulator -help-char-devices |
-help-sdk-images | Получает справку по образам дисков, важным для разработчиков приложений. Эта опция получает информацию о местоположении файлов образов для AVD, созданного с помощью инструментов SDK. Например: emulator -help-sdk-images |
-help-build-images | Предоставляет справку по образам дисков, актуальным для разработчиков платформы. Например: emulator -help-build-images |
-initdata filepath-init-data filepath | Указывает начальную версию раздела данных. После удаления пользовательских данных эмулятор копирует содержимое указанного файла в пользовательские данные (по умолчанию, файл Например: emulator @Pixel8_API_34 -initdata ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/userdata-test.img Если путь не указан, файл будет помещен в системный каталог. Дополнительную информацию см. в разделе «Системный каталог AVD» . |
-kernel filepath | Использует конкретное эмулируемое ядро. Если путь не указан, эмулятор будет искать его в системном каталоге. Используйте параметр‑show‑kernel для просмотра отладочных сообщений ядра.Например: emulator @Pixel8_API_34 -kernel ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/kernel-test.img -show-kernel Если этот параметр не указан, по умолчанию используется |
-noaudio-no-audio | Отключает поддержку звука для этого виртуального устройства. На некоторых компьютерах под управлением Linux и Windows установлены неисправные аудиодрайверы, вызывающие различные симптомы, например, препятствующие запуску эмулятора. В этом случае используйте этот параметр для решения проблемы. В качестве альтернативы можно использовать переменную среды Например: emulator @Pixel8_API_34 -noaudio |
-nocache-no-cache | Запускает эмулятор без раздела кэша. Если вы не используете этот параметр, по умолчанию используется временный файл с именем Например: emulator @Pixel8_API_34 -nocache |
-no-snapshot | Запрещает как автоматическую загрузку, так и сохранение, в результате чего эмулятор выполнит полную последовательность загрузки и потеряет свое состояние при закрытии. Он переопределяет параметр Например: emulator @Pixel8_API_34 -no-snapshot |
-no-snapshot-load | Предотвращает загрузку эмулятором состояния AVD из хранилища снимков. Выполняет полную загрузку. Например: emulator @Pixel8_API_34 -no-snapshot-load |
-no-snapshot-save | Предотвращает сохранение эмулятором состояния AVD в хранилище снимков при выходе, что означает потерю всех изменений. Например: emulator @Pixel8_API_34 -no-snapshot-save |
-no-snapshot-update-time | Не пытается немедленно скорректировать время на часах AVD при восстановлении снимка. Эта опция может быть полезна во время тестирования, поскольку позволяет избежать резкого скачка времени. Обновления времени по-прежнему отправляются на AVD примерно каждые 15 секунд. Например: emulator @Pixel8_API_34 -no-snapshot-update-time |
-no-snapstorage | Запускает эмулятор без монтирования файла для хранения или загрузки снимков состояния, принудительно выполняя полную загрузку и отключая функциональность создания снимков состояния. Этот параметр переопределяет параметры Например: emulator @Pixel8_API_34 -no-snapstorage |
-no-window | Отключает отображение графического окна в эмуляторе. Эта опция полезна при запуске эмулятора на серверах, не имеющих дисплея. Доступ к эмулятору можно получить через emulator @Pixel8_API_34 -no-window |
-partition-size size | Указывает размер системного раздела данных в МБ. Например: emulator @Pixel8_API_34 -partition-size 1024 |
-prop name = value | Устанавливает системное свойство Android в эмуляторе при его загрузке. emulator @Pixel8_API_34 -prop qemu.name=value -prop qemu.abc=xyz |
-qemu args | Передает аргументы программному обеспечению эмулятора QEMU. При использовании этой опции убедитесь, что она указана последней, поскольку все последующие опции интерпретируются как специфические для QEMU. Эта опция довольно сложная и должна использоваться только разработчиками, хорошо знакомыми с QEMU и эмуляцией Android. |
-qemu -h | Отображает справку emulator -qemu -h |
-ramdisk filepath | Указывает образ загрузочного диска в оперативной памяти. Указывает имя файла и абсолютный путь или путь относительно рабочего каталога. Например: emulator @Pixel8_API_34 -ramdisk ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/ramdisk-test.img Если вы не используете этот параметр, по умолчанию будет использоваться файл |
-report-console socket | Перед началом эмуляции сообщает удаленной третьей стороне порт консоли. Это может быть полезно для скрипта автоматизированного тестирования.
Для получения дополнительной информации используйте параметр |
-shell | Создает консоль с правами root на текущем терминале. Этот параметр отличается от команды
Например: emulator @Pixel8_API_34 -shell |
-snapshot name | Указывает имя снимка в файле хранилища снимков для автоматического запуска и сохранения. Вместо выполнения полной последовательности загрузки эмулятор может возобновить выполнение с более раннего снимка состояния, что обычно значительно быстрее. Если вы укажете этот параметр, эмулятор загрузит снимок с указанным именем из образа снимка и сохранит его обратно под тем же именем при завершении работы. Если вы не используете эту опцию, по умолчанию выполняется полная загрузка системы. Если указанный снимок не существует, эмулятор вместо этого выполняет полную загрузку системы и операцию сохранения. Информацию о том, как указать файл хранилища моментальных снимков и файл по умолчанию, см. в описании параметра emulator @Pixel8_API_34 -snapshot snapshot2 Помните, что в процессе загрузки снимка все содержимое системы, пользовательские данные и образы SD-карт перезаписываются содержимым, которое они содержали на момент создания снимка. Если вы не сохраните эту информацию в другом снимке, все изменения, внесенные с тех пор, будут потеряны. Вы также можете создать снимок из консоли эмулятора, используя команду ` |
-snapshot-list | Отображает список доступных снимков. Эта команда выводит таблицу снимков, хранящихся в файле хранилища снимков, с которым был запущен эмулятор, а затем завершает работу. Если вы также укажете Например: emulator @Pixel8_API_34 -snapshot-list -snapstorage ~/.android/avd/Pixel8_API_34.avd/snapshots-test.img Значения столбцов ID и TAG из выходных данных можно использовать в качестве аргументов для параметра |
-snapstorage filepath | Указывает файл репозитория, содержащий все снимки состояния. Все снимки, сделанные во время выполнения, сохраняются в этом файле. Восстановить во время работы эмулятора можно только снимки из этого файла. Например: emulator @Pixel8_API_34 -snapstorage ~/.android/avd/Pixel8_API_34.avd/snapshots-test.img Если этот параметр не указан, по умолчанию используется файл |
-sysdir dir | Указывает системный каталог, используя абсолютный путь. Для получения дополнительной информации см. раздел «Системный каталог AVD» . Например: emulator @Pixel8_API_34 -sysdir ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/test |
-system filepath | Указывает начальный системный файл. Предоставляет имя файла и абсолютный путь или путь относительно рабочего каталога. Например: emulator @Pixel8_API_34 -system ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/system-test.img Если вы не используете этот параметр, по умолчанию будет использоваться файл |
-writable-system | Используйте эту опцию, чтобы во время сеанса эмуляции у вас был доступный для записи образ системы. Для этого:
Using this flag creates a temporary copy of the system image that can be very large, up to several hundred MBs, but will be destroyed when the emulator exits. |
Устаревшие опции
The following command-line options are deprecated:
-
-audio-in -
-audio-out -
-charmap -
-code-profile -
-cpu-delay -
-dpi-device -
-dynamic_skin -
-enable-kvm -
-gps -
-image -
-keyset -
-help-keys -
-help-keyset-file -
-nand-limits -
-noskin -
-no-skin -
-onion -
-onion-alpha -
-onion-rotation -
-radio -
-ranchu -
-raw-keys -
-scale -
-shared-net-id -
-shell-serial -
-skin -
-skindir -
-trace -
-useaudio
Get help about command-line options
This section describes how to get help about the command-line options. It provides more in-depth information about the commonly used emulator command-line options that are available when you start the emulator.
List all emulator options
To print a list of all emulator options, including a short description, enter the following command:
emulator -help
Get detailed help for a specific option
To print help for a specific startup option, enter the following command:
emulator -help-option
Например:
emulator -help-netspeed
This help is more detailed than the description provided by the -help option.
Get detailed help for all options
To get detailed help for all emulator options, enter the following command:
emulator -help-all
List emulator environment variables
To get a list of emulator environment variables, enter the following command:
emulator -help-environment
You can set environment variables in the terminal window before launching a virtual device, or you can set it through your user settings in the operating system. For example, set it in your .bashrc file on Linux.
List debug tags
To print a list of tags for the -debug options, enter the following command:
emulator -help-debug-tags
The -debug options let you enable or disable debug messages from specific emulator components, as specified by the tags.
The Android SDK includes an Android device emulator—a virtual device that runs on your computer. The Android Emulator lets you develop and test Android apps without using a physical device.
This page describes command-line features that you can use with the Android Emulator. For information about using the Android Emulator UI, see Run apps on the Android Emulator .
Start the emulator
Use the emulator command to start the emulator, as an alternative to running your project or starting it through the AVD Manager .
Here's the basic command-line syntax for starting a virtual device from a terminal prompt:
emulator -avd avd_name [ {-option [value]} … ]
Или
emulator @avd_name [ {-option [value]} … ]
For example, if you launch the emulator from within Android Studio running on a Mac, the default command line will be similar to the following:
/Users/janedoe/Library/Android/sdk/emulator/emulator -avd Pixel8_API_34 -netdelay none -netspeed full -qt-hide-window -grpc-use-token -idle-grpc-timeout
Please note that the arguments -qt-hide-window -grpc-use-token -idle-grpc-timeout are only used to run the emulator window within Android Studio. If you want to run the emulator on its own window, you should not use those extra parameters.
You can specify startup options when you start the emulator, but not after it has started.
For a list of AVD names, enter the following command:
emulator -list-avds
Use this option to display a list of AVD names from your Android home directory. You can override the default home directory by setting the ANDROID_SDK_HOME environment variable that specifies the root of the user-specific directory where all configuration and AVD content is stored.
You can set the environment variable in the terminal window before launching a virtual device or through your user settings in the operating system. For example, in your .bashrc file on Linux.
To stop the Android Emulator, close the emulator window.
Установите приложение
In addition to installing an app through Android Studio or the emulator UI , you can install your app on a virtual device by using the adb utility.
To use adb to install, run, and test your app, follow these general steps:
- Build and package your app into an APK, as described in Build and run your app .
- Start the emulator from the command line, as described in the previous section, using any startup options necessary.
- Install your app using
adb. - Run and test your app on the emulator.
While the emulator is running, you can use the Emulator console to issue commands as needed.
To uninstall an app, do so as you would on an Android device.
The virtual device preserves the app and its state data across restarts in a user data disk partition ( userdata-qemu.img ). To clear this data, start the emulator with the -wipe-data option or wipe the data in the AVD Manager. For more information about the user data partition and other storage, see the following section.
Note: The adb utility views the virtual device as an actual physical device. For this reason, you might have to use the -d flag with some common adb commands, such as install . The -d flag lets you specify which of several connected devices to use as the target of a command. If you don't specify -d , the emulator targets the first device in its list.
Understand the default directories and files
The emulator uses associated files, of which the AVD system and data directories are the most important. It's helpful to understand the emulator directory structure and files when specifying command-line options, although you typically don't need to modify the default directories or files.
The Android Emulator uses the ( QEMU ) hypervisor.
AVD system directory
The system directory contains the Android system images that the emulator uses to simulate the operating system. This directory has platform-specific, read-only files shared by all AVDs of the same type, including API level, CPU architecture, and Android variant. The default locations are the following:
- macOS and Linux -
~/Library/Android/sdk/system-images/android- apiLevel / variant / arch / - Windows -
C:\Users\ user \Library\Android\sdk\system-images\android- apiLevel \ variant \ arch \
Где:
-
apiLevelis a numeric API level or a letter for preview releases. For example,android-Vindicates the Android VanillaIceCream preview. On release, it became API level 35, designated byandroid-35. -
variantis a name corresponding to specific features implemented by the system image. For example,google_apisorandroid-wear. -
archis the target CPU architecture. For example,x86.
Use the -sysdir option to specify a different system directory for the AVD.
The emulator reads the following files from the system directory:
Table 1. System directory files read by the Android Emulator
| Файл | Описание | Option to specify a different file |
|---|---|---|
kernel-qemu or kernel-ranchu | The binary kernel image for the AVD. kernel-ranchu is based on the QEMU emulator. | -kernel |
ramdisk.img | The boot partition image. This is a subset of system.img loaded by the kernel initially before the system image is mounted. It typically contains just a few binaries and initialization scripts. | -ramdisk |
system.img | The read-only, initial version of the system image. Specifically, the partition containing the system libraries and data corresponding to the API level and variant. | -system |
userdata.img | The initial version of the data partition, which appears as data/ in the emulated system and contains all writable data for the AVD. The emulator uses this file when you create a new AVD or use the ‑wipe-data option. For more information, see the userdata-qemu.img file description in the following section. | -initdata-init-data |
AVD data directory
The AVD data directory, also called the content directory, is specific to a single AVD instance and contains all modifiable data for the AVD.
The default location is the following, where name is the AVD name:
- macOS and Linux -
~/.android/avd/ name .avd/ - Windows 10, and higher -
C:\Users\ user \.android\ name .avd\
Use the -datadir option to specify a different AVD data directory.
The following table lists the most important files contained in this directory:
Table 2. Important files in the AVD data directory
| Файл | Описание | Option to specify a different file |
|---|---|---|
userdata-qemu.img | The content of the data partition, which appears as Each virtual device instance uses a writable user-data image to store user and session-specific data. For example, it uses the image to store a unique user's installed app data, settings, databases, and files. Each user has a different | -data |
cache.img | The cache partition image, which appears as cache/ in the emulated system. It's empty when you first create an AVD or use the -wipe-data option. It stores temporary download files and is populated by the download manager and sometimes the system. For example, the browser uses it to cache downloaded web pages and images while the emulator is running. When you power off the virtual device, the file is deleted. You can persist the file by using the -cache option. | -cache |
sdcard.img | (Optional) An SD card partition image that lets you simulate an SD card on a virtual device. You can create an SD card image file in the AVD Manager or using the When defining an AVD in the AVD Manager, you can choose to use an automatically managed SD card file or a file that you created with the You can browse, send files to, and copy and remove files from a simulated SD card by using the emulator UI or the To copy files to the SD card file before loading it, mount the image file as a loop device and then copy the files. Or, use a utility, such as the The emulator treats the file as a pool of bytes, so the SD card format doesn't matter. The | -sdcard |
List directories and files used by the emulator
You can discover where files are located in two ways:
- Use the
-verboseor-debug initoption when you start the emulator from the command line. Look at the output. - Use the
emulator-help- optioncommand to list a default directory. For example:emulator -help-datadir
Use '-datadir <dir>' to specify a directory where writable image files will be searched. On this system, the default directory is: /Users/me/.android See '-help-disk-images' for more information about disk image files.
Command-line startup options
This section lists options you can supply on the command line when you start the emulator.
Note: The Android Emulator is continually under development to make it more reliable. For status on the issues reported against various command-line options and to report bugs, see the Android Issue Tracker .
Commonly used options
The following table lists command-line startup options that you might use more often:
Table 3. Commonly used command-line options
| Command-line option | Описание |
|---|---|
| Quick Boot | |
-no-snapshot-load | Performs a cold boot and saves the emulator state on exit. |
-no-snapshot-save | Performs a quick boot if possible, but does not save the emulator state on exit. |
-no-snapshot | Disables the Quick Boot feature completely and doesn't load or save the emulator state. |
| Device Hardware | |
-camera-back mode-camera-front mode | Sets the emulation mode for a camera facing back or front. This overrides any camera setting in the AVD.
Например: emulator @Pixel8_API_34 -camera-back webcam0 |
-webcam-list | Lists the webcams on your development computer that are available for emulation. For example:emulator @Pixel8_API_34 -webcam-list
List of web cameras connected to the computer:
Camera 'webcam0' is connected to device 'webcam0'
on channel 0 using pixel format 'UYVY' In the example, the first As of SDK Tools 25.2.4, the AVD name is required. |
| Disk images and memory | |
-memory size | Specifies the physical RAM size, from 1536 to 8192 MBs. For example: emulator @Pixel8_API_34 -memory 2048 This value overrides the AVD setting. |
-sdcard filepath | Specifies the filename and path to an SD card partition image file. For example: emulator @Pixel8_API_34 -sdcard C:/sd/sdcard.img If the file isn't found, the emulator still launches, but without an SD card. The command returns a No SD Card Image warning. If you don't specify this option, the default is |
-wipe-data | Deletes user data and copies data from the initial data file. This option clears the data for the virtual device and returns it to the same state as when it was first defined. All installed apps and settings are removed. For example:emulator @Pixel8_API_34 -wipe-data By default, the user data file is |
| Отлаживать | |
-debug tags | Enables or disables the display of debug messages for one or more tags. Separate multiple tags by a space, comma, or column. For example:$ emulator @Pixel8_API_34 -debug init,metrics To disable a tag, place a dash (-) in front of it. For example, the following option displays all debug messages, except the ones related to network sockets and metrics: For a list of tags and descriptions, use the emulator -help-debug-tags You can define the default debug tags in the ANDROID_VERBOSE=socket,gles It's equivalent to using: или |
-debug- tag-debug-no- tag | Enables a specific debug message type. Use the no form to disable a debug message type. For example:emulator @Pixel8_API_34 -debug-all -debug-no-metrics For a list of tags, use the |
-logcat logtags | Enables the display of Logcat messages for one or more tags and writes them to the terminal window. For example, the following command enables error messages from all components:emulator @Pixel8_API_34 -logcat *:e
The following example displays GSM component messages at the informative log level: emulator @Pixel8_API_34 -logcat '*:s GSM:i' If you don't supply the For more information about Logcat and |
-show-kernel | Displays kernel debug messages in the terminal window. For example:emulator @Pixel8_API_34 -show-kernel One use of this option is to check that the boot process works correctly. |
-verbose | Prints emulator initialization messages to the terminal window. For example:emulator @Pixel8_API_34 -verbose It displays which files and settings are actually selected when starting a virtual device defined in an AVD. This option is the same as specifying |
| Сеть | |
-dns-server servers | Uses the specified DNS servers. servers is a comma-separated list of up to four DNS server names or IP addresses. For example:emulator @Pixel8_API_34 -dns-server 192.0.2.0, By default, the emulator tries to detect the DNS servers you're using and sets up special aliases in the emulated firewall network to allow the Android system to connect directly to the servers. Use the |
-http-proxy proxy | Makes all TCP connections through a specified HTTP/HTTPS proxy. If your emulator must access the internet through a proxy server, you can use this option or the http_proxy environment variable to set up the appropriate redirection. For example:emulator @Pixel8_API_34 -http-proxy myserver:1981
The If this option isn't supplied, the emulator looks up the |
-netdelay delay | Sets network latency emulation to one of the following
Например: emulator @Pixel8_API_34 -netdelay gsm The emulator supports network throttling as well as higher connection latencies. You can define it either through the skin configuration or with the |
-netfast | Disables network throttling. For example:emulator @Pixel8_API_34 -netfast This option is the same as specifying |
-netspeed speed | Sets the network speed emulation. Specifies the maximum network upload and download speeds with one of the following
Например: emulator @Pixel8_API_34 -netspeed edge The emulator supports network throttling as well as higher connection latencies. You can define it either through the skin configuration or with the |
-port port | Sets the TCP port number that's used for the console and adb . For example:emulator @Pixel8_API_34 -port 5556 The default value is 5554 for the first virtual device instance running on the your machine. A virtual device normally occupies a pair of adjacent ports: a console port and an The port assignments are often the same as specifying The Note that if the |
-ports | Sets the TCP ports used for the console and adb . For example:emulator @Pixel8_API_34 -ports 5556,5559 The valid ports range is 5554 to 5682, allowing for 64 concurrent virtual devices. The We recommend using the For more information about setting console and |
-tcpdump filepath | Captures network packets and stores them in a file. For example:emulator @Pixel8_API_34 -tcpdump /path/dumpfile.cap Use this option to begin capturing all network packets that are sent through the virtual Ethernet LAN of the emulator. Afterward, you can use a tool like Wireshark to analyze the traffic. Note that this option captures all ethernet packets and isn't limited to TCP connections. |
| Система | |
-accel mode | Configures emulator VM acceleration. For example:emulator @Pixel8_API_34 -accel auto Accelerated emulation works for x86 and x86_64 system images only. On Linux, it relies on KVM. On Windows and Mac, it relies on an Intel CPU and Intel HAXM driver. This option is ignored if you're not emulating an x86 or x86_64 device. Valid values for
For more information, see Configure hardware acceleration for the Android Emulator . |
-accel-check | Checks whether a required hypervisor for emulator VM acceleration is installed (HAXM or KVM). For example:emulator -accel-check For more information, see Check if a hypervisor is installed . |
-engine engine | Specifies the emulator engine:
Например: emulator @Pixel8_API_34 -engine auto Auto-detection should choose the value that provides the best performance when emulating a particular AVD. Use the |
-gpu mode | Selects the GPU emulation mode. For example:emulator @Pixel8_API_34 -gpu swiftshader_indirect For more information, see Configure graphics acceleration . |
-no-accel | Disables emulator VM acceleration when using an x86 or x86_64 system image. It's useful for debugging only and is the same as specifying -accel off . For example:emulator @Pixel8_API_34 -no-accel For more information, see Configure hardware acceleration for the Android Emulator . |
-nojni-no-jni | Disables extended Java Native Interface (JNI) checks in the Android Dalvik or ART runtime. For example:emulator @Pixel8_API_34 -nojni When you start a virtual device, extended JNI checks are enabled by default. For more information, see JNI tips . |
-selinux {disabled|permissive} | Sets the Security-Enhanced Linux ( SELinux ) security module to either disabled or permissive mode on a Linux operating system. For example:me-linux$ emulator @Pixel8_API_34 -selinux permissive By default, SELinux is in |
-timezone timezone | Sets the time zone for the virtual device to emulator @Pixel8_API_34 -timezone Europe/Paris By default, the emulator uses the time zone of your development computer. Use this option to specify a different time zone or if the automatic detection isn't working correctly. The
The specified time zone must be in the zoneinfo database . |
-version | Displays the emulator version number. For example:emulator @Pixel8_API_34 -version Или emulator -version |
| UI | |
-no-boot-anim | Disables the boot animation during emulator startup for faster booting. For example:emulator @Pixel8_API_34 -no-boot-anim On slower computers, this option can significantly speed up the boot sequence. |
-screen mode | Sets emulated touch screen mode. For example:emulator @Pixel8_API_34 -screen no-touch
|
Расширенные параметры
The command-line startup options in the following table are available but not commonly used by the average app developer.
In the descriptions, the working directory is the current directory in the terminal where you're entering commands. For information about the AVD system directory and data directory and the files stored within them, see the section about default directories and files .
Some of these options are appropriate for external app developers, and some of them are used primarily by platform developers. App developers create Android apps and run them on specific AVDs. Platform developers work on the Android system and run it inside the emulator with no pre-created AVD.
Table 4. Advanced command-line options
| Advanced option | Краткое описание |
|---|---|
-bootchart timeout | Enables bootcharting with a timeout in seconds. Some Android system images have a modified init system that integrates a bootcharting facility. You can pass a bootcharting timeout period to the system with this option. If your init system doesn't have bootcharting activated, the option does nothing. This option is primarily useful to platform developers, not external app developers. Например: emulator @Pixel8_API_34 -bootchart 120 |
-cache filepath | Specifies a cache partition image file. Provides a filename and an absolute path or a path relative to the data directory to set up a persistent cache file. If the file doesn't exist, the emulator creates it as an empty file. Например: emulator @Pixel8_API_34 -cache ~/.android/avd/Pixel8_API_34.avd/cache_persistent.img If you don't use this option, the default is a temporary file named |
-cache-size size | Sets the cache partition size in MBs. Например: emulator @Pixel8_API_34 -cache-size 1000 If you don't specify this option, the default is 66 MB. Normally, most app developers don't need this option, unless they need to download very large files that are larger than the default cache. For more information about the cache file, see AVD data directory . |
-data filepath | Sets the user data partition image file. Provides a filename and an absolute path or a path relative to the working directory to set up a persistent user data file. If the file doesn't exist, the emulator creates an image from the default Например: emulator @Pixel8_API_34 -data ~/.android/avd/Pixel8_API_34.avd/userdata-test.img If you don't use this option, the default is a file named |
-datadir dir | Specifies a data directory using an absolute path. For more information, see AVD data directory . Например: emulator @Pixel8_API_34 -datadir ~/.android/avd/Pixel8_API_34.avd/mytest |
-force-32bit | Uses the 32-bit emulator on 64-bit platforms. Occasionally, this option is useful for testing or debugging. For example, there was an issue where the emulator would sometimes not run on 64-bit Windows, but 32-bit did run. This option was helpful for performing comparisons to debug the issue. Here's an example: emulator @Pixel8_API_34 -force-32bit |
-help-disk-images | Gets help about about disk images. This option provides information relevant to both app and platform developers. For example: emulator -help-disk-images |
-help-char-devices | Gets help about character emulator -help-char-devices |
-help-sdk-images | Gets help about disk images relevant to app developers. This option gets information about where the image files are located for an AVD created with the SDK tools. For example: emulator -help-sdk-images |
-help-build-images | Gets help about disk images relevant to platform developers. For example: emulator -help-build-images |
-initdata filepath-init-data filepath | Specifies the initial version of the data partition. After wiping user data, the emulator copies the contents of the specified file to user data (by default, the Например: emulator @Pixel8_API_34 -initdata ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/userdata-test.img If you don't specify a path, it places the file in the system directory. For more information, see AVD system directory . |
-kernel filepath | Uses a specific emulated kernel. If you don't specify a path, the emulator looks in the system directory. Use the‑show‑kernel option to view kernel debug messages.Например: emulator @Pixel8_API_34 -kernel ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/kernel-test.img -show-kernel If you don't specify this option, the default is |
-noaudio-no-audio | Disables audio support for this virtual device. Some Linux and Windows computers have faulty audio drivers that cause different symptoms, such as preventing the emulator from starting. In this case, use this option to overcome the issue. Alternatively, you can use the Например: emulator @Pixel8_API_34 -noaudio |
-nocache-no-cache | Starts the emulator without a cache partition. If you don't use this option, the default is a temporary file named Например: emulator @Pixel8_API_34 -nocache |
-no-snapshot | Inhibits both the automatic load and save operations, causing the emulator to execute a full boot sequence and to lose its state when closed. It overrides the Например: emulator @Pixel8_API_34 -no-snapshot |
-no-snapshot-load | Prevents the emulator from loading the AVD state from snapshot storage. Performs a full boot. Например: emulator @Pixel8_API_34 -no-snapshot-load |
-no-snapshot-save | Prevents the emulator from saving the AVD state to snapshot storage on exit, meaning that all changes will be lost. Например: emulator @Pixel8_API_34 -no-snapshot-save |
-no-snapshot-update-time | Doesn't try to correct the AVD clock time immediately on snapshot restore. This option can be useful during testing as it avoids a sudden time jump. Time updates are still sent to the AVD about every 15 seconds. Например: emulator @Pixel8_API_34 -no-snapshot-update-time |
-no-snapstorage | Starts the emulator without mounting a file to store or load state snapshots, forcing a full boot and disabling state snapshot functionality. This option overrides the Например: emulator @Pixel8_API_34 -no-snapstorage |
-no-window | Disables graphical window display on the emulator. This option is useful when running the emulator on servers that have no display. You can access the emulator through emulator @Pixel8_API_34 -no-window |
-partition-size size | Specifies the system data partition size in MBs. For example: emulator @Pixel8_API_34 -partition-size 1024 |
-prop name = value | Sets an Android system property in the emulator when it boots. emulator @Pixel8_API_34 -prop qemu.name=value -prop qemu.abc=xyz |
-qemu args | Passes arguments to the QEMU emulator software. When using this option, make sure it's the last option specified, as all options after it are interpreted as QEMU-specific options. This option is quite advanced and should be used only by developers who are very familiar with QEMU and Android emulation. |
-qemu -h | Displays emulator -qemu -h |
-ramdisk filepath | Specifies a ramdisk boot image. Specifies the filename and an absolute path or a path relative to the working directory. Например: emulator @Pixel8_API_34 -ramdisk ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/ramdisk-test.img If you don't use this option, the default is the |
-report-console socket | Reports the console port to a remote third party before starting emulation. It can be useful for an automated testing script.
For more information, use the |
-shell | Creates a root shell console on the current terminal. This option differs from the
Например: emulator @Pixel8_API_34 -shell |
-snapshot name | Specifies the name of a snapshot within a snapshot storage file for automatic start and save operations. Rather than executing a full boot sequence, the emulator can resume execution from an earlier state snapshot, which is usually significantly faster. When you supply this option, the emulator loads the snapshot of that name from the snapshot image and saves it back under the same name on exit. If you don't use this option, the default is a full boot sequence. If the specified snapshot doesn't exist, the emulator performs a full boot sequence instead and performs a save operation. See the emulator @Pixel8_API_34 -snapshot snapshot2 Remember that in the process of loading a snapshot, all contents of the system, user data, and SD card images are overwritten with the contents they held when the snapshot was made. Unless you save this information in a different snapshot, any changes since then are lost. You can also create a snapshot from the emulator console by using the |
-snapshot-list | Displays a list of available snapshots. This command prints a table of snapshots that are stored in the snapshot storage file that the emulator was started with, then exits. If you specify Например: emulator @Pixel8_API_34 -snapshot-list -snapstorage ~/.android/avd/Pixel8_API_34.avd/snapshots-test.img You can use the ID and TAG column values in the output as arguments for the |
-snapstorage filepath | Specifies a repository file that contains all state snapshots. All snapshots made during execution are saved in this file. Only snapshots in this file can be restored during the emulator run. Например: emulator @Pixel8_API_34 -snapstorage ~/.android/avd/Pixel8_API_34.avd/snapshots-test.img If you don't specify this option, the default is |
-sysdir dir | Specifies a system directory using an absolute path. For more information, see AVD system directory . For example: emulator @Pixel8_API_34 -sysdir ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/test |
-system filepath | Specifies an initial system file. Provides the filename and an absolute path or a path relative to the working directory. Например: emulator @Pixel8_API_34 -system ~/Library/Android/sdk/system-images/android-34/ google_apis/x86_64/system-test.img If you don't use this option, the default is the |
-writable-system | Use this option to have a writable system image during your emulation session. To do so:
Using this flag creates a temporary copy of the system image that can be very large, up to several hundred MBs, but will be destroyed when the emulator exits. |
Устаревшие опции
The following command-line options are deprecated:
-
-audio-in -
-audio-out -
-charmap -
-code-profile -
-cpu-delay -
-dpi-device -
-dynamic_skin -
-enable-kvm -
-gps -
-image -
-keyset -
-help-keys -
-help-keyset-file -
-nand-limits -
-noskin -
-no-skin -
-onion -
-onion-alpha -
-onion-rotation -
-radio -
-ranchu -
-raw-keys -
-scale -
-shared-net-id -
-shell-serial -
-skin -
-skindir -
-trace -
-useaudio
Get help about command-line options
This section describes how to get help about the command-line options. It provides more in-depth information about the commonly used emulator command-line options that are available when you start the emulator.
List all emulator options
To print a list of all emulator options, including a short description, enter the following command:
emulator -help
Get detailed help for a specific option
To print help for a specific startup option, enter the following command:
emulator -help-option
Например:
emulator -help-netspeed
This help is more detailed than the description provided by the -help option.
Get detailed help for all options
To get detailed help for all emulator options, enter the following command:
emulator -help-all
List emulator environment variables
To get a list of emulator environment variables, enter the following command:
emulator -help-environment
You can set environment variables in the terminal window before launching a virtual device, or you can set it through your user settings in the operating system. For example, set it in your .bashrc file on Linux.
List debug tags
To print a list of tags for the -debug options, enter the following command:
emulator -help-debug-tags
The -debug options let you enable or disable debug messages from specific emulator components, as specified by the tags.