- Kivy on Android¶
- Package for Android¶
- Debugging your application on the Android platform¶
- Using Android APIs¶
- Plyer¶
- Pyjnius¶
- Android module¶
- Status of the Project and Tested Devices¶
- 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¶
- Осторожно — Бульдозер (сборка apk пакетов в Kivy)
- Зависимости
Kivy on Android¶
You can run Kivy applications on Android, on (more or less) any device with OpenGL ES 2.0 (Android 2.2 minimum). This is standard on modern devices; Google reports the requirement is met by 99.9% of devices.
Kivy APKs are normal Android apps that you can distribute like any other, including on stores like the Play store. They behave properly when paused or restarted, may utilise Android services and have access to most of the normal java API as described below.
Follow the instructions below to learn how to package your app for Android , debug your code on the device , and use Android APIs such as for vibration and reading sensors.
Package for Android¶
The Kivy project provides all the necessary tools to package your app on Android, including building your own standalone APK that may be distributed on a market like the Play store. This is covered fully in the Create a package for Android documentation.
Debugging your application on the Android platform¶
You can view the normal output of your code (stdout, stderr), as well as the normal Kivy logs, through the Android logcat stream. This is accessed through adb, provided by the Android SDK. You may need to enable adb in your device’s developer options, then connect your device to your computer and run:
You’ll see all the logs including your stdout/stderr and Kivy logger.
If you packaged your app with Buildozer, the adb tool may not be in your $PATH and the above command may not work. You can instead run:
to run the version installed by Buildozer, or find the SDK tools at $HOME/.buildozer/android/platform .
You can also run and debug your application using the Kivy Launcher. If you run your application this way, you will find log files inside the “/.kivy/logs” sub-folder within your application folder.
Using Android APIs¶
Although Kivy is a Python framework, the Kivy project maintains tools to easily use the normal java APIs, for everything from vibration to sensors to sending messages through SMS or email.
For new users, we recommend using Plyer . For more advanced access or for APIs not currently wrapped, you can use Pyjnius directly. Kivy also supplies an android module for basic Android functionality.
User contributed Android code and examples are available on the Kivy wiki.
Plyer¶
Plyer is a pythonic, platform-independent API to use features commonly found on various platforms, particularly mobile ones. The idea is that your app can call simply call a Plyer function, such as to present a notification to the user, and Plyer will take care of doing so in the right way regardless of the platform or operating system. Internally, Plyer uses Pyjnius (on Android), Pyobjus (on iOS) and some platform specific APIs on desktop platforms.
For instance, the following code would make your Android device vibrate, or raise a NotImplementedError that you can handle appropriately on other platforms such as desktops that don’t have appropriate hardware::
Plyer’s list of supported APIs is growing quite quickly, you can see the full list in the Plyer README.
Pyjnius¶
Pyjnius is a Python module that lets you access java classes directly from Python, automatically converting arguments to the right type, and letting you easily convert the java results to Python.
Pyjnius can be obtained from github, and has its own documentation.
Here is a simple example showing Pyjnius’ ability to access the normal Android vibration API, the same result of the plyer code above:
This code directly follows the java API functions to call the vibrator, with Pyjnius automatically translating the api to Python code and our calls back to the equivalent java. It is much more verbose and java-like than Plyer’s version, for no benefit in this case, though Plyer does not wrap every API available to Pyjnius.
Pyjnius also has powerful abilities to implement java interfaces, which is important for wrapping some APIs, but these are not documented here — you can see Pyjnius’ own documentation.
Android module¶
Python-for-android includes a python module (actually cython wrapping java) to access a limited set of Android APIs. This has been largely superseded by the more flexible Pyjnius and Plyer as above, but may still occasionally be useful. The available functions are given in the python-for-android documentation.
This includes code for billing/IAP and creating/accessing Android services, which is not yet available in the other tools above.
Status of the Project and Tested Devices¶
These sections previously described the existence of Kivy’s Android build tools, with their limitations and some devices that were known to work.
The Android tools are now quite stable, and should work with practically any device; our minimum requirements are OpenGL ES 2.0 and Android 2.2. These are very common now — Kivy has even been run on an Android smartwatch!
A current technical limitation is that the Android build tools compile only ARM APKs, which will not run on Android devices with x86 processors (these are currently rare). This should be added soon.
As Kivy works fine on most devices, the list of supported phones/tablets has been retired — all Android devices are likely to work if they meet the conditions above.
Источник
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.
Источник
Осторожно — Бульдозер (сборка 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 потребуется время, чтобы извлечь и развернуть все библиотеки. К счачтью, все последующие загрузки программы длятся не более пяти секунд.
В следующей статье я расскажу, за какие рычаги дергать Бульдозер, чтобы увидеть собранный проект, но уже гораздо меньшего размера.
Источник