This translation is community contributed and may not be up to date. We only maintain the English version of the documentation. Read this manual in English

Разработка для Android

Устройства Android позволяют свободно запускать на них собственные приложения. Очень легко создать версию вашей игры и скопировать ее на устройство Android. В этом руководстве описаны шаги, связанные с созданием вашей игры для Android. В процессе разработки рекомендуется запускать игру через development app, так как оно позволяет осуществлять горячую перезагрузку контента и кода по беспроводной связи прямо на устройство.

Android и процесс подписания Google Play

Android требует, чтобы все APK были подписаны цифровым сертификатом перед установкой на устройство или обновлением. Если вы используете Android App Bundles, вам нужно подписать только ваш пакет приложений перед загрузкой в Play Console, а Play App Signing позаботится обо всем остальном. Однако вы также можете вручную подписать свое приложение для загрузки в Google Play, других магазинов приложений и для распространения вне магазинов.

При создании пакета Android-приложений в редакторе Defold или с помощью development app, вы можете указать файл keystore (содержащий ваш сертификат и ключ) и пароль keystore, который будет использоваться при подписании вашего приложения. Если вы этого не сделаете, Defold создаст отладочное keystore и будет использовать его при подписании пакета приложений.

Вы никогда не загружайте свое приложение в Google Play, если оно было подписано с использованием отладочного хранилища ключей. Всегда используйте специальное хранилище ключей, которое вы создали сами.

Создание хранилища ключей

Процесс подписи Android в Defold изменился в версии 1.2.173 с использования отдельного ключа и сертификата на keystore. Дополнительная информация в сообщении форума.

Вы можете создать хранилище ключей с помощью Android Studio или из терминала/командной строки:

keytool -genkey -v -noprompt -dname "CN=John Smith, OU=Area 51, O=US Air Force, L=Unknown, ST=Nevada, C=US" -keystore mykeystore.keystore -storepass 5Up3r_53cR3t -alias myAlias -keyalg RSA -validity 9125

В результате будет создан файл keystore с именем mykeystore.keystore, содержащий ключ и сертификат. Доступ к ключу и сертификату будет защищен паролем 5Up3r_53cR3t. Ключ и сертификат будут действительны в течение 25 лет (9125 дней). Сгенерированные ключ и сертификат будут идентифицированы псевдонимом myAlias.

Обязательно храните хранилище ключей и связанный с ним пароль в безопасном месте. Если вы подписываете и загружаете свои приложения в Google Play самостоятельно, а keystore или пароль keystore утерян, вы не сможете обновить приложение в Google Play. Вы можете избежать этого, используя Google Play App Signing и позволяя Google подписывать ваши приложения за вас.

Создание пакета приложений для Android

Редактор позволяет легко создать отдельный пакет приложений для вашей игры. Перед созданием пакета вы можете указать, какую иконку (иконки) использовать для приложения, установить код версии и т.д. в game.project файл настроек проекта.

Для создания пакета выберите в меню Project ▸ Bundle... ▸ Android Application....

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

Подписание пакета Android

Если вы хотите подписать свой пакет определенным хранилищем ключей, укажите Keystore и Keystore password. Ожидается, что Keystore будет иметь расширение файла .keystore, а пароль будет храниться в текстовом файле с расширением .txt:

Подписание пакета Android

Defold поддерживает создание файлов APK и AAB. Выберите APK или AAB из выпадающего списка Bundle Format.

Нажмите Create Bundle, когда вы настроите параметры пакета приложений. Затем вам будет предложено указать, где на вашем компьютере будет создан пакет.

Файл пакета приложения Android

Build variants

When you bundle a game, you need to choose what type of engine you wish to use. You have three basic options:

  • Debug
  • Release
  • Headless

These different versions are also referred to as Build variants

When you choose Project ▸ Build you’ll always get the debug version.

Debug

This type of executable is typically used during development of a game as it has several useful debugging features included:

  • Profiler - Used for gathering performance and usage counters. Learn how to use the profiler in the Profiling manual.
  • Logging - The engine will log system information, warnings and errors when logging is enabled. The engine will also output logs from the Lua print() function and from native extensions logging using dmLogInfo(), dmLogError() and so on. Learn how to read these logs in the Game and System Logs manual.
  • Hot reload - Hot-reload is a powerful feature which lets a developer reload resource while the game is running. Learn how to use this in the Hot-Reload manual.
  • Engine services - It is possible to connect to and interact with a debug version of a game through a number of different open TCP ports and services. The services include the hot-reload feature, remote log access and the profiler mentioned above, but also other services to remotely interact with the engine. Learn more about the engine services in the developer documentation.

Release

This variant has the debugging features disabled. This options should be chosen when the game is ready to be released to the app store or in other ways shared with players. It is not recommended to release a game with the debugging features enabled for a number of reasons:

  • The debugging features take up a little bit of size in the binary, and it is a best practice to try to keep the binary size of a released game as small as possible.
  • The debugging features takes a little bit of CPU time as well. This can impact the performance of the game if a user has a low-end hardware. On mobile phones the increased CPU usage will also contribute to heating and battery drain.
  • The debugging features may expose information about the game that is not intended for the eyes of the players, either from a security, cheating or fraud perspective.

Headless

This executable runs without any graphics and sound. It means that you can run the game unit/smoke tests on a CI server, or even have it as a game server in the cloud.

Установка пакета приложений для Android

Установка APK

Файл .apk можно скопировать на устройство с помощью инструмента adb (см. ниже) или в Google Play через консоль разработчика Google Play.

The adb command line tool is an easy to use and versatile program that is used to interact with Android devices. You can download and install adb as part of the Android SDK Platform-Tools, for Mac, Linux or Windows.

Download the Android SDK Platform-Tools from: https://developer.android.com/studio/releases/platform-tools. You find the adb tool in /platform-tools/. Alternatively, platform specific packages can be installed through respective package managers.

On Ubuntu Linux:

$ sudo apt-get install android-tools-adb

On Fedora 18/19:

$ sudo yum install android-tools

On macOS (Homebrew)

$ brew cask install android-platform-tools

You can verify that adb works by connecting your Android device to your computer via USB and issue the following command:

$ adb devices
List of devices attached
31002535c90ef000    device

If your device does not show up, verify that you have enabled USB debugging on the Android device. Open the device Settings and look for Developer options (or Development).

Enable USB debugging

$ adb install Defold\ examples.apk
4826 КБ/с (18774344 байта за 3,798 с)
  pkg: /data/local/tmp/my_app.apk
Success

Установка APK с использованием редактора

Вы можете установить и запустить файл .apk, используя опции редактора “Install on connected device” и “Launch installed app” в диалоговом окне создания пакета:

Установка и запуск APK

Для работы этой функции необходимо, чтобы ADB был установлен, а на подключенном устройстве была включена USB-отладка. Если редактор не может определить расположение команды ADB, необходимо указать путь к ADB в разделе Preferences.

Установка AAB

Файл .aab можно загрузить в Google Play через консоль разработчика Google Play. Также можно сгенерировать .apk файл из .aab файла для локальной установки с помощью Android bundletool.

Разрешения

Движок Defold требует ряд различных разрешений для работы всех функций движка. Разрешения определяются в AndroidManifest.xml, указанном в game.project файл настроек проекта. Подробнее о разрешениях Android можно прочитать в официальных документах. В манифесте по умолчанию запрашиваются следующие разрешения:

android.permission.INTERNET и android.permission.ACCESS_NETWORK_STATE (Уровень защиты: нормальный)

Позволяет приложениям открывать сетевые сокеты и получать доступ к информации о сетях. Эти разрешения необходимы для доступа в Интернет. (Android official docs) и (Android official docs).

android.permission.WAKE_LOCK (Уровень защиты: нормальный)

Позволяет использовать блокировку PowerManager WakeLocks для предотвращения засыпания процессора или затемнения экрана. Это разрешение необходимо для временного предотвращения засыпания устройства при получении push-уведомления. (Официальные документы Android)

Использование AndroidX

AndroidX — это значительное улучшение по сравнению с оригинальной Android Support Library, которая больше не поддерживается. Пакеты AndroidX полностью заменяют библиотеку поддержки, обеспечивая тот же функционал и предлагая новые библиотеки. Большинство Android-расширений на портале ассетов поддерживают AndroidX. Если вы не хотите использовать AndroidX, вы можете явно отключить его в пользу старой библиотеки поддержки Android, установив флажок Use Android Support Lib в манифесте приложения.

FAQ

Q: Is it possible to hide the navigation and status bars on Android?

A: Yes, set the immersive_mode setting in the Android section of your game.project file. This lets your app take over the whole screen and capture all touch events on the screen.

Q: Why am I’m getting “Failure [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES]” when installing a Defold game on device?

A: Android detects that you try to install the app with a new certificate. When bundling debug builds, each build will be signed with a temporary certificate. Uninstall the old app before installing the new version:

$ adb uninstall com.defold.examples
Success
$ adb install Defold\ examples.apk
4826 KB/s (18774344 bytes in 3.798s)
      pkg: /data/local/tmp/Defold examples.apk
Success

Q: Why am I getting errors about conflicting properties in AndroidManifest.xml when building with certain extensions?

A: This can happen when two or more extensions provide an Android Manifest stub containing the same property tag but with different values. This has for instance happened with Firebase and AdMob. The build error looks similar to this:

SEVERE: /tmp/job4531953598647135356/upload/AndroidManifest.xml:32:13-58
Error: Attribute property#android.adservices.AD_SERVICES_CONFIG@resource
value=(@xml/ga_ad_services_config) from AndroidManifest.xml:32:13-58 is also
present at AndroidManifest.xml:92:13-59 value=(@xml/gma_ad_services_config).
Suggestion: add 'tools:replace="android:resource"' to <property> element at
AndroidManifest.xml to override. 

You can read more about the issue and the workaround in reported Defold issue #9453 and Google issue #327696048.