- Quickstart¶
- Init and build for Android¶
- Run my application¶
- Run my application from Windows 10В¶
- Install on non-connected devices¶
- Installation¶
- Targeting Android¶
- Android on Ubuntu 20.04 (64bit)В¶
- Android on Windows 10В¶
- Before Using Buildozer¶
- Android on macOS¶
- TroubleShooting¶
- Buildozer stuck on “Installing/updating SDK platform tools if necessary”¶
- Aidl not found, please install it.В¶
- python-for-android related errors¶
- Targeting IOS¶
- Осторожно — Бульдозер (сборка apk пакетов в Kivy)
- Зависимости
- Create a package for Android¶
- Buildozer¶
- Packaging with python-for-android¶
- Packaging your application for the Kivy Launcher¶
- Installation of Examples¶
- Release on the market¶
- Targeting Android¶
Quickstart¶
Let’s get started with Buildozer!
Init and build for Android¶
Buildozer will try to guess the version of your application, by searching a line like __version__ = “1.0.3” in your main.py . Ensure you have one at the start of your application. It is not mandatory but heavily advised.
Create a buildozer.spec file, with:
Edit the buildozer.spec according to the specifications . You should at least change the title , package.name and package.domain in the [app] section.
Start a Android/debug build with:
Now it’s time for a coffee / tea, or a dinner if you have a slow computer. The first build will be slow, as it will download the Android SDK, NDK, and others tools needed for the compilation. Don’t worry, thoses files will be saved in a global directory and will be shared across the different project you’ll manage with Buildozer.
At the end, you should have an APK file in the bin/ directory.
Run my application¶
Buildozer is able to deploy the application on your mobile, run it, and even get back the log into the console. It will work only if you already compiled your application at least once:
For iOS, it would look the same:
You can combine the compilation with the deployment:
You can also set this line at the default command to do if Buildozer is started without any arguments:
To save the logcat output into a file named my_log.txt (the file will appear in your current directory):
To see your running application’s print() messages and python’s error messages, use:
Run my application from Windows 10В¶
- Plug your Android device on a USB port.
- Open Windows PowerShell, go into the folder where you installed the Windows version of ADB, and activate the ADB daemon. When the daemon is started you must see a number besides the word “device” meaning your device was correctly detected. In case of trouble, try another USB port or USB cable.
- Open the Linux distribution you installed on Windows Subsystem for Linux (WSL) and proceed with the deploy commands:
It is important to notice that Windows ADB and Buildozer installed ADB must be the same version. To check the versions, open PowerShell and type:
Install on non-connected devices¶
If you have compiled a package, and want to share it easily with others devices, you might be interested with the serve command. It will serve the bin/ directory over HTTP. Then you just have to access to the URL showed in the console from your mobile:
© Copyright 2014, Kivy’s Developers Revision 028adb14 .
Источник
Installation¶
Buildozer itself doesn’t depend on any library Python >= 3.3. Depending the platform you want to target, you might need more tools installed. Buildozer tries to give you hints or tries to install few things for you, but it doesn’t cover every situation.
First, install the buildozer project with:
Targeting Android¶
Android on Ubuntu 20.04 (64bit)В¶
(expected to work as well in later version, but only regularly tested in the latest LTS)
Android on Windows 10В¶
To use buildozer in Windows 10 you need first to enable Windows Subsystem for Linux (WSL) and install a Linux distribution: https://docs.microsoft.com/en-us/windows/wsl/install-win10.
These instructions were tested with WSL 1 and Ubuntu 18.04 LTS.
After installing WSL and Ubuntu in your Windows 10 machine, open Ubuntu and do this:
- Run the commands listed on the previous section (Android in Ubuntu 18.04 (64-bit).
- Run the following commands:
Windows Subsystem for Linux does not have direct access to USB. Due to this, you need to install the Windows version of ADB (Android Debug Bridge):
- Go to https://developer.android.com/studio/releases/platform-tools and click on “Download SDK Platform-Tools for Windows”.
- Unzip the downloaded file to a new folder. For example, “C:\platform-tools”.
Before Using Buildozer¶
If you wish, clone your code to a new folder, where the build process will run.
You don’t need to create a virtualenv for your code requirements. But just add these requirements to a configuration file called buildozer.spec as you will see in the following sections.
Before running buildozer in your code folder, remember to go into the buildozer folder and activate the buildozer virtualenv.
Android on macOS¶
TroubleShooting¶
Buildozer stuck on “Installing/updating SDK platform tools if necessary”¶
Press “y” then enter to continue, the license acceptance system is silently waiting for your input
Aidl not found, please install it.В¶
Buildozer didn’t install a necessary package
Then press “y” then enter to accept the license.
python-for-android related errors¶
Targeting IOS¶
Install XCode and command line tools (through the AppStore)
Источник
Осторожно — Бульдозер (сборка apk пакетов в Kivy)
Фух! Только что выбрался из под траков этого чудовища. А кое-кому повезло меньше. Как и было обещано в предыдущей статье, сегодня мы расскажем, как собираются apk пакеты для программ, написанных с использованием фреймворка Kivy при помощи утилиты Buildozer.
Что для этого понадобится? Помимо уже известных инструментов — кофе-сигареты, полкило нервов — нам потребуются ключи от новенького Бульдозера, который стоит в ангаре на github и сопутствующие зависимости, без которых он, к сожалению, не заведется, а если заведется, то никого задавить не удастся и apk пакет для Android не собрать.
Кстати, пользователи Microsoft, на своих Windows машинах за Бульдозером с нами не едут, потому что для сборки apk пакета требуется Linux система, либо ее образ на виртуалке. Ну, что ж. А мы отправляемся на github, отбуксируем Бульдозер и распакуем архив в какую-нибудь директорию. Блин. Да это просто монстр!
Спокойно. Не заводим. За рычаги не хватаемся. Во-первых, нам нужно скачать пакет pip — инструмент для установки и управления пакетами Python.
Заходим в ангар, в смысле в папку с Бульдозером.
… и выполняем команду —
Об успешной установке мы будем извещены сообщением Successfully installed buildozer. Бульдозер работает как на Python 2.7 так и на Python >= 3.3. Я использую Python 2.7. Просто потому, что я пока не пытался собирать apk пакеты для программ, написанных с использованием Python 3, хотя по заявлениям разработчиков Kivy, третий Python полностью поддерживается. Ну, и теперь, собственно, давайте скачаем python-for-android. У меня работает именно эта ветка, поэтому других я не предлагаю. Распакуйте python-for-android.zip и пока забудем о нем.
Зависимости
Их довольно много и от правильной их установки будет зависеть, сможете ли вы собрать заветную apk-шечку или придется выпить валидолу и начать все сначала. Считается, что все вышеперечисленные пакеты у вас отсутствуют и предполагается, что фреймворк Kivy установлен и успешно вами используется.
Для сборки пакета под Android нам понадобится Android SDK. Некоторые его двоичные файлы все еще находятся в 32 битных библиотеках, так что нужно сделать их доступными:
После этого можем установить следующие пакеты:
Ну, и теперь, наконец, мы готовы сесть в удобное кресло Бульдозера и схватится за рычаги управления. Заходим в папку проекта и выполняем в терминале команду —
… которая создаст в проекте файл спецификации buildozer.spec, где мы будем указывать Бульдозеру с какими параметрами собирать наше приложение.
Откроем данный файл и посмотрим его содержимое:
Теперь рассмотрим подробнее.
Это имя приложение, которое будет отображаться на Android девайсе и которое будет носить установочный apk пакет.
Уникальный домен приложения.
Директория, в которой находится точка входа в приложение — файл main.py. По умолчанию это корневая директория проекта.
Расширение файлов, которые будут включены в сборку apk пакета из вашего проекта. Структура дерева директорий, откуда указанные файлы будут браться, сохраняется.
Версия программы и в каком файле ее (версию) искать. Данный метод говорит, что в файле main.py корневой директории проекта должна быть переменная со значением версии вашего приложения.
Сторонние библиотеки, которые будут включены в сборку. Через запятую вы можете указать пакеты библиотек, с которыми работает ваше приложение, например: kivy, opencv, pil, sqlite3.
Полный список доступных библиотек вы можете посмотреть в редакторе спецификации в инструменте для построения UI — Kivy Designer. Очень рекомендую!
Изображение, которое будет показано на экране девайса пока запускается ваше приложение, где %(source.dir)s — путь к корневой директории проекта.
Иконка приложения, которая будет отображаться на девайсе.
Ориентация вашего приложения на девайсе. Помимо ‘portrait’, может принимать значение ‘landscape’. ‘fullscreen’ указывает разворачивать Activity на весь экран. Также принимает значение ‘0’.
Используемая приложением версия Android API (должна быть в Android SDK). Здесь могут возникнуть проблемы, если, например, вы указали версию Android API 10, которая отсутствует в Android NDK.
Минимальная версия Android API, поддерживаемая приложением.
Версия Android SDK.
Версия Android NDK.
Указывает создавать папку с файлами проекта на девайсе на SD карте. Рекомендую. Потому что в данном случае вы можете заменить байткомпилированое представление *.pyo файлов проекта на исходные тексты, и если будет необходимость внести в проект небольшое изменение, вы можете сделать это прямо на девайсе, отредактировав исходники или перезалив их с компьютера.
Здесь все понятно. Можете сделать следующим образом:
В таком случае Бульдозер скачает и Android SDK с указанными в спецификации версиями ANDROID API, и Android NDK, и python-for-android, будет скачан Apache-ant, если Бульдозер его не найдет. Также будут скачаны следующие библиотеки и исходники самого Python и модулей:
Да. Все это несколько хлопотно, но делается это один раз. Потом, для сборки проекта, достаточно просто отредактировать файл спецификации buildozer.spec и закинуть его в проект, который мы хотим собрать. Остальные параметры спецификации я не рассматриваю, поскольку пока я их еще сам не использоавл. И, да, параметры для сборки под iOS тоже остаются за траками, потому что я не имею девайса с данной платформой.
Собственно, эй, вы там — закройте двери Бульдозера с той стороны и прочь со взлетной полосы — мы заходим в папку проекта и выполняем в терминале команду начала компиляции:
Пройдет о-о-очень много времени (пригодились сигареты и кофе), прежде чем вы увидите заветное сообщение:
Обратите внимание, что apk-шечка получается дебажная. На Хабре есть статья, в которой описывается процесс создания подписанного пакета. К тому же размер сборки довольно внушительный — 7.6 Мб. Это потому, что Бульдозер включает в сборку весь Python целиком со всеми тестами и не нужными библиотеками. Также сам Kivy включается со всеми API даже если ваше приложение их не использует.
После установки собранного apk на девайсе и его старта, приложение будет довольно долго запускаться. Kivy потребуется время, чтобы извлечь и развернуть все библиотеки. К счачтью, все последующие загрузки программы длятся не более пяти секунд.
В следующей статье я расскажу, за какие рычаги дергать Бульдозер, чтобы увидеть собранный проект, но уже гораздо меньшего размера.
Источник
Create a package for Android¶
You can create a package for android using the python-for-android project. This page explains how to download and use it directly on your own machine (see Packaging with python-for-android ) or use the Buildozer tool to automate the entire process. You can also see Packaging your application for the Kivy Launcher to run kivy programs without compiling them.
For new users, we recommend using Buildozer as the easiest way to make a full APK. You can also run your Kivy app without a compilation step with the Kivy Launcher app.
Kivy applications can be released on an Android market such as the Play store, with a few extra steps to create a fully signed APK.
The Kivy project includes tools for accessing Android APIs to accomplish vibration, sensor access, texting etc. These, along with information on debugging on the device, are documented at the main Android page .
Buildozer¶
Buildozer is a tool that automates the entire build process. It downloads and sets up all the prequisites for python-for-android, including the android SDK and NDK, then builds an apk that can be automatically pushed to the device.
Buildozer currently works only in Linux, and is a beta release, but it already works well and can significantly simplify the apk build.
This will install buildozer in your system. Afterwards, navigate to your project directory and run:
This creates a buildozer.spec file controlling your build configuration. You should edit it appropriately with your app name etc. You can set variables to control most or all of the parameters passed to python-for-android.
Finally, plug in your android device and run:
to build, push and automatically run the apk on your device.
Buildozer has many available options and tools to help you, the steps above are just the simplest way to build and run your APK. The full documentation is available here. You can also check the Buildozer README at https://github.com/kivy/buildozer.
Packaging with python-for-android¶
You can also package directly with python-for-android, which can give you more control but requires you to manually download parts of the Android toolchain.
Packaging your application for the Kivy Launcher¶
The Kivy launcher is an Android application that runs any Kivy examples stored on your SD Card. To install the Kivy launcher, you must:
Go to the Kivy Launcher page on the Google Play Store
Click on Install
Select your phone… And you’re done!
If you don’t have access to the Google Play Store on your phone/tablet, you can download and install the APK manually from http://kivy.org/#download.
Once the Kivy launcher is installed, you can put your Kivy applications in the Kivy directory in your external storage directory (often available at /sdcard even in devices where this memory is internal), e.g.
should be a directory containing:
The file android.txt must contain:
These options are just a very basic configuration. If you create your own APK using the tools above, you can choose many other settings.
Installation of Examples¶
Kivy comes with many examples, and these can be a great place to start trying the Kivy launcher. You can run them as below:
Run the launcher and select one of the Pictures, Showcase, Touchtracer, Cymunk or other demos…
Release on the market¶
If you have built your own APK with Buildozer or with python-for-android, you can create a release version that may be released on the Play store or other Android markets.
To do this, you must run Buildozer with the release parameter (e.g. buildozer android release ), or if using python-for-android use the —release option to build.py. This creates a release APK in the bin directory, which you must properly sign and zipalign. The procedure for doing this is described in the Android documentation at https://developer.android.com/studio/publish/app-signing.html#signing-manually — all the necessary tools come with the Android SDK.
Targeting Android¶
Kivy is designed to operate identically across platforms and as a result, makes some clear design decisions. It includes its own set of widgets and by default, builds an APK with all the required core dependencies and libraries.
It is possible to target specific Android features, both directly and in a (somewhat) cross-platform way. See the Using Android APIs section of the Kivy on Android documentation for more details.
Источник