- Running Your Android Application on an Android Emulator
- To Start Your Android Emulator
- To Run Your Application on Your Android Emulator
- Running Your Android Application on an Android Emulator
- To Add GPU Emulation to the Default Emulator
- To Start Your Android Emulator
- To Run Your Application on Your Android Emulator
- Run android on android virtual device
- Установка Intel HAXM
- Размеры и разрешение экрана
- Создание виртуального устройства
Running Your Android Application on an Android Emulator
After you create one or more Android emulators, you can run your RAD Studio mobile applications on your Android emulators. Before you run your application on your Android emulator, start your Android emulator as described below in To Start Your Android Emulator, so as to reduce startup time when you run your Android application from the IDE.
Caution: Android emulators are extremely slow and do not support the same feature set as real devices.
We do not recommend that you attempt to use an Android emulator:
- If you have an Android device, use your Android device instead.
- You can also use Mobile Preview to do initial debugging of an Android app.
To Start Your Android Emulator
- Start the Android Virtual Device Manager: Select Start | All Programs | Embarcadero RAD Studio XE6 | Android SDKs | Android AVD Manager .
- In the Android Virtual Device Manager, select your Android emulator in the list and click Start.
- On the Launch options dialog box, click Launch:
To Run Your Application on Your Android Emulator
- Open your Android application in RAD Studio.
- In the Project Manager, enable the emulator as the target platform. If necessary, expand the Target Platforms node and double-click the Android target platform. (The active target platform is displayed using a bold font.)
- Expand the Android node in the Project Manager.
- Expand the child Target node.
- Double-click the target Android emulator to activate it. (The active emulator is displayed using a bold font.) Note: If the emulator is not shown, right-click the Target node and select Refresh. If the emulator still is not displayed, see Using the Target Node.
In the following image you can see an emulator named rsxe6_android running, and the target platform setting activated in the Project Manager:
- In the device selector in the FireMonkey Mobile Form Designer, select the device that matches the emulator you are using. For example, if your emulator uses the WQVGA400 device, select 3.3″ WQVGA Android Phone (240dp x 400 dp).
- Run your application:
- Run with debugging ( Run >Run or F9)
- Run without debugging ( Run >Run Without Debugging or SHIFT+CTRL+F9)
- Compile and deploy messages should appear in the IDE.
- If the emulator is not running, the IDE displays: «The selected emulator is not running. Do you want start it?» Click Yes. A «Launching emulator» message is displayed.
- Open your emulator screen and watch for the app to appear. In the following image you can see a custom Nexus 4 emulator running a simple Hello World! application:
RAD Studio builds your application for Android and runs your application on the selected Android emulator. If the active Android emulator is not running, RAD Studio shows a dialog box that gives you the choice to start your Android emulator. If your Android emulator screen is locked, unlock it to access your application.
Android emulators run much slower than real devices due to the ARM platform emulation on top of a non-ARM system; if performance prevents you from using an Android emulator side by side with RAD Studio, see Running and Debugging Your Android Application Remotely. For obvious reasons, emulators also lack some of the physical features that real devices provide, although you can emulate some features], such as geo location.
Источник
Running Your Android Application on an Android Emulator
RAD Studio provides a default Android emulator for your use. The emulator is named rsxe5_android.exe, and it is located in C:\Users\ \.android\avd\ . You can either use the default rsxe5_android emulator or create an Android emulator yourself.
Before you run your application on your Android emulator, have your Android emulator already open to save some time.
To Add GPU Emulation to the Default Emulator
The default emulator (rsxe5_android) does not have the Use Host GPU property set by default. You might find that the emulator runs faster if you enable GPU emulation, as follows:
- Open the Android Virtual Device Manager:
- Select Start > All Programs > Embarcadero RAD Studio > Android Tools.
- In the SDK Manager, click the Tools menu and select Manage AVDs.
- Select the rsxe5_android emulator and click the Edit button. Note: If the rsxe5_android emulator is not present, you can create your own Android emulator. See Creating an Android Emulator.
- On the Edit Android Virtual Device (AVD) dialog box, click New in the Hardware field.
- Add the GPU emulation property and set its value to yes:
- Click Edit AVD to save your changes.
To Start Your Android Emulator
- Start the Android Virtual Device Manager:
- Select Start > All Programs > Embarcadero RAD Studio > Android Tools .
- In the SDK Manager, click the Tools menu and select Manage AVDs.
- In the Android Virtual Device Manager, select your Android emulator in the list and click Start.
- On the Launch options dialog box, click Launch:
Note: If the rsxe5_android emulator is not present, you can create your own Android emulator. See Creating an Android Emulator.
To Run Your Application on Your Android Emulator
- Open your Android application in RAD Studio.
- In the Project Manager, enable the emulator as the target platform. If necessary, expand the Target Platforms node and double-click the Android target platform. (The active target platform is displayed using a bold font.)
- Expand the Android node in the Project Manager.
- Expand the child Target node.
- Double-click the target Android emulator to activate it. (The active emulator is displayed using a bold font.) Note: If the emulator is not shown, right-click the Target node and select Refresh. If the emulator still is not displayed, see Using the Target Node.
In the following image you can see the default rsxe5_android emulator running, and the target platform setting activated in the Project Manager:
- In the device selector in the FireMonkey Mobile Form Designer, select the device that matches the emulator you are using. For example:
- If you are using the default rsxe5_android emulator with its built-in skin, select WXGA800.
- If your emulator uses the WQVGA400 device, select 3.3″ WQVGA Android Phone (240dp x 400 dp)
- Run your application:
- Run with debugging ( Run >Run or F9 )
- Run without debugging ( Run >Run Without Debugging or Shift+Ctrl+F9 )
- Compile and deploy messages should appear in the IDE.
- If the emulator is not running, the IDE displays: «The selected emulator is not running. Do you want start it?» Click Yes. A «Launching emulator» message is displayed.
- Open your emulator screen and watch for the app to appear. In the following image you can see a custom Nexus 4 emulator running a simple Hello World! application:
RAD Studio builds your application for Android and runs your application on the selected Android emulator. If the active Android emulator is not running, RAD Studio shows a dialog box that gives you the choice to start your Android emulator. If your Android emulator screen is locked, unlock it to access your application.
Android emulators run much slower than real devices due to the ARM platform emulation on top of a non-ARM system; if performance prevents you from using an Android emulator side by side with RAD Studio, see Running and Debugging Your Android Application Remotely. For obvious reasons, emulators also lack some of the features that real devices provide, although you can emulate some of those features such as geo location.
Источник
Run android on android virtual device
Виртуальное устройство Android (Android Virtual Device, AVD) позволяет разработчику тестировать свои приложения, не имея под рукой телефона с Android. Можно создавать несколько эмуляторов – устройств AVD, с различными видами конфигурации, чтобы эмулировать различные типы реальных телефонов.
Стандартный эмулятор работает достаточно медленно. Если на Вашем ПК установлен процессор Intel с поддержкой технологии виртуализации VT-x (Intel Virtualization Techology for x86 VT-x) (данные параметры устанавливаются в BIOS), то достаточно просто можно повысить его производительность. Для этого необходимо с помощью SDK Manager инсталлировать следующие пакеты:
- Intel x86 Atom System Image
- Intel x86 Emulator Accelerator (HAXM)
Образ Intel x86 Atom System Image будет доступен при создании и настройке конкретного эмулятора.
Далее необходимо установить пакет Intel x86 Emulator Accelerator (HAXM). Он находится здесь \sdk\extras\intel\Hardware_Accelerated_Execution_Manager.
Установка Intel HAXM
В процессе установки вам предложат определить объем выделяемой оперативной памяти. Вы можете оставить значение, предложенное по умолчанию. Если в процессе работы вы захотите изменить это значение – запустите установку еще раз.
Если режим не включен или не поддерживается, то появится окно сообщения:
В этом случае проверьте настройки в BIOS, возможно виртуализация поддерживается вашей системой, но по умолчанию отключена.
Размеры и разрешение экрана
Общие сведения о размерах и разрешении экранов нам понадобятся при создании виртуального устройства. Приведем основные сведения.
Существует 4 диапазона размеров экранов:
small — QVGA (320×426 dp)
normal — HVGA (320×470 dp)
large — VGA (480×640 dp)
xlarge — HVGA (720×960 dp), доступно с API 9 (Android 2.3)
и следующие диапазоны плотностей экранов:
Плотность пикселей на дюйм | Соотношение dp к px |
ldpi — 120dpi | 1 dp = 3/4 px |
mdpi — 160dpi | 1 dp = 1 px |
hdpi — 240dpi | 1 dp = 1.5 px |
xdpi — 320dpi | 1 dp = 2 px |
xxdpi — 480dpi (с API 16, Android 4.1) | 1 dp = 3 px |
xxxdpi — 640dpi (с API 18, Android 4.3) | 1 dp = 4 px |
nodpi — «как есть» | |
tvdpi — 1.33 * mdpi | 1 dp = 1.33 px |
Вот несколько примеров:
- QVGA (Quarter Video Graphics Array) 240×320 dp – низкая плотность, размер 2-3,5″;
- WQVGA (Wide Quarter Video Graphics Array) 240×400 dp – низкая плотность, размер 2-3,5″;
- HVGA (Half Video Graphics Array) 320×480 dp – средняя плотность, размер 3-4″;
- WVGA800 (Wide Video Graphics Array) 480×800 dp) –высокая плотность, размер 4-7″;
- WVGA854 (Wide Video Graphics Array) 480×854 dp) –высокая плотность, размер 4-7″;
Создание виртуального устройства
После установки образа эмулятора Android для x86 необходимо создать новое виртуальное устройство с помощью Android Virtual Device Manager. Для этого:
- Запускаем ADV Manager. Меню Tools|Android|AVD Manager.
Примечание. Если запустить ADV Manager из папки установки SDK, то появится более простое и знакомое диалоговое окно по IDE Eclipse. - Выбираем создание устройства «+Create Virtual Device«
На этом экране из возможных типов эмуляторов мобильных устройств выбираем тип Phone и переходим к выбору эмулятора модели телефона.
В начале разработки приложения, как правило, наиболее важным параметром эмулятора является скорость его работы, поэтому следует выбрать достаточно простой и быстрый эмулятор. На последующих этапах разработки приложения можно перейти на эмулятор, который наиболее точно моделирует работу реального устройства или использовать реальное устройство. В этой связи для учебных целей выбираем устройство: Nexus One (3.7” 480×800 hdpi) или Nexus S(4.0″480×800 hdpi). Эти эмуляторы требует немного оперативной памяти (500 mb и 375 mb) и поэтому достаточно быстро работают. Следует помнить, что «крутой эмулятор» потребует большие ресурсы ПК, что приводит к медленной его работе, а иногда он может просто не запуститься.
Далее жмём кнопку «Next» и переходим на экран, предлагающий выбрать версию операционной системы для эмулятора.
У Google издавна сложилась традиция называть разрабатываемые версии операционных систем тремя словами:
KitKat — Key Lime Pie(Лаймовый Пирог)
Lollipop — Lemon Meringue Pie(Лимонный Пирог Безе)
MNC — Macadamia Nut Cookie (Печенье из Ореха Макадамия).
Поскольку на ПК, на котором будет запускаться эмулятор, установлен процессор Intel с поддержкой технологии виртуализации VT и используется ОС Windows 7 x86, то выбираем Lollipop уровень API 22, ABI x86, целевая версия Android 5.1.1.
ABI — двоичный интерфейс приложения (Application binary interface)- это образ аппаратной части выбираемой аппаратной платформы создаваемого виртуального устройства. Здесь как раз и следует выбирать x86 образ, который был установлен нами ранее.
Target — целевая версия Android это версия API, на которую ориентировано приложение. Выберем самую новую.
Лучше всегда использовать более новую версию потому, что она содержит более новую версию компилятора и дополнительные проверки, позволяющие в автоматическом режиме находить часто встречающие ошибки. Кроме того:
- использование самой последней версии гарантирует, что у нас корректный и оптимальный код.
- это нас ни как не ограничивает, чтобы поддерживать более старые версии платформы в готовом приложении.
Если необходима поддержка более старых версий, то необходимо перед созданием виртуального устройства скачать и установить соответствующие пакеты (точно так же как описана установка примеров из SDK приведенная выше).
Если мы ошибочно выберем образ системы, который нами не установлен, то будет выдано соответствующее предупреждение : Consider using an x86 system image for better emulator performance (рассмотрите использование образа системы x86 для повышения производительности эмулятора). Соответствующий экран представлен ниже.
Переходим к следующему экрану. Здесь при необходимости можно внести изменения в характеристики создаваемого виртуального устройства.
Обратим внимание на следующие параметры:
AVD Name — Имя устройства. Можно задать какое нравится, рекомендую указывать что-то простое, на латинице, без пробелов, например, имя устройства и номер AIP: Nexus_S_API22.
Startup size and orientation
Scale – позволяет изменить размер эмулятора на экране монитора.
Orientation — позволяет задать книжную или альбомную ориентацию
Emulated performance — производительность эмулятора.
Use Host GPU — использование аппаратного ускорения графики при работе эмулятора. Рекомендуется включить данную опцию — так графика в эмуляторе будет работать быстрее.
Snapshot — снимок системы — при включении этой опции эмулятор виртуального устройства будет сохранять свое состояние при рестарте, т.е. после включения (загрузки) получаем устройство в том же состоянии как перед выключением (выгрузкой) эмулятора. Данную опцию пока трогать не будем, оставим ее в выключенном состоянии.
Camera — камера
Front Back — включение эмуляции камер (фронтальной и основной), при желании можно вывести через них картинку с web-камеры. Оставим значения по умолчанию — None, так как в простых учебных примерах камеры практически не применяются, а «боевые» приложения, использующие «сложные» аппаратные возможности надежнее отлаживать на реальных устройствах.
Memory and Storage — опции памяти и внутреннего хранилища.
Здесь указывается, сколько оперативной (RAM) памяти будет доступно в эмуляторе, а так же размер VM Heap — количество доступной памяти для одного экземпляра приложения. Рекомендуется эти значения указывать исходя из ресурсов реальных устройств, поэтому оставим значения по умолчанию (512 и 32). Однако, при увеличении этих параметров приложение в эмуляторе будет работать быстрее, но следует помнить что вы разрабатываете приложение для реального устройства, где объем оперативной памяти жестко задан производителем устройства и поменять его невозможно.
Internal Storage — внутреннее хранилище. Здесь указывается объем внутреннего устройство хранения, опять таки — указывайте значение, которое возможно на реальном устройстве.
SD Card — SD карта. Здесь, если требуется, можно указать параметры используемой виртуальной SD карты памяти (которые используются на реальных устройствах повсеместно, для расширения внутреннего хранилища). Оставим поле Size (размер) пустым — пока что не будем использовать SD карту. Для удобства программиста здесь же можно указать готовый образ SD карты в файле, если такая необходимость есть.
Frame Frame – имитировать ли внешний вид реального устройства.
Skin — скин эмулятора. Включение отображения аппаратных элементов управления в окне эмулятора (hardware buttons). Так же воспользуемся данным пунктом, что бы видеть кнопки устройства в окне эмулятора.
Keyboard — клавиатура. Включение представления аппаратной клавиатуры (hardware keyboard). Воспользуемся данным пунктом.
Теперь осталось запустить и проверить все ли настроено верно. Выбираем созданный эмулятор и запускаем его кнопкой «Start”.
Далее идем в настройки и выполняем следующие действия:
- Устанавливаем русский язык
- Проверяем работает ли эмулятор в режиме поддержки технологии виртуализации ( образ x86)
Если все было сделано правильно, то для нашего примера, в поле «Модель» мы увидим строку «Android SDK Build for x86«.
Источник