Введение
Часто бывает необходимость проверить работу свеженаписанного приложения на устройстве. Но вполне может оказаться, что устройства под рукой нет. Или нет устройства с определенными параметрами (правда, это больше относится к размеру/разрешению экрана). Что же делать в этом случае? К счастью, альтернативы есть. Android-сообщество и разные компании предлагают на выбор несколько вариантов замены android-устройств для разных целей. Я кратко расскажу о следующих:
- Эмулятор в составе SDK
- Genymotion
- Android x86
- Bluestacks
Если интересно — добро пожаловать под кат (осторожно, достаточно много картинок)
Эмулятор в составе SDK
Сайт: http://developer.android.com/sdk/index.html Самый очевидный способ подмены устройства. Если занимаешься разработкой под Android — эмулятор точно есть.
Использование
Для использвания достаточно открыть AVD Manager из эклипса или в консоли
/path/to/sdk/tools/android avd
создать свой AVD (Android Virtual Device) и запустить. Более подробно процесс описывать не буду, все достаточно просто. Однако не обошлось без особенностей. ARM-эмуляторы до ужаса медленные. Что-то нормально проверить практически невозможно, особенно на не очень сильном железе (потому что эмуляция процессора с другой архитектурой). Тут на помощь может прийти технология Intel HAXM, однако это чревато тем, что платформо-зависимый код (который должен работать под ARM) может не работать, поскольку используется x86. Скриншоты AVD manager Параметры запуска Сам эмулятор
Плюсы
- Кроссплатформенное решение
- Входит в состав SDK, не нужны сторонние тулы
- Конфигурируемый (размер памяти, подключение камеры и т.д)
- Доступ по telnet для настройки параметров сети, батареи и т.д.
- Плагин для Eclipse, легкий доступ через adb
- Обновляется сразу после выхода новой версии Android
Минусы
- Медленный, если не использовать HAXM
- Не ARM, если использовать HAXM
- Нет эмуляции Bluetooth, OTG, наушников и некоторых других железных параметров
Genymotion
Сайт:http://www.genymotion.com/ Проприетарная реализация, выросшая из проекта AndroVM. По сути, виртуальная машина на VirtualBox с дополнительными фишками вроде своих контролов, расширенной настройки и т.д. Достаточно удобен, быстр, много возможность, коммандлайн тулы, Java API для тестов. При создании устройства из сети выкачивается его образ. APK можно устанавливать, перетянув их на окно с виртуалкой. Скриншоты Окно работающего девайса Создание виртуального девайса Главное окно приложения
Плюсы
- Кроссплатформенное решение
- Быстрый
- Много дополнительных тулов (контроль заряда, акселерометра, API для тестов и т.д.)
- Плагин для Eclipse, легкий доступ через adb
Минусы
- Платный для компаний, и это главный минус
- Не ARM
- Достаточно долгий выход актуальных версий Android
Android x86
Сайт:http://www.android-x86.org/ Проект по портированию Android на платформу x86. Распространяется в виде образа iso, можно запустить/установить в виртуальной машине, при большом желании можно даже поставить на живую машину с x86 процессором (на ноутбук, например). Работает быстро, но есть куча проблем из-за того, что это виртуальная машина. Например, привязывние мыши внутри окна виртуалки, доступ к adb только по сети и т.д. Для использования в VirtualBox нужно отключать Mouse Integration, иначе в виртуальной машине не видно курсора. Для подключения adb нужно выполнить
adb connect ip.add.res.s
IP-адрес можно узнать, нажав в машине Alt+F1 и введя netcfg. Вернуться в графический режим — Alt+F7. Скриншоты Главное окно: Консоль с IP-адресом:
Плюсы
- Кроссплатформенное решение (везде, где есть VirtualBox)
- Быстрый
Минусы
- Неудобный доступ к adb
- Минусы, связанные с использованием VM — привязка мыши, например
- Не ARM
- Очень долгий выход актуальных версий
Bluestacks
Сайт:www.bluestacks.com Позиционируется как плеер приложений для Windows, Mac и TV. Умеет запускать приложения, имеет доступ к маркету. Неудобен для разработки и тестирования — apk ставятся тулом из комплекта, но доступ к adb можно получить. Однако для запуска приложений может быть полезен. Для подключения через adb:
adb connect 127.0.0.1
Скриншоты Запуск: Главное окно:
Плюсы
- Кроссплатформенное решение (правда, только Mac и Windows)
- Быстрый
Минусы
- Неудобно ставить приложения
- Непонятно, что с версиями android (2.3 под OS X, под Windows ставился 4.0)
- Нет под linux
Вывод
Получается, что для некоторых ситуаций можно обойтись и без девайса. Однако не стоит забывать, что во многих случаях железо эмуляторов отличается от реального, да и прошивки реальных устройств тоже могут подбросить сюрпризов. Поэтому эмуляторы — всего лишь для начальной проверки. 383 233.2k 383
An Android Virtual Device (AVD) is a configuration that defines the characteristics of an Android phone, tablet, Wear OS, Android TV, or Automotive OS device that you want to simulate in the Android Emulator. The AVD Manager is an interface you can launch from Android Studio that helps you create and manage AVDs.
To open the AVD Manager, do one of the following:
- Select Tools > AVD Manager.
- Click AVD Manager in the toolbar.
- About AVDs An AVD contains a hardware profile, system image, storage area, skin, and other properties. We recommend that you create an AVD for each system image that your app could potentially support based on the setting in your manifest. Hardware profile The hardware profile defines the characteristics of a device as shipped from the factory. The AVD Manager comes preloaded with certain hardware profiles, such as Pixel devices, and you can define or customize the hardware profiles as needed. Notice that only some hardware profiles are indicated to include Play Store. This indicates that these profiles are fully CTS compliant and may use system images that include the Play Store app. System images A system image labeled with Google APIs includes access to Google Play services. A system image labeled with the Google Play logo in the Play Store column includes the Google Play Store app and access to Google Play services, including a Google Play tab in the Extended controls dialog that provides a convenient button for updating Google Play services on the device. To ensure app security and a consistent experience with physical devices, system images with the Google Play Store included are signed with a release key, which means that you cannot get elevated privileges (root) with these images. If you require elevated privileges (root) to aid with your app troubleshooting, you can use the Android Open Source Project (AOSP) system images that do not include Google apps or services. Storage area The AVD has a dedicated storage area on your development machine. It stores the device user data, such as installed apps and settings, as well as an emulated SD card. If needed, you can use the AVD Manager to wipe user data, so the device has the same data as if it were new. Skin An emulator skin specifies the appearance of a device. The AVD Manager provides some predefined skins. You can also define your own, or use skins provided by third parties. AVD and app features Be sure your AVD definition includes the device features your app depends on. See Hardware Profile Properties and AVD Properties for lists of features you can define in your AVDs. Create an AVD Tip: If you want to launch your app into an emulator, instead run your app from Android Studio and then in the Select Deployment Target dialog that appears, click Create New Virtual Device. To create a new AVD: Open the AVD Manager by clicking Tools > AVD Manager. Click Create Virtual Device, at the bottom of the AVD Manager dialog. The Select Hardware page appears. Notice that only some hardware profiles are indicated to include Play Store. This indicates that these profiles are fully CTS compliant and may use system images that include the Play Store app. Select a hardware profile, and then click Next. If you don’t see the hardware profile you want, you can create or import a hardware profile. The System Image page appears. Select the system image for a particular API level, and then click Next. The Recommended tab lists recommended system images. The other tabs include a more complete list. The right pane describes the selected system image. x86 images run the fastest in the emulator. If you see Download next to the system image, you need to click it to download the system image. You must be connected to the internet to download it. The API level of the target device is important, because your app won’t be able to run on a system image with an API level that’s less than that required by your app, as specified in the minSdkVersion attribute of the app manifest file. For more information about the relationship between system API level and minSdkVersion, see Versioning Your Apps. If your app declares a element in the manifest file, the app requires a system image in which that external library is present. If you want to run your app on an emulator, create an AVD that includes the required library. To do so, you might need to use an add-on component for the AVD platform; for example, the Google APIs add-on contains the Google Maps library. The Verify Configuration page appears. Change AVD properties as needed, and then click Finish. Click Show Advanced Settings to show more settings, such as the skin. The new AVD appears in the Your Virtual Devices page or the Select Deployment Target dialog. To create an AVD starting with a copy: From the Your Virtual Devices page of the AVD Manager, right-click an AVD and select Duplicate. Or click Menu and select Duplicate. The Verify Configuration page appears. Click Change or Previous if you need to make changes on the System Image and Select Hardware pages. Make your changes, and then click Finish. The AVD appears in the Your Virtual Devices page. Create a hardware profile
- Edit existing AVDs
- Edit existing hardware profiles
- Run and stop an emulator, and clear data
- Import and export hardware profiles From the Select Hardware page, you can import and export hardware profiles: To it a hardware profile, click Import Hardware Profiles and select the XML file containing the definition on your computer. To export a ware profile, right-click it and select Export. Specify the location where you want to store the XML file containing the definition. Hardware profile properties You can specify the following properties of hardware profiles in the Configure Hardware Profile page. AVD configuration properties override hardware profile properties, and emulator properties that you set while the emulator is running override them both. The predefined hardware profiles included with the AVD Manager aren’t editable. However, you can copy them and edit the copies. Hardware Profile Property Description Device Name Name of the hardware profile. The name can contain uppercase or lowercase letters, numbers from 0 to 9, periods (.), underscores (_), parentheses ( () ), and spaces. The name of the file storing the hardware profile is derived from the hardware profile name. Device Type Select one of the following: Phone/Tablet Wear OS Android TV Chrome OS Device Android Automotive Screen Size The physical size of the screen, in inches, measured at the diagonal. If the size is larger than your computer screen, it’s reduced in size at launch. Screen Resolution Type a width and height in pixels to specify the total number of pixels on the simulated screen. Round Select this option if the device has a round screen, such as some Wear OS devices. Memory: RAM Type a RAM size for the device and select the units, one of B (byte), KB (kilobyte), MB (megabyte), GB (gigabyte), or TB (terabyte). Input: Has Hardware Buttons (Back/Home/Menu) Select this option if your device has hardware navigation buttons. Deselect it if these buttons are implemented in software only. If you select this option, the buttons won’t appear on the screen. You can use the emulator side panel to «press» the buttons, in either case. Input: Has Hardware Keyboard Select this option if your device has a hardware keyboard. Deselect it if it doesn’t. If you select this option, a keyboard won’t appear on the screen. You can use your computer keyboard to send keystrokes to the emulator, in either case. Navigation Style Select one of the following: None — No hare controls. Navigation is through the software. D-pad — Dironal Pad support. Trackball > Wheel hese options are for actual hardware controls on the device itself. However, the events sent to the device by an external controller are the same. Supported Device States Select one or both options: Portrait — nted taller than wide. Landscape -ented wider than tall. If you select both, you can switch between orientations in the emulator. You must select at least one option to continue. Cameras To enable the camera, select one or both options: Back-Facingera — The lens faces away from the user. Front-Facinmera — The lens faces toward the user. Later, you can use a webcam or a photo provided by the emulator to simulate taking a photo with the camera. Sensors: Accelerometer Select if the device has hardware that helps the device determine its orientation. Sensors: Gyroscope Select if the device has hardware that detects rotation or twist. In combination with an accelerometer, it can provide smoother orientation detection and support a six-axis orientation system. Sensors: GPS Select if the device has hardware that supports the Global Positioning System (GPS) satellite-based navigation system. Sensors: Proximity Sensor Select if the device has hardware that detects if the device is close to your face during a phone call to disable input from the screen. Default Skin Select a skin that controls what the device looks like when displayed in the emulator. Remember that specifying a screen size that’s too big for the resolution can mean that the screen is cut off, so you can’t see the whole screen. See Create an emulator skin for more information. AVD properties You can specify the following properties for AVD configurations in the Verify Configuration page. The AVD configuration specifies the interaction between the development computer and the emulator, as well as properties you want to override in the hardware profile. AVD configuration properties override hardware profile properties. Emulator properties that you set while the emulator is running override them both. AVD Property Description AVD Name Name of the AVD. The name can contain uppercase or lowercase letters, numbers from 0 to 9, periods (.), underscores (_), parentheses ( () ), dashes (-), and spaces. The name of the file storing the AVD configuration is derived from the AVD name. AVD ID (Advanced) The AVD filename is derived from the ID, and you can use the ID to refer to the AVD from the command line. Hardware Profile Click Change to select a different hardware profile in the Select Hardware page. System Image Click Change to select a different system image in the System Image page. An active internet connection is required to download a new image. Startup Orientation Select one option for the initial emulator orientation: Portrait — nted taller than wide. Landscape -ented wider than tall. An option is enabled only if it’s selected in the hardware profile. When running the AVD in the emulator, you can change the orientation if both portrait and landscape are supported in the hardware profile. Camera (Advanced) To enable a camera, select one or both options: Front — Thes faces away from the user. Back — The faces toward the user. The Emulated setting produces a software-generated image, while the Webcam setting uses your development computer webcam to take a picture. This option is available only if it’s selected in the hardware profile; it’s not available for Wear OS and Android TV. Network: Speed (Advanced) Select a network protocol to determine the speed of data transfer: GSM — Global System for Mobile Communications HSCSD — High-Speed Circuit-Switched Data GPRS — Generic Packet Radio Service EDGE — Enhanced Data rates for GSM Evolution UMTS — Universal Mobile Telecommunications System HSDPA — High-Speed Downlink Packet Access LTE — Long-Term Evolution Full (default) — Transfer data as quickly as your computer allows. Network: Latency (Advanced) Select a network protocol to set how much time (delay) it takes for the protocol to transfer a data packet from one point to another point. Emulated Performance: Graphics Select how graphics are rendered in the emulator: Hardware — Use your computer graphics card for faster rendering. Software — Emulate the graphics in software, which is useful if you’re having a problem with rendering in your graphics card. Automatic — Let the emulator decide the best option based on your graphics card. Emulated Performance: Boot option (Advanced) Cold boot — Start the device each time by powering up from the device-off state. Quick boot — Start the device by loading the device state from a saved snapshot. For details, see Run the emulator with Quick Boot. Emulated Performance: Multi-Core CPU (Advanced) Select the number of processor cores on your computer that you’d like to use for the emulator. Using more processor cores speeds up the emulator. Memory and Storage: RAM The amount of RAM on the device. This value is set by the hardware manufacturer, but you can override it, if needed, such as for faster emulator operation. Increasing the size uses more resources on your computer. Type a RAM size and select the units, one of B (byte), KB (kilobyte), MB (megabyte), GB (gigabyte), or TB (terabyte). Memory and Storage: VM Heap The VM heap size. This value is set by the hardware manufacturer, but you can override it, if needed. Type a heap size and select the units, one of B (byte), KB (kilobyte), MB (megabyte), GB (gigabyte), or TB (terabyte). For more information on Android VMs, see Memory Management for Different Virtual Machines. Memory and Storage: Internal Storage The amount of nonremovable memory space available on the device. This value is set by the hardware manufacturer, but you can override it, if needed. Type a size and select the units, one of B (byte), KB (kilobyte), MB (megabyte), GB (gigabyte), or TB (terabyte). Memory and Storage: SD Card The amount of removable memory space available to store data on the device. To use a virtual SD card managed by Android Studio, select Studio-managed, type a size, and select the units, one of B (byte), KB (kilobyte), MB (megabyte), GB (gigabyte), or TB (terabyte). A minimum of 100 MB is recommended to use the camera. To manage the space in a file, select External file and click … to specify the file and location. For more information, see mksdcard and AVD data directory. Device Frame: Enable Device Frame Select to enable a frame around the emulator window that mimics the look of a real device. Custom Skin Definition (Advanced) Select a skin that controls what the device looks like when displayed in the emulator. Remember that specifying a screen size that’s too big for the skin can mean that the screen is cut off, so you can’t see the whole screen. See Create an emulator skin for more information. Keyboard: Enable Keyboard Input (Advanced) Select this option if you want to use your hardware keyboard to interact with the emulator. It’s disabled for Wear OS and Android TV. Create an emulator skin
- Android Studio. Создание виртуального устройства AVD
- Установка Intel HAXM
- Размеры и разрешение экрана
- Создание эмулятора Android, настройка эмулятора Android
- Новое виртуальное устройство
Содержание