Как установить bulldozer на windows kivy

Open source UI framework written in Python, running on Windows, Linux, macOS, Android and iOS - kivy/kivy

If you are using Windows 10, you can use WSL (also sometimes called «bash on windows»), to package your app for android.

https://docs.microsoft.com/en-us/windows/wsl/install-win10

Once your ubuntu on windows is setup, you can follow buildozer’s instructions

https://buildozer.readthedocs.io/en/latest/installation.html#installation

also follow the steps for «targeting android» for ubuntu.

Making ADB work.

Almost everything will work just like on a normal ubuntu installation (though possibly a bit slower), but adb which is used by buildozer to install the app on your android device and display the logs, can’t work directly inside WSL, but it’s possible to make it work.

First you need to check the version of adb that buildozer installed.

After a successful build of your apk, type the two following commands in bash.

adb=$(find ~/.buildozer -name adb -type f,l)
$adb --version

This will show the version of adb that was installed, for me it’s 1.0.39, but it’s probably different for you.

Download the windows version of this version of adb.

https://developer.android.com/studio/releases/platform-tools#downloads
allows you to download the latest version of the tools, try this one first.

  • extract adb from it
  • open a cmd window
  • drag and drop your extracted adb.exe onto it and type --version after it then validate.
  • If the version is more recent than the one you got through buildozer, you can download an older version by editing the version in this link

https://dl.google.com/android/repository/platform-tools_r27.0.0-windows.zip

repeat the steps to check for adb version, once you got the same version as with buildozer, create yourself a shortcut to start it easily, you don’t even need to see it, just to be able to easily start it.

using that ADB for server.

Make sure an adb server is not running in ubuntu

adb=$(find ~/.buildozer -name adb -type f,l)
$adb --kill-server

Then run the window’s adb (using cmd or just double-clicking your shortcut)

check that you can access your device by running
$adb devices in ubuntu.

Of course, your device must be in developer mode (https://developer.android.com/studio/debug/dev-options) and have usb debugging enabled (https://developer.android.com/studio/debug/dev-options) for this to work.
When you run the command, you might get a confirmation dialog on your device asking for confirmation of access to your device, this is for security purpose, and is fine to accept here as you are the one asking for connection.

After that you should be all set to do android development with buildozer on windows 10, don’t forgot to run adb on windows before trying to use it in ubuntu every time you reboot your computer.

Время прочтения
8 мин

Просмотры 55K

Фух! Только что выбрался из под траков этого чудовища. А кое-кому повезло меньше. Как и было обещано в предыдущей статье, сегодня мы расскажем, как собираются apk пакеты для программ, написанных с использованием фреймворка Kivy при помощи утилиты Buildozer.

Что для этого понадобится? Помимо уже известных инструментов — кофе-сигареты, полкило нервов — нам потребуются ключи от новенького Бульдозера, который стоит в ангаре на github и сопутствующие зависимости, без которых он, к сожалению, не заведется, а если заведется, то никого задавить не удастся и apk пакет для Android не собрать.

Кстати, пользователи Microsoft, на своих Windows машинах за Бульдозером с нами не едут, потому что для сборки apk пакета требуется Linux система, либо ее образ на виртуалке. Ну, что ж. А мы отправляемся на github, отбуксируем Бульдозер и распакуем архив в какую-нибудь директорию. Блин. Да это просто монстр!

Спокойно. Не заводим. За рычаги не хватаемся. Во-первых, нам нужно скачать пакет pip — инструмент для установки и управления пакетами Python.

sudo apt-get install python-pip

Заходим в ангар, в смысле в папку с Бульдозером…

… и выполняем команду —

sudo python setup.py install

Об успешной установке мы будем извещены сообщением 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 установлен и успешно вами используется.

sudo pip install --upgrade cython
sudo pip install virtualenv
sudo pip install Jinja2

Для сборки пакета под Android нам понадобится Android SDK. Некоторые его двоичные файлы все еще находятся в 32 битных библиотеках, так что нужно сделать их доступными:

dpkg --add-architecture i386

После этого можем установить следующие пакеты:

sudo apt-get update
sudo apt-get install -y build-essential ccache git zlib1g-dev python2.7 python2.7-dev libncurses5:i386 libstdc++6:i386 zlib1g:i386 openjdk-7-jdk unzip

Ну, и теперь, наконец, мы готовы сесть в удобное кресло Бульдозера и схватится за рычаги управления. Заходим в папку проекта и выполняем в терминале команду —

buildozer init

… которая создаст в проекте файл спецификации buildozer.spec, где мы будем указывать Бульдозеру с какими параметрами собирать наше приложение.

Откроем данный файл и посмотрим его содержимое:

buildozer.spec

[app]

# (str) Title of your application
title = DemoCleanMaster

# (str) Package name
package.name = democleanmaster

# (str) Package domain (needed for android/ios packaging)
package.domain = org.heattheatr

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,kv,jpg

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = []

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = []

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version.regex = __version__ = ['"](.*)['"]
version.filename = %(source.dir)s/main.py

# (str) Application versioning (method 2)
# version = 1.2.0

# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = kivy
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
presplash.filename = %(source.dir)s/Data/Images/presplash.jpg

# (str) Icon of the application
icon.filename = %(source.dir)s/Data/Images/logo.png

# (str) Supported orientation (one of landscape, portrait or all)
orientation = portrait

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 1

#
# Android specific
#

# (list) Permissions
android.permissions = INTERNET

# (int) Android API to use
android.api = 18

# (int) Minimum API required (8 = Android 2.2 devices)
android.minapi = 8

# (int) Android SDK version to use
android.sdk = 21

# (str) Android NDK version to use
android.ndk = 9

# (bool) Use --private data storage (True) or --dir public storage (False)
android.private_storage = False

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
android.ndk_path = /home/zavulon/Opt/android-ndk-r9

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
android.sdk_path = /home/zavulon/Opt/android-sdk

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
android.p4a_dir = /home/zavulon/Opt/Python/python-for-android

# (list) python-for-android whitelist
#android.p4a_whitelist =

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (str) python-for-android branch to use, if not master, useful to try
# not yet merged features.
#android.branch = master

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (list) Android additionnal libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

#
# iOS specific
#

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 0

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#
#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

Теперь рассмотрим подробнее…

title = DemoCleanMaster

Это имя приложение, которое будет отображаться на Android девайсе и которое будет носить установочный apk пакет.

package.name = democleanmaster
package.domain = org.heattheatr

Уникальный домен приложения.

source.dir = .

Директория, в которой находится точка входа в приложение — файл main.py. По умолчанию это корневая директория проекта.

source.include_exts = py,kv,jpg,png

Расширение файлов, которые будут включены в сборку apk пакета из вашего проекта. Структура дерева директорий, откуда указанные файлы будут браться, сохраняется.

version.regex = __version__ = ['"](.*)['"]
version.filename = %(source.dir)s/main.py

Версия программы и в каком файле ее (версию) искать. Данный метод говорит, что в файле main.py корневой директории проекта должна быть переменная со значением версии вашего приложения.

# main.py

__version__ = '0.0.1'

# ...ваш код

requirements = kivy

Сторонние библиотеки, которые будут включены в сборку. Через запятую вы можете указать пакеты библиотек, с которыми работает ваше приложение, например: kivy, opencv, pil, sqlite3.

Полный список доступных библиотек вы можете посмотреть в редакторе спецификации в инструменте для построения UI — Kivy Designer. Очень рекомендую!

presplash.filename = %(source.dir)s/Data/Images/presplash.jpg

Изображение, которое будет показано на экране девайса пока запускается ваше приложение, где %(source.dir)s — путь к корневой директории проекта.

icon.filename = %(source.dir)s/Data/Images/logo.png

Иконка приложения, которая будет отображаться на девайсе.

orientation = portrait
fullscreen = 1

Ориентация вашего приложения на девайсе. Помимо ‘portrait’, может принимать значение ‘landscape’. ‘fullscreen’ указывает разворачивать Activity на весь экран. Также принимает значение ‘0’.

android.permissions = INTERNET

Права приложения.

android.api = 18

Используемая приложением версия Android API (должна быть в Android SDK). Здесь могут возникнуть проблемы, если, например, вы указали версию Android API 10, которая отсутствует в Android NDK.

android.minapi = 8

Минимальная версия Android API, поддерживаемая приложением.

android.sdk = 21

Версия Android SDK.

android.ndk = 9

Версия Android NDK.

android.private_storage = False

Указывает создавать папку с файлами проекта на девайсе на SD карте. Рекомендую. Потому что в данном случае вы можете заменить байткомпилированое представление *.pyo файлов проекта на исходные тексты, и если будет необходимость внести в проект небольшое изменение, вы можете сделать это прямо на девайсе, отредактировав исходники или перезалив их с компьютера.

android.ndk_path = /home/zavulon/Opt/android-ndk-r9
android.sdk_path = /home/zavulon/Opt/android-sdk

android.p4a_dir = /home/zavulon/Opt/Python/python-for-android

Здесь все понятно. Можете сделать следующим образом:

android.ndk_path = 
android.sdk_path = 
android.p4a_dir = 

В таком случае Бульдозер скачает и Android SDK с указанными в спецификации версиями ANDROID API, и Android NDK, и python-for-android, будет скачан Apache-ant, если Бульдозер его не найдет. Также будут скачаны следующие библиотеки и исходники самого Python и модулей:

Да. Все это несколько хлопотно, но делается это один раз. Потом, для сборки проекта, достаточно просто отредактировать файл спецификации buildozer.spec и закинуть его в проект, который мы хотим собрать. Остальные параметры спецификации я не рассматриваю, поскольку пока я их еще сам не использоавл. И, да, параметры для сборки под iOS тоже остаются за траками, потому что я не имею девайса с данной платформой.

Собственно, эй, вы там — закройте двери Бульдозера с той стороны и прочь со взлетной полосы — мы заходим в папку проекта и выполняем в терминале команду начала компиляции:

buildozer android debug

Пройдет о-о-очень много времени (пригодились сигареты и кофе), прежде чем вы увидите заветное сообщение:

Обратите внимание, что apk-шечка получается дебажная. На Хабре есть статья, в которой описывается процесс создания подписанного пакета. К тому же размер сборки довольно внушительный — 7.6 Мб. Это потому, что Бульдозер включает в сборку весь Python целиком со всеми тестами и не нужными библиотеками. Также сам Kivy включается со всеми API даже если ваше приложение их не использует.

После установки собранного apk на девайсе и его старта, приложение будет довольно долго запускаться. Kivy потребуется время, чтобы извлечь и развернуть все библиотеки. К счачтью, все последующие загрузки программы длятся не более пяти секунд.

В следующей статье я расскажу, за какие рычаги дергать Бульдозер, чтобы увидеть собранный проект, но уже гораздо меньшего размера…

Удачных сборок! Смотрите под траки!

This guide describes how to turn your Kivy/Python app into an APK,
by running the buildozer build tool in a virtual machine. This
is not the only way to run buildozer, it can work natively on Linux
or MacOS or be run from the Windows Subsystem for Linux. See the Kivy
documentation
for more general instructions.

Creating a Virtual Machine

I’ll be using VirtualBox. Other
virtualisation software should also work, but you’ll need to adapt the
specific instructions.

We also need a target OS. I recommend Lubuntu 18.04, available here (or direct download link). Lubuntu
is a light weight Ubuntu variant. You
can also use a different distro if you like, but may need to adapt the
later instructions.

Once you have downloaded the Lubuntu iso file, start VirtualBox and
press New to create a new virtual machine. You’ll see a dialog
like the following:

New VM dialog

Fill in the other options as shown in the image. It’s fine to set a
larger memory size if you have enough available, or less may also work
fine. Then press Create to continue.

Disk image creation dialog

You now need to select a file size for your virtual hard disk. 15 GB
should be sufficient, but it’s safest to double that. Leave the other
options unchanged and choose Create to continue.

Now, select your new VM and click Start in the main VirtualBox
GUI. You should be prompted to select a virtual optical disk to boot from:

Choose iso to boot

Navigate to your Lubuntu 18.04 iso downloaded earlier, as shown, and
press Start to continue. The first screen you see should look
something like the following:

Select language

Select your language to see the boot menu:

Choose boot option

Choose the second option, «Install Lubuntu». It doesn’t matter if you
accidentally press enter to «Try Lubuntu without installing», in this
case there should be an Install Lubuntu application on the desktop
that you can click to continue the install process.

You’ll be shown a series of dialogs to help prepare the install
process. Clicking through with the defaults is fine, or select other
options if you prefer.

The fourth screen will ask what kind of install to use, as shown:

Choose install type

The options shown above should be the defaults, and are what you want
to use, so go ahead and continue.

Choose partitioning options

Next, select «Erase disk and install Lubuntu». Note that this is only
erasing the (emtpy) virtual disk image created earlier, it won’t
affect your host operating system.

Click through again, and you’ll eventually reach the user creation
screen. It doesn’t matter what your username is, I used kivyuser:

User creation dialog

Click «Continue» to finally start the install. You’ll be asked a few
more questions, but eventually will just have to wait for the
installation to complete. This shouldn’t take too long. You’ll be
prompted to «Restart Now», which you should go ahead and do.

Restart Now screen

If you have any issues with the virtual machine failing to reboot, go
ahead and select Machine > Reset in the VirtualBox menu, it
doesn’t matter how you do it as long as the machine is reset. If all
goes well, Lubuntu should now automatically boot to a login screen —
congratulations, your virtual machine is ready to use! Enter your
username and password, and proceed to the next section of instructions.

Login screen

Setting up buildozer

We can now go ahead and set up buildozer ready to build your app. Open
an LXTerminal as below:

LXTerminal location in menu

We now have to run a few commands to install everything buildozer
needs to run. Run the following command to do so, and enter your
user’s password if prompted:

sudo apt-get install python3-pip openjdk-8-jdk autoconf libtool python3-venv

That should give us everything we need for a basic app, so we can go
ahead and install buildozer:

.. code-block:: sh

python3 -m venv buildozer-env
source buildozer-env/bin/activate
pip install buildozer cython

Note that we installed cython as well, this is also required for
building the APK.

You only have to create the virtual environment once, but if you
reboot the virtual machine you’ll need to run source
buildozer-env/bin/activate again. See the Python documentation for more details.

The final step before running buildozer is to have your app ready in
the virtual machine. You can access a folder in your host machine
using VirtualBox shared folders (in the Devices > Shared Folders
menu), but I won’t cover the details here. Note though that if you do
this you must copy the folder contents to a different folder within
the virtual machine, the buidozer process will not work if run within
a shared folder.

In the following instructions I’ll assume you’ve created a folder
named app_dir and placed a main.py file inside it containing
your application code. Navigate to this folder in the terminal (cd
app_dir) and run:

.. code-block:: sh

buildozer init

This will create a buildozer.spec file alongside your main.py:

Creating buildozer.spec

Edit the buildozer.spec to set any options you like. In this example
I’ve changed only the title and pacakge.name options:

Editing buildozer.spec

I recommend changing very little for this first build, to make sure
everything works. It won’t cause any problems if you edit the
buildozer.spec again later.

We’re now ready to actually build the app into an APK file. Start the
process with:

.. code-block:: sh

buildozer -v android debug

The -v option asks for verbose output. This is recommended so that
you can keep an eye on what’s happening — the details aren’t too
important, but you should be able to see that the process never stops
in one place for too long.

Buildozer will now download the Android tools it needs. This may take
a while.

At some point you’ll be asked to accept the Android SDK license
agreement, which is printed for you as in the following image:

SDK license agreement

At this point, press «y» and then enter to accept the agreement (or
abort the process if you don’t agree). This is necessary even if you
don’t see any text asking you to do so, due to a bug in buildozer
(fixed in the next release).

After downloading everything it needs, buildozer will work through the
build process compiling and packaging each of the components for your
app. This may take a while, but as long as it doesn’t crash then
everything is fine. Future builds will be much faster unless you
change the build options, as only the contents of your app itself will
need re-packaging.

Eventually the build will complete, you’ll see a screen like the following:

Build complete

That’s it, you’re done! You can find the finished APK in the bin
directory, as noted in the final message buildozer prints.

Tests
Android
iOS
Coverage Status
Backers on Open Collective
Sponsors on Open Collective

Buildozer is a tool for creating application packages easily.

The goal is to have one «buildozer.spec» file in your app directory, describing
your application requirements and settings such as title, icon, included modules
etc. Buildozer will use that spec to create a package for Android, iOS, Windows,
OSX and/or Linux.

Buildozer currently supports packaging for Android via the python-for-android
project, and for iOS via the kivy-ios project. iOS and OSX are still under work.

For Android, buildozer will automatically download and prepare the
build dependencies. For more information, see
Android-SDK-NDK-Information.
Note that only Python 3 is supported.

Note that this tool has nothing to do with the eponymous online build service
buildozer.io.

Installing Buildozer with target Python 3 (default):

  • Install buildozer:

    # via pip (latest stable, recommended)
    # if you use a virtualenv, don't use the `--user` option
    pip install --user buildozer
    
    # latest dev version
    # if you use a virtualenv, don't use the `--user` option
    pip install --user https://github.com/kivy/buildozer/archive/master.zip
    
    # git clone, for working on buildozer
    git clone https://github.com/kivy/buildozer
    cd buildozer
    python setup.py build
    pip install -e .
    
  • Check buildozer is in your path

    `which buildozer`
    # if there is no result, and you installed with --user, add this line at the end of your `~/.bashrc` file.
    export PATH=~/.local/bin/:$PATH
    # and then run
    . ~/.bashrc
    
  • Go into your application directory and run:

    buildozer init
    # edit the buildozer.spec, then
    buildozer android debug deploy run
    

Buildozer Docker image

A Dockerfile is available to use buildozer through a Docker environment.

  • Build with:

    docker build --tag=buildozer .
    
  • Run with:

    docker run --volume "$(pwd)":/home/user/hostcwd buildozer --version
    

Buildozer GitHub action

Use ArtemSBulgakov/buildozer-action@v1
to build your packages automatically on push or pull request.
See full workflow example.

Examples of Buildozer commands

# buildozer target command
buildozer android clean
buildozer android update
buildozer android deploy
buildozer android debug
buildozer android release

# or all in one (compile in debug, deploy on device)
buildozer android debug deploy

# set the default command if nothing set
buildozer setdefault android debug deploy run

Usage

Usage:
    buildozer [--profile <name>] [--verbose] [target] <command>...
    buildozer --version

Available targets:
    android        Android target, based on python-for-android project
    ios            iOS target, based on kivy-ios project

Global commands (without target):
    distclean          Clean the whole Buildozer environment
    help               Show the Buildozer help
    init               Create an initial buildozer.spec in the current directory
    serve              Serve the bin directory via SimpleHTTPServer
    setdefault         Set the default command to run when no arguments are given
    version            Show the Buildozer version

Target commands:
    clean      Clean the target environment
    update     Update the target dependencies
    debug      Build the application in debug mode
    release    Build the application in release mode
    deploy     Deploy the application on the device
    run        Run the application on the device
    serve      Serve the bin directory via SimpleHTTPServer

Target "ios" commands:
    list_identities    List the available identities to use for signing.
    xcode              Open the xcode project.

Target "android" commands:
    adb                Run adb from the Android SDK. Args must come after --, or
                        use --alias to make an alias
    logcat             Show the log from the device
    p4a                Run p4a commands. Args must come after --, or use --alias
                        to make an alias

buildozer.spec

See buildozer/default.spec for an up-to-date spec file.

Default config

You can override the value of any buildozer.spec config token by
setting an appropriate environment variable. These are all of the
form $SECTION_TOKEN, where SECTION is the config file section and
TOKEN is the config token to override. Dots are replaced by
underscores.

For example, here are some config tokens from the [app] section of the
config, along with the environment variables that would override them.

  • title -> $APP_TITLE
  • package.name -> $APP_PACKAGE_NAME
  • p4a.source_dir -> $APP_P4A_SOURCE_DIR

Support

If you need assistance, you can ask for help on our mailing list:

  • User Group : https://groups.google.com/group/kivy-users
  • Email : kivy-users@googlegroups.com

Discord channel:

Server : https://chat.kivy.org
Channel : #support

For debugging on Android, don’t hesitate to use ADB to get logs of your application.

Contributing

We love pull requests and discussing novel ideas. Check out our
contribution guide and
feel free to improve buildozer.

The following mailing list and IRC channel are used exclusively for
discussions about developing the Kivy framework and its sister projects:

  • Dev Group : https://groups.google.com/group/kivy-dev
  • Email : kivy-dev@googlegroups.com

We also have a Discord channel:

  • Server : https://chat.kivy.org
  • Channel : #support

License

Buildozer is released under the terms of the MIT License. Please refer to the
LICENSE file.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]










Change Log

1.5.0

Full Changelog

Fixed bugs:

  • Buildozer Error ValueError: read of closed file #760

Closed issues:

  • kivy app does not support android 10+ #1551
  • Waiting for a response from the server socket #1550
  • orientation = portrait fails #1546
  • When I run the application on my smartphone, the application crashes and gives an error in logcat [WARNING] [Base ] Unknown <android> provider #1545
  • Android application crashes trying to use local storage #1544
  • Buildozer failed to work with NDK 25b (minimum supported by p4a) #1543
  • The Widget MDTopAppBar is not working in Android 12.0 #1542
  • The ‘buildozer==1.4.1.dev0’ distribution was not found and is required by the application #1541
  • anyone knows how to install torch with buildozer compiler? #1538
  • Building Kivy from a GitHub repository #1536
  • Request runtime Permission for BLUETOOTH (NEARBY DEVICES) Android 31 #1534
  • Configure.ac is outdated #1533
  • Problem in psutil Recipe #1532
  • Two errors in pyzmq recipe #1531
  • Buildozer failed to execute the last command!!!!! #1530
  • Error building apk. /usr/bin/python -m pythonforandroidtoolchain apk #1528
  • ERROR While run Buildozer android Debug #1527
  • Buildozer Requires python-for-android version with AAB #1524
  • Error JVM exception occurred: Didn’t find class «com.google.android.gms.auth.api.signin.GoogleSignInOptions» #1523
  • Could not resolve all files for configuration ‘:classpath’. #1522
  • Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x40 but on working app #1521
  • Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x40 in tid 10919 (SDLThread), pid 10882 (org.test.myapp) #1520
  • A problem occurred evaluating root project #1510
  • ModuleNotFoundError: No module named ‘kivy._clock’ #1509
  • Buildozer Raise Error when I try to convert my file… #1507
  • i got this error while trying to create an apk using buildozer #1506
  • # Command failed: [‘/usr/bin/python3’, ‘-m’, ‘pythonforandroid.toolchain’, ‘create’, ‘—dist_name=kivy_example’, ‘—bootstrap=sdl2’, ‘—requirements=python3,kivy==2.0.0rc4,kivy_garden.graph,numpy’, ‘—arch=arm64-v8a’, ‘—arch=armeabi-v7a’, ‘—copy-libs’, ‘—color=always’, ‘—storage-dir=/home/skander/kivy_examples/graphs/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a’, ‘—ndk-api=21’, ‘—ignore-setup-py’, ‘—debug’] #1505
  • Cannot allocate memory #1504
  • SSL: CERTIFICATE_VERIFY_FAILED only on Android #1502
  • Command failed: [‘tar’, ‘xzf’, ‘apache-ant-1.9.4-bin.tar.gz’] #1501
  • error while building liblzma #1498
  • How to add custom requirements in your Colab project with Buildozer? #1496
  • Buildozer requires a p4a version with AAB support. #1493
  • APK Keeps crashing #1488
  • android.presplash_color bug #1487
  • mew error #1486
  • [ERROR] Hostpython3 recently got an error #1485
  • Buildozer issue on MacOS M1 #1484
  • kivy + buildozer one place app name and version conventions #1482
  • [Feature Request] Arm64 ubuntu support #1480
  • ffmpeg is not supported in latest buildozer update. #1474
  • Android : Some .jpg are not displayed, some are. #1471
  • Issue while converting my python file to .aab: ERROR: Trying to release a package that starts with org.test #1469
  • Logs: #1468
  • Issue while converting my python file to .aab: ERROR: Trying to release a package that starts with org.test #1467
  • Buildozer stopped working suddenly #1459
  • hostpython3 download error, ssl error #1441
  • Feature: Make buildozer expose app resources folder. #1397
  • Error while trying to create an APK using Buildozer for Kivy Image processing application. Below is the Error Log. Unable to create APK file #1376
  • During APK build, matplotlib build tries to link against wrong libpng version #1362
  • No such file or directory buildozer debug run #1361
  • Question: How can I change the location of org.testapp on android? #1359
  • docker buildozer Aidl not found, please install it. #1357
  • Building Android app on macOS Catalina gives zlib headers error #1334
  • Has anyone succeeded in converting apk on M1? #1331
  • configure: error: cannot compute sizeof (long double) #1329
  • python==3.9.5 #1325
  • Buildozer fails to execute the last command #1324
  • build is crashing when I am trying to run it via docker #1323
  • build an android app with ffpyplayer #1322
  • Build APK with both x86 and arm libs #1321
  • Build failed on MacMini with M1 Processor while PhaseScriptExecution Script-113D17E2153E3DB5001310A6.sh #1318
  • Build APK Error when I append Numpy OpenCV-python matplotlib to requirements , . #1316
  • Error in compilation #1313
  • org/kivy/android/PythonActivity java.lang.NoClassDefFoundError #1308
  • Issue building a simple app, probably a user error #1299
  • Buildozer.spec add numpy to requirements #1282
  • Libffi not compiling (aarch64/arm64/armv8) #1281
  • android debug process stuck at downloading sdl2 #1273
  • having a problem in installing buildozer for kivy 1.11.1 in Ubuntu 18 #1270
  • Having a problem in installing Buildozer for Kivy in Ubuntu 18.04(Eror:autogen.sh) #1266
  • Can’t build on MacOS 11.0.1 BigSure #1262
  • NDK Missing #1250
  • buildozer crashes while applying fix_numpy_includes.patch for pandas #1244
  • Error when using buildozer android debug #1112
  • Buildozer install doc is very out of date #819

Merged pull requests:

  • Removes broken and unneeded checks, now we can support additional permission syntaxes. #1549 (misl6)
  • Makes orientation option cross-platform and conform to latest python-for-android changes, adds android.manifest.orientation. #1548 (misl6)
  • Update Python versions in test matrix #1540 (misl6)
  • Flake8 does not support inline comments for any of the keys. + Cleanup some ignored errors/warnings #1539 (misl6)
  • Removed (broken) --no-byte-compile-pyo support and added support for --no-byte-compile-python #1525 (misl6)
  • CeDeROM add FreeBSD support 20221014. #1516 (cederom)
  • Add resources #1513 (RobertFlatt)
  • Update Defaults #1512 (RobertFlatt)
  • Update installation.rst #1500 (RobertFlatt)
  • Fix presplash color #1497 (Apacelus)
  • Fixes some E275 — assert is a keyword. #1495 (misl6)
  • Show output during aab support check, as p4a may require the user input #1494 (misl6)
  • Removes six dependency in tests #1475 (misl6)
  • p4a prerequisites install should be done in non-interactive mode during CI builds. #1465 (misl6)
  • Bump version to 1.4.1.dev0 #1464 (misl6)
  • Avoid the usage of shell=True in Popen, which could lead to potential security risks. #1435 (misl6)
  • Add support for p4a option —res_xml #1230 (rambo)

1.4.0 (2022-07-20)

Full Changelog

Closed issues:

  • error #1461
  • error #1460
  • ModuleNotFoundError: No module named ‘_bz2’ #1457
  • java.nio.file.NoSuchFileException #1456
  • kivy app doesnt start on android #1455
  • (WSL) buildozer adb doesn’t recognize usb #1453
  • Error: Command […] returned non-zero exit status 1 #1452
  • Command failed: /home/username/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager —sdk_root=/home/username/.buildozer/android/platform/android-sdk platform-tools #1449
  • gradlew assembly Debug execution error when building apk #1447
  • How to run Python script in background in android? #1446
  • buildozer appclean doesnt work. #1443
  • Flags android.gradle_dependencies && android.add_jars don’t work. #1442
  • ModuleNotFoundError: No module named ‘PIL’ #1440
  • Bulldozer error while running «buildozer -v android debug» #1439
  • started app on three different andoid phones — there is no internet connection on 2 of them #1434
  • Not Able to change the python version under buildozer 1.3.0 #1432
  • ndk r22 invalid #1431
  • error building numpy with bulldozer #1426
  • sh.CommandNotFound: cmake #1424
  • Compile-time name ‘JNIUS_PYTHON3’ not defined #1422
  • Error Building hostpython3 for arm64-v8a with buildozer #1421
  • building for android failed #1420
  • Error «Aidl not found, please install it.» #1416
  • Buildozer Release Signign Issue #1415
  • Unable to run the buildozer command on initial application #1414
  • buildozer -v android debug error,please help me,thank you! #1413
  • Buildozer failed to create android app #1412
  • module encodings found error or something else #1408
  • [ERROR]: Build failed: Requested API target 27 is not available, install it with the SDK android tool. #1404
  • buildozer requirements for firebase-admin Python? #1402
  • I am given the following error, which I believe is due to recent changes for aab support in buildozer: » This buildozer version requires a python-for-android version with AAB (Android App Bundle) support. Please update your pinned version accordingly #1401
  • How to mention Python modules used in Kivy buildozer.spec file? #1400
  • Приложение вылетает при запуске #1399
  • Buildozer deploy failed with python3 -m venv venv command #1389
  • Gradlew Build error for Android on Linux #1371
  • AAB #1353
  • Error creating apk on Macos Big Sur #1345
  • BUILD FAILED #1335

Merged pull requests:

  • Updates default buildozer.spec NDK from 19b to 23b #1462 (misl6)
  • use p4a —add-source instead of manual copy of java files #1450 (tito)
  • fix aar build #1444 (mzakharo)
  • Our self-hosted Apple Silicon runner now has been migrated to actions/runner v2.292.0 which now supports arm64 natively #1438 (misl6)
  • Changes for NDK23 #1427 (HyTurtle)
  • Bump version to 1.4.0.dev0 #1411 (misl6)

1.3.0 (2022-03-13)

Full Changelog

Merged pull requests:

  • Improves iOS CI workflow and adds Apple Silicon M1 runner #1393 (misl6)
  • iOS: force archive iOS destination #1392 (syrykh)
  • simple typo #1390 (Jessime)
  • Bump support-request to v2. Previous integration has been shut down. #1385 (misl6)
  • Add android.add_assets #1382 (RobertFlatt)
  • add the option p4a.extra_args #1369 (antocuni)
  • Fix CI tests for iOS and Android #1365 (misl6)
  • Add aab (Android App Bundle) support #1356 (misl6)
  • Fixes deprecated plistlib API #1347 (meow464)
  • docs: fix a few simple typos #1327 (tshirtman)
  • use HTTPS urls #1319 (obfusk)
  • iOS OTA manifest generation for in-house app distribution #1317 (syrykh)
  • android: adaptive icon/launcher: expose p4a options in buildozer.spec #1312 (SomberNight)
  • Add enable_androidx #1311 (RobertFlatt)
  • Update iOS codesign options #1307 (syrykh)
  • Allow setting custom p4a URL instead of fork #1305 (syrykh)
  • chore : Fixed code quality issues #1300 (powerexploit)
  • added few additional options for android p4a builds #1275 (vesellov)
  • :recycle: Minor check_requirements() refactoring #1274 (AndreMiras)
  • Allow displaying only the logcat of our app. #1272 (tshirtman)
  • fix ndk version check & download link #1271 (obfusk)
  • Let buildozer.spec files pin to a specific p4a commit hash #1269 (xloem)
  • Change android.manifest_placeholders default to None #1265 (misl6)
  • Pass debug loglevel down through to python for android #1260 (xloem)
  • Use develop branch for automated tests #1257 (misl6)
  • Add android.adb_args option #1238 (germn)
  • Add support for p4a —feature option #1229 (rambo)
  • Add option for controlling p4a distutils support, fixes #1224 #1225 (rambo)
  • WSL workaround now accommodates WSL 2 #1220 (stefan-sherwood)
  • Add android.backup_rules parameter to buildozer.spec #1219 (Jorilx)
  • make include_exts etc. properly case-insentitive #1217 (obfusk)
  • Add manifestPlaceholders feature #1212 (misl6)
  • Add support for —presplash-lottie option of p4a #1208 (tshirtman)
  • Fix issue #881: Add android.allow_backup parameter to buildozer.spec #1206 (Jorilx)
  • Add link to GitHub action #1198 (ArtemSBulgakov)
  • Fixes heading for iOS target #1175 (fullbuffer)
  • :white_check_mark: Increases ios target test coverage #1171 (AndreMiras)
  • :white_check_mark: Unit test ios target #1168 (AndreMiras)
  • Expand «~» before every path normalization. #1165 (pakal)
  • :green_apple: Improves iOS support #1160 (AndreMiras)
  • :construction_worker: Moves Android build to dedicated workflow file #1158 (AndreMiras)
  • SafeConfigParser deprecated. #1155 (Julian-O)
  • Declare Buildozer to be Stable #1147 (Julian-O)
  • :fire: Drops garden support #1142 (AndreMiras)
  • :arrow_up: Bumps Ubuntu and OpenJDK versions #1140 (AndreMiras)
  • Post release bump 1.2.0.dev0 #1139 (AndreMiras)
  • Update quickstart.rst for Windows 10 #1124 (arqeco)
  • Update instalation.rst for Windows 10 #1123 (arqeco)

1.2.0 (2020-05-30)

Full Changelog

Merged pull requests:

  • Bumps to latest Cython version #1132 (AndreMiras)
  • Also integration test on macOS #1131 (AndreMiras)
  • Tests android.numeric_version config #1129 (AndreMiras)
  • Refactored the TargetAndroid tests #1127 (pavelsof)
  • Adds p4a —numeric-version support #1126 (AndreMiras)
  • Linter fixes and README.md update #1118 (AndreMiras)
  • Removes Python 2 constructions #1114 (AndreMiras)

1.1.0 (2020-05-18)

Full Changelog

Fixed bugs:

  • [Docker image] SSLError(«Can’t connect to HTTPS URL because the SSL module is not available.») #1096
  • NameError: name ‘raw_input’ is not defined #1070
  • Setup coverage testing #1058
  • AttributeError: ‘function’ object has no attribute ‘glob’ #1044

Closed issues:

  • Pygallary #1109
  • Buildozer compilation ERROR: No matching distribution found for hostpython2 (from -r requirements.txt (line 2)) #1104
  • Circular errors with Java version and Android SDK #1103
  • APK not running on Android 10? #1102
  • Buildozer command fails: Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate #1095
  • Command Failed Error #1092
  • APK Can’t be install (package can’t be install in android) #1091
  • buildozer Install python 3.8.1 #1090
  • i have weak reference error while using python 3.8 #1089
  • buildozer is choosing odd venv, and using a different python? #1080
  • Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding #1076
  • Buildozer just wont compile my app #1074
  • Autoreconf not found? #1072
  • error while buildozer android debug deploy run #1064
  • Syntax error in Kivy and KivyMD dependencies file when using Buildozer to compile KivyMD app #1051
  • Adding CFFI as a Buildozer requirement breaks the Android build #1050
  • Is buildozer compatible with Python 3.7 #1048
  • Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jre8:1.2.0 #1042
  • Error while running buildozer android debug deploy #1038
  • cant able to build apk on linux with python3 #1033
  • Keystore was tampered with, or password was incorrect #1028
  • Windows support to build Android APK #1022
  • How to make third party site-packages ‘requests’ run on Android #1021
  • Crash on buildozer android debug command. Command failed: /usr/bin/python -m pythonforandroid.toolchain #1017
  • Build failed: Couldn’t find executable for CC #1014
  • Cloning Error of python-for-android #1008
  • checking whether the C compiler works… no #1007
  • Kivy :How to ask for storage permission when app starts #1004
  • Buildozer :No module named ‘numpy.core._multiarray_umath’ #1002
  • Kivy app Crashes while import openpyxl #1001
  • Warning when i run «buildozer -v android debug» #982
  • sdkmanager is notinstalled #927

Merged pull requests:

  • Update README.md #1111 (tshirtman)
  • Fixes Docker apt cache missed #1107 (AndreMiras)
  • Adds libssl-dev to the install dependencies #1106 (AndreMiras)
  • Automatically publish to PyPI upon tagging #1105 (AndreMiras)
  • Fix punctuation and typo in README.md #1101 (hematogender)
  • Build integration test #1100 (AndreMiras)
  • Fixes missing libssl-dev dependency #1099 (AndreMiras)
  • Drops Python 2 support #1094 (AndreMiras)
  • Checks SDK, NDK and p4a get downloaded on first run #1093 (AndreMiras)
  • Integration testing #1083 (AndreMiras)
  • Also tests against macOS platform #1078 (AndreMiras)
  • Fix NameError with Python 3 and iOS target #1071 (lerela)
  • Unit tests TargetAndroid.build_package() #1069 (AndreMiras)
  • Dedicated Docker build/run job #1068 (AndreMiras)
  • F841: local variable is assigned to but never used #1066 (AndreMiras)
  • PEP8 organisation and fixes #1065 (AndreMiras)
  • Fixes coveralls.io on pull requests #1063 (AndreMiras)
  • Coveralls TOKEN is only available on branch master #1062 (AndreMiras)
  • Starts unit testing buildozer/targets/android.py #1061 (AndreMiras)
  • Setup coverage testing #1060 (AndreMiras)
  • Fix Dockerfile dependencies #1053 (Sirfanas)
  • Updates default buildozer.spec NDK from 17c to 19b #1041 (AndreMiras)
  • Fix config typo in default.spec #1026 (touilleMan)
  • Android gradle build: fix apk name #1025 (SomberNight)

1.0 (2019-12-22)

Full Changelog

Fixed bugs:

  • Accept license terms prompt is not visible #916
  • Unable to build release. File «/usr/lib/python3.6/shutil.py», line 96, in copyfile with open(src, ‘rb’) as fsrc: IOError: [Errno 2] No such file or directory: #851
  • error: cannot find -lpython3.7 #842
  • android.accept_sdk_license may misbehave #816
  • Python3 error with pexpect #221

Closed issues:

  • Sup Req : Buildozer debug does not complete — Error threading.py, sh.py, etc.. #1000
  • Buildozer failed to execute the last command #999
  • Android fullscreen mode: cannot hide status bar! #989
  • buildozer uses wrong python version and disrespects requirement versions #988
  • The version of Kivy installed on this system is too old. #987
  • Failed to download any source lists! #986
  • Aidl cannot be executed error buildozer #984
  • buildozer debug error «[WARNING]» when i run buildozer andriod debug #980
  • Building kivy app with python3 requirement gives «No compiled python is present to zip, skipping.» warning and «Unable to import kivy._clock. Have you perhaps forgotten to compile kivy? …» error when run on android device. #977
  • Java And Python-for-android toolchain errors #975
  • buildozer + python3 #973
  • Error while running «.buildozer…/native-build/python -OO -m compileall -b -f /…/app #972
  • buildozer fails with kivymd link #968
  • ndk_platform doesn’t exist: /home/rr/android-ndk-r20/platforms/android-20/arch-arm #966
  • Paused at Installing/updating SDK platform tools if necessary #965
  • java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema #962
  • please add aidl into Dockerfile #960
  • Missing _ctypes module #955
  • Kivy-Buildozer release version doesnt upload google store #953
  • buildozer using wrong kivy version #943
  • buildozer ndk-api=21 error #942
  • app crash #939
  • ERROR: JAVA_HOME is set to an invalid directory: /usr/lib/jvm/java-8-oracle #929
  • no-issue #926
  • can’t find file to patch toggle_jpg_png_webp.patch #921
  • No matching distribution found for io #915
  • Error: No matching distribution found for io(from -r requirements.txt (line 5)) #914
  • I’m also experiencing the same issue, using macOS 10.14.3 and no Docker — just plain Buildozer from the PyPi repo. What is the recommended course of action to fix this? #913
  • app crash #911
  • warnings while building apk using buildozer #910
  • buildozer error please help me!! #906
  • My application does not open in android but if it works in geany, help please. #903
  • [Docker image] Can’t compile apk: /bin/tar … «Cannot utime: Operation not permitted» #902
  • Fails to call numpy fft on android #899
  • Command failed: /usr/bin/python3 -m pythonforandroid.toolchain #898
  • error: C compiler cannot create executables #897
  • stopped at «Installing/updating SDK platform tools if necessary» #896
  • ValueError: Tried to access ndk_ver but it has not been set — this should not happen, something went wrong! #893
  • Buildozer not installing from custom source folders #892
  • Error with build requirements PIL (Python 3) #890
  • rocker plants.cvs -an active -r -p rco.png #889
  • rocker plants.cvs -an active -r -p rco.png #888
  • rocker plants.cvs -an active -r -p rco.png #887
  • rocker plants.cvs -an active -r -p rco.png #886
  • rocker plants.cvs -an active -r -p rco.png #885
  • host=arm-linux-androideabi #884
  • Buildozer has attribute errors and will not run #883
  • buildozer on osx not working #879
  • Android API Issue #877
  • What is the way to add folders and files? #875
  • Buildozer Error #874
  • Problem with «Unpacking sdl2_image» and «Parent module ‘pythonforandroid.recipes’ not found» #872
  • buildozer android debug deploy is stuck #870
  • running autoreconf -vif #866
  • Exception in thread «main» java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema #862
  • Can not build x86 APK file #861
  • But then a lot more issues, deep in the weeds now. #858
  • Create tests for PR fix bug when logcat value which cannot be decode to utf-8 #857
  • Can’t Cythonize pyjnius: TypeError: can’t pickle Argument objects #850
  • buildozer -h complains about NoneType target #849
  • Building failes at compiling openssl[armeabi-v7a] #841
  • Applying patches for libffi[armeabi-v7a] #840
  • Errors while running buildozer android debug deploy #832
  • «Command failed» when running «buildozer android debug deploy run» #829
  • Build Python3 for Android with Azure-keyvault and merest #828
  • Outdated Android NDK download URL in Kivy Virtual Machine #827
  • App crashes on startup #826
  • I found the origin of the problem mentioned in issue #694 (Aidl not found) #824
  • download() is not CI log friendly #823
  • Application stuck in portrait mode #820
  • Orientation landscape when set to portrait #818
  • Certain python requirements fail due to _ctypes #815
  • Running buildozer help crashes #813
  • [Buildozer 0.40.dev0, Buildozer 0.39] AttributeError: ‘Buildozer’ object has no attribute ‘translate_target’ #812
  • Version number failing to be added to apk #810
  • Virtual machine out of date #764
  • Docker doesn’t build #751
  • Buildozer exit code on recipe fail #674
  • not able to release apk in release mode — build failed #363
  • Issue with NDK r11b #308
  • Feature: Create a compat.py for correct PY3 support and implement it #300
  • Curl missing in KivyVM #296
  • Virtual machine image could have better support for international keyboards #295
  • Virtual machine image does not have enough disk space #294
  • Not quite an issue, just some dependency stuff #247
  • # Command failed: ./distribute.sh -m «kivy» -d «stapp» #204
  • Command ./distribute.sh failed — no buildozer.spec found when it exists #203
  • buildozer -v android debug : Compile fails at fcntlmodule.c #196
  • Build errors on OSX 10.10 (for android) #165
  • Feature Request: Vagrantfile #154

Merged pull requests:

  • Feature GitHub actions #1005 (tito)
  • Fixes test_p4a_recommended_android_ndk_found() mocking #983 (AndreMiras)
  • Fixes packaging for current p4a develop branch #978 (misl6)
  • Updates install instructions and troubleshooting #976 (AndreMiras)
  • fix: show output of sdk update if auto_accept_license is false #970 (tshirtman)
  • Add libs only for current arch #969 (misl6)
  • Rename final apk with arch in the name #967 (tito)
  • Code improvements around NDK download #961 (inclement)
  • Separate build per android.arch #957 (tito)
  • spec file: cast paths in source.exclude_dirs to lowercase #956 (SomberNight)
  • added cmake to requirements #950 (mcroni)
  • Add ability to get p4a’s recommended android’s NDK version #947 (opacam)
  • New feature: allow to use a p4a fork #940 (opacam)
  • Minor linter fix #937 (AndreMiras)
  • Update installation.rst #936 (yairlempert)
  • clarify overriding of config tokens #935 (brentpicasso)
  • Extend add_libs to arm64-v8a #934 (misl6)
  • Doc/installation updates #932 (tshirtman)
  • customizability options #919 (zworkb)
  • disable orientation and window option for service_only bootstrap #912 (zworkb)
  • Unit test unicode decode on command output, fixes #857 #905 (AndreMiras)
  • Made sure to print all lines of license question by always flushing #904 (inclement)
  • Exits with error code on build exception, fixes #674 #882 (AndreMiras)
  • Download Apache ANT at the same path as the buildozer.spec android.ant_path option #860 (robertpro)
  • Fix for bug when logcat value which cannot be decode to utf-8 #856 (Draqun)
  • Changes default log level to debug (2) #855 (AndreMiras)
  • Handles unknown command/target error gracefully, closes #812 #853 (AndreMiras)
  • Updates system requirements needed to build recipes #852 (AndreMiras)
  • Various Dockerfile improvements #848 (AndreMiras)
  • Support p4a uses-library argument #846 (pax0r)
  • Removed reference to Kivy VM #845 (Megalex42)
  • Removes extra log_env() call #843 (AndreMiras)
  • add missing android arch to spec file #839 (OptimusGREEN)
  • feat: make unzip quiet #836 (mkg20001)
  • fix: drop release-unsigned from release output path #835 (mkg20001)
  • Add ci_mode to toggle download progress #833 (mkg20001)
  • Unit test logger #831 (AndreMiras)
  • refactor auto accept license #822 (AndreMiras)
  • Unit tests buildozer —help command, refs #813 #821 (AndreMiras)
  • Use getbooldefault() for boolean, fixes #806 #817 (AndreMiras)
  • Update the issue template #814 (AndreMiras)
  • Show envs when run2 #802 (maho)

0.39 (2019-02-04)

Full Changelog

0.38 (2019-02-03)

Full Changelog

Fixed bugs:

  • TypeError: read() takes exactly 2 arguments (3 given) #793
  • TypeError: read() takes exactly 2 arguments (3 given) #792
  • AttributeError: ‘str’ object has no attribute ‘decode’ #756

Closed issues:

  • Openssl compilation fails, ‘__atomic’ undefined #800
  • —ndk-api appears twice #798
  • Error in toolchain.py and argument —ndk-api 9 #797
  • Target ndk-api is 19, but the **python3 recipe supports only 21** #796
  • Add support for —frameworks on iOS #790
  • Hello World impossible: checking whether the C compiler works… no #785
  • Buildozer 0.37 UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xc2 #782
  • APK Crashes on start with no obvious cause #779
  • Outdated Android NDK download URL in Kivy Virtual Machine #778
  • Buildozer «gradlew failed!» #777
  • Conflicting documentation Python2 versus Python3 #774
  • No valid —ndk-api received, using the default of 0 = min(android-api=0, default ndk-api=21) #772
  • default.spec specifies python3 but also incompatible NDK and API settings #770
  • Error: minsdk argument does not match the api that is compiled against #768
  • Need to support sensorLandscape #762
  • minsdk argument does not match the api that is compiled against #761
  • Need to be able to specify the NDK API target #758
  • Buildozer cannot import name pythran_is_numpy_func_supported #753
  • Python3 recipe not building, error with self.ctx.python_recipe #752
  • compile error #744
  • APK build failed «ndk_platform doesn’t exist» (Python3.6; android.api = 27) #742
  • Logo Design Proposal #734
  • android clean not working (FileNotFoundError: [Errno 2] No such file or directory) #732
  • Can’t Make an APK via Buildozer #712
  • App build Failed #707
  • ERROR: /home/kivy/.buildozer/android/platform/apache-ant-1.9.4/bin/ant failed! #706
  • APK using txt file in main.py issue. #704
  • «Copying APK» fails because of wrong path used #699
  • Cannot build #697
  • Fail on build #692
  • Cannot build «Hello World» APK #687
  • Error when building an android APK using Kivy #684
  • can’t get audio stream from a server #683
  • Continuous integration testing #679
  • Post build fails because copying built apk fails #671
  • Buildozer can’t compile for Android on Manjaro Linux #670
  • Icon/Logo Proposal #669
  • Buildozer cant compile platform Ubuntu 16.04 #668
  • Buildozer gets stuck at unpacking kivy #667
  • Kivy window #666
  • Failed building wheel for pyaudio #665
  • Buildozer compilation gets stuck #663
  • IOError: [Errno 2] No such file or directory: u’/home/samurai-girl/python2/.buildozer/android/platform/build/dists/test/build/outputs/apk/test-debug.apk’ #662
  • Unable to build _ctypes.so #660
  • error while packaging for android on macOS #659
  • Command failed: /usr/bin/python2 -m pythonforandroid.toolchain #658
  • Cannot build apk with buildozer android debug #656
  • How to correctly build an APK package with Python 3? #655
  • SDK does not have any Build Tools installed. #652
  • Error building Kivy app with opencv(and numpy) — raise CommandNotFoundError(path) #651
  • FileNotFoundError: [Errno 2] #649
  • The python3crystax recipe can only be built when using the CrystaX NDK. Exiting. #648
  • build apk : error can not find the build/output folder #647
  • help me building cryptography #646
  • sslv3 alert handshake failure on Addroid #643
  • Opening Android SDK Manager to download «Google Repository» and «Google Play services» #642
  • kivy python host failed #641
  • python.host failed #640
  • Kivy Crashing #638
  • .so lib files missing debug symbols #637
  • Kivy app doesn’t run #634
  • «* daemon not running. starting it now on port 5037 * * daemon started successfully *» #633
  • FileNotFoundError: [Errno 2] No such file or directory: ‘/home/alex/Documents/pengame/.buildozer/android/platform/build/dists/helloworldapp/build/outputs/apk/helloworldapp-debug.apk’ #632
  • Compiling Kivy app to apk fails with a pip error #631
  • ERROR: /home/ubuntu/.buildozer/android/platform/apache-ant-1.9.4/bin/ant failed! #625
  • Build error when building Kivy app #624
  • buildozer debug is not running this error is showing #622
  • unexpected e_machine: 3 #621
  • buildozer matplotlib #617
  • IOError: [Errno 2] No such file or directory: u’/Users/gauravgupta/kivy/.buildozer/android/platform/build/dists/myellipse/build/outputs/apk/myellipse-debug.apk’ #613
  • Build failing in final ANT stage #610
  • Cannot build apk #606
  • Installing buildozer for Python 3 failed #604
  • FileNotFoundError at end of build when copying APK file. #602
  • BUILD FAILED #601
  • Error with buildozer #591
  • ImportError: No module named Cython.Distutils While running buildozer android debug #587
  • python 2.7 compile with NDK 15c #584
  • Problem upgrade to newest version #583
  • Simple Kivy test app can’t compile to android apk #581
  • Apple Watch Support #574
  • Skip error or better error message: requirements with extra comma #562
  • failed to build numpy on Mac #557
  • p4a.source_dir set and android clean —> crash #556
  • Kivy python android build error? #555
  • python3 import networkx needs lib2to3 but cannot be imported #554
  • buildozer android debug deploy run ERROR #550
  • App Crashes #541
  • Requirements: Requests, Ssl #539
  • Error: Aidl cannot be executed #532
  • Kivy and Beautifulsoup with Buildozer fail on Python 3. #529
  • I’m having similar problem #528
  • Awkward error while building apk #526
  • The «android» command is deprecated #519
  • Kivy: Permission denied (when running buildozer android on Mac OS X) #517
  • Extraction of «Kivy2.7z» failed #516
  • buildozer still download ndk from wrong path #506
  • android-new landscape error on restart #482
  • Add possibility to choose pip version for modules in the requirements section #475
  • Bulldozer android_new fails when ffmpeg is added to the requirements: No C Compiler found! #463
  • CalledProcessError: Command ‘[‘python’, ‘package_app.py’, ‘—displayname=Music Favorites’]’ returned non-zero exit status 1 #448
  • [Errno 13] Permission denied; Buildozer on Flask Server #445
  • Error while compiling a kivy app for android (undefined reference to ‘SDL_main’ collect2: error: ld returned 1 exit status) #438
  • AsyncImage not loading in .apk #433
  • Big Bug, ORMs cant find sqlite3.so #426
  • cp: cannot stat ‘~/.buildozer/android/platform/python-for-android/src/libs/armeabi/*.so’: No such file or directory #422
  • using android_new causes missing packages errors #420
  • Buildozer fails with «Command ‘[‘ant’, ‘debug’]’ returned non-zero exit status 1» #419
  • Buildozer fails to build when ffmpeg is added #418
  • Build on arm64 android #412
  • Building with «android_new» target fails due to missing architecture on pythonforandroid.toolchain apk #407
  • Command ‘[‘ant’, ‘debug’]’ returned non-zero exit status 1 when building PIL library #406
  • Android, Pygame backend: buildozer android debug deploy run tries to launch wrong Activity #401
  • AttributeError: ‘NoneType’ object has no attribute ‘splitlines’ #400
  • Pyzmq import fails on Android with python2 / kivy 1.9 / cython 0.23 #397
  • Python 3: # Aidl cannot be executed AttributeError: ‘module’ object has no attribute ‘maxint’ #392
  • subprocess.CalledProcessError #391
  • python.host could not find platform independent libraries #390
  • Buildozer android_new fails #388
  • toolchain.py: error: argument —private is required #384
  • Android fails on running Kivy apk #381
  • ImportError: No module named plyer with android_new as a target #379
  • buildozer -v android debug runs into problem #376
  • subprocess.CalledProcessError #372
  • Can’t install Pillow , return errors #371
  • failed to load ctypes as android app built on OSX #368
  • old_toolchain not shows images #367
  • Buildozer deployment dlopen failed libSDL2.so has unexpected e_machine: 40 #365
  • Rebuild only selected packages #226

Merged pull requests:

  • Updated README for Python 3 #809 (inclement)
  • Update README.md to add opencollective #808 (tito)
  • Made buildozer respect user sdk dir when accessing sdkmanager #807 (inclement)
  • Removed android_old and updated SDK management to work with current SDK #806 (inclement)
  • Removed redundant —ndk-api argument and fixed default value #805 (inclement)
  • Update for p4a master #803 (inclement)
  • Unit tests read spec file, refs #793 #799 (AndreMiras)
  • Support the —add-frameworks flag in kivy-ios #795 (hackalog)
  • Introduces CI and tox testing, fixes #679 #794 (AndreMiras)
  • Fix python 2 crash when reading config file #791 (etc0de)
  • Handle buildozer.spec with unicode chars #789 (guysoft)
  • Specify GitHub branches in buildozer.spec #787 (hackalog)
  • Fixes minor comment typo introduced in #759 #786 (AndreMiras)
  • Docker from current git #775 (maho)
  • Fix output directory for gradle #766 (wo01)
  • support sensorLandscape mode. resolves #762 #763 (brentpicasso)
  • allow specifying of Android NDK API. Resolves #758 #759 (brentpicasso)
  • Update cython version from the docs #757 (AndreMiras)
  • fix android sdk/ndk information link #755 (avere001)
  • this allows to build with ndk 17c (and other recent-ish ones) #754 (tshirtman)
  • fix ndk URLs #747 (zworkb)

0.36 (2018-11-21)

Full Changelog

Fixed bugs:

  • Error in debug, install platform, Indexerror. #731

Closed issues:

  • Buildozer looking for nonexistent script #749
  • Can not build APK file with buildozer. UnicodeDecodeError #746
  • CrystaX no longer the preferred NDK for Python3 #745
  • AKP build fails (android.py line 524) #738
  • Buildozer 0.35 with IndexError: list index out of range on Mac OS #737
  • cannot build pyjnius for armeabi-v7a #735
  • I can’t package my app the way i always did. #733
  • OSError: [Errno 18] Invalid cross-device link #644

Merged pull requests:

  • Correctly write out a sub-process’s stdout when using Python 3. #743 (dbrnz)
  • Explicitly run pip3 when using Python 3 #741 (dbrnz)
  • workaround for working in WSL #740 (tshirtman)
  • Allow for install_reqs line having whitespace at start. #736 (dbrnz)
  • Fix Support config file name #730 (dessant)

0.35 (2018-10-24)

Full Changelog

Fixed bugs:

  • Buildozer should not regex/hack install_reqs #722

Closed issues:

  • Command failed: /usr/bin/python -m pythonforandroid.toolchain create… #727
  • buildozer fails at installing platfrom #726
  • Unable to build APK #725
  • Buildozer APK not working: OS X, Docker, or fresh Ubuntu 16.04 #723
  • gcc Segmentation Fault #720
  • Error debugging for android #719
  • ndk_platform doesn’t exist (when switching to API = 28) #717
  • FileNotFoundError: [Errno 2] (SOLVED) — It was Encoding Error #715
  • SDL_JAVA_PACKAGE_PATH error? #714
  • Python3Crystax instructions in README #710
  • Bug or support request? #708
  • build requirement failed #701
  • I am using Virtual Machine provided in the official kivy website for building android APK, this is the part of log file #696
  • App minimizes instantly after launching. #695
  • Aidl not detected #694
  • python 3 ssl #690
  • Is there something like multiprocessing? #685
  • Kivy in pyCharm #682
  • Toolchain error. Help,please! #678
  • virtual machine does not compile apk Fails with errors #677
  • An error in Buildozer Apk (Python Kivy) Help PLZ! #676
  • App crashes on android but works fine in idle window using buildozer #675
  • Pyjnius exception Adbuddiz class not found #661
  • Buildozer failed to execute the last command #/usr/bin/python3 -m pythonforandroid.toolchain create —dist_name=blueb —bootstrap=sdl2 —requirements=python3crystax,kivy —arch x86 —copy-libs —color=always —storage-dir=/home/jp/Desktop/BlueB/.buildozer/android/platform/build #654
  • java.lang.ClassNotFoundException: sun.misc.BASE64Encoder #639
  • IOError: [Errno 2] No such file or directory: #636
  • App crashes with aws boto3 #635
  • APK Immediately Closes After Opening in Debug, Release, and Zipaligned & Signed Versions #629
  • Using Python/Buildozer to compile Kivy for Android #628
  • «configure: error: C compiler cannot create executables See `config.log’ for more details» (# Command failed: ./distribute.sh -m «kivy» -d «pollygot») #627
  • «OSError: [Errno 30] Read-only file system» (# Command failed: virtualenv —python=python2.7 ./venv) #626
  • Java compiling issue: buildozer uses obsolete source value 1.5 #619
  • Cloning into ‘python-for-android-new-toolchain’… #618
  • Failed to build application: ‘WindowInfoX11’ is not a type identifier #616
  • Sudo issue[closed] #615
  • buildozer-vm-2 installed from scratch ABENDS #611
  • ASCII decode problem #608
  • error: could not delete ‘build/lib.linux-x86_64-2.7/buildozer/targets/android.py’: Permission denied #607
  • APK Build Failing with Python 3.6 #605
  • IOError: [Errno 2] No such file or directory: u’/home/kivy/buildozer/.buildozer/android/platform/build/… #603
  • Feature Request: Dockerfile or image in dockerhub #589
  • Buildozer debug error. #545

Merged pull requests:

  • Fix #645 #729 (tito)
  • Enable Support app #728 (dessant)
  • Updates p4a deps parsing #724 (AndreMiras)
  • Improved error handling if p4a setup.py can’t be read #721 (inclement)
  • Various spelling corrections #718 (Zen-CODE)
  • Updates Python 3 install instructions, fixes #710 #711 (AndreMiras)
  • Remove obsolete sh package dependency #705 (Cheaterman)
  • Changes how is_gradle_build is detected. #700 (rammie)
  • Cleans installation docs #689 (AndreMiras)
  • Adds issue template with basic required info #688 (AndreMiras)
  • buildozer Dockerfile, fixes #589 #681 (AndreMiras)
  • Removes few unused variables #680 (AndreMiras)
  • Fixed a typo pointed out by AndreMiras #664 (inclement)
  • Updates installation.rst with Ubuntu 18.04 instructions #657 (AndreMiras)
  • fix prerelease version #653 (marceloneil)
  • allow setting launchMode for the main activity in the manifest #650 (SomberNight)
  • Fixes Invalid cross-device link #645 (robertpro)
  • Quote —storage-dir value #630 (ghost)
  • Allow adding Java activities to the manifest #612 (bauerj)
  • add comment re p4a.port in default.spec #600 (replabrobin)
  • Spelling #592 (jsoref)

0.34 (2017-12-15)

Full Changelog

Closed issues:

  • IOERROR invalid directory #599
  • Buidozer 0.33 AttributeError: ‘module’ object has no attribute ‘directory’ #598
  • Issu with buildozer packing #596
  • Gradle: path may not be null or empty string. path=’null’ #595
  • ERROR: Trying to release a package that starts with org.test; what can I do? #593
  • App crash with python3 #590
  • Problem running buildozer android debug first time #586
  • buildozer download some content failed #585
  • complie platform failed #580
  • Module OS — buildozer.spec #579
  • Buildozer doesn’t compile app with cryptography requirement #578
  • Buildozer x psycopg2 #575
  • Problem with Android API 23 #573
  • App crashing on startup- ImportError: dlopen failed: _imaging.so is 64-bit #568
  • Buildozer issue with latest Xcode/macOS #566
  • Requests SSL error #565
  • buildozer failed for Broken toolchain when building numpy with python.host #564
  • Encountered a bad program behavior #563
  • error at using pycypto in the requirements #558
  • Websocket error: SSL not available. #552
  • «crystax_python does not exist» with python3crystax #551
  • App crashes after build #549
  • Installing CyLP on windows #548
  • Service notification launch intent causes app crash #547
  • Application crashes on start #546
  • New android target is unable to produce a python 4 android service #543
  • Buildozer Build Error #538
  • # Aidl not found, please install it. #537
  • Error compiling Cython file on Ubuntu 14.0.4 with python 2.7 and 3.4/5 #536
  • Failed compilation on ubuntu with python 2.7 configure: error: C compiler cannot create executables #535
  • Remove app permissions added by default #534
  • Buildozer error while packaging #531
  • Buildozer failing to pack .apk #530
  • toolchain fails to recognize option —sdk #524
  • # Command failed: /usr/bin/python -m pythonforandroid.toolchain create —dist_name=myapp —bootstrap=sdl2 —requirements=kivy —arch armeabi-v7a —copy-libs —color=always —storage-dir=/home/abhipso/thembapp/.buildozer/android/platform/build #521
  • apk way too large — 800mb #520
  • [features] Snapcraft implementation #514
  • Possibility of building in kivy virtual machine all locally #513
  • Python3(crystax ndk) builds broken #511
  • build fails in virtualenv #509
  • password for the virtual machine? #507
  • Failed to build APK with python 3.6 : [sh.CommandNotFound: python3.5] #504
  • Don’t Unpacking opencv for armeabi-v7a #503
  • Fails to package app on OSX Sierra 10.12.4 (hdiutil: attach failed — image not recognized keka) #494
  • File missing building release APK #469
  • Building APK using Buildozer/Kivy #459
  • buildozer failed to build apk: subprocess.CalledProcessError: Command ‘[‘ant’, ‘debug’]’ returned non-zero exit status 1 #373
  • AttributeError: ‘Context’ object has no attribute ‘hostpython’ in recipe #361
  • Cant compile apk with sqlite3 (using python3 crystax) #359

Merged pull requests:

  • Imported os to fix ImportError #594 (inclement)
  • add p4a.port config option; to allow specifiying webview port #588 (replabrobin)
  • Fix Py3 utf-8 encode error #582 (Zen-CODE)
  • Fixes p4a.branch comment #577 (AndreMiras)
  • Fix old toolchain index error #576 (Zen-CODE)
  • Some fixes in old android target #572 (rnixx)
  • Removed —sdk argument for p4a #571 (inclement)
  • Update specifications.rst #560 (crajun)
  • Changed p4a directory name for current toolchain #527 (inclement)
  • Update android.py, updated recreate the project.properties section #525 (mokhoo)
  • Fix unicode coding error in android build target #518 (jamalex)
  • Add 404 status code handling on kivy download #508 (SecretObsession)
  • Use dmg instead of 7z #505 (shivan1b)

0.33 (2017-05-15)

Full Changelog

Fixed bugs:

  • Installation of python for android is missing dependencies #501

Closed issues:

  • Break buildozer if the user try to release a version with «org.test» as a domain #500
  • Migrate p4a options to its own subkey #499
  • Use stable branch from python-for-android #498
  • Migrate android to android_new, and add android_old #497
  • sh.CommandNotFound: cmake #496
  • Need Help Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 4579 (SDLThread) #495
  • Buildozer APK Cannot LAUNCH #493
  • Buildozer Error #492
  • android_new target hardcodes python2 support for p4a #491
  • android.arch ignored #488
  • fail to install distribute #486
  • sh.py raise a exception and fail to build #485
  • some functionality lost when debugged with android_new command #481
  • Problem when deploy to android device #480
  • dlopen failed: python2.7/site-packages/grpc/_cython/cygrpc.so not 32-bit: 2 #479
  • Cannot build APK with python3crystax and flask — conflicting dependencies #477
  • Buildozer can’t download NDK #474
  • websocket-client «SSL not available.» #473
  • Using Cython with Kivy-iOS and Buildozer #472
  • android.requirements does not merge with app.requirements #471
  • buildozer fails to find Android SDK #468
  • Crash of APK on start #467
  • App not launching #461
  • sqlite3 not working with android_new #457
  • how to set path for p4a #454
  • TypeError: write() argument 1 must be unicode, not str #452
  • New toolchain — lxml included but not able to import #451
  • sqlite3 with python2.7 and buildozer 0.33dev and new toolchain not working #450
  • Update the Virtual Machine @ https://kivy.org/#download #449
  • “No module named setuptools” after installing setuptools #444
  • how to add —arch=armeabi-v7a to buildozer spec #443
  • buildozer android debug fails with jinja2.exceptions.TemplateNotFound: build.xml #442
  • buildozer.spec — requirements — kivy == master #440
  • Buildozer can’t find zlib #437
  • Expose kivy download source? #435
  • compiling crash #431
  • Buildozer unable to make apk #430
  • Crash APK on start #429
  • More like a noob question #428
  • keka failed to download (OS X El Capitan) #427
  • Buildozer fails with pure python library pint #425
  • Invalid argument to arm-linux-androideabi-gcc #424
  • dlopen failed: _clock.so is 64-bit instead of 32-bit #423
  • how to solve the build error for «java»? #421
  • Problems in patching files during building for android_new #416
  • Buildozer doesn’t work with multiple first-class directories #415
  • Buildozer suddenly not working, Linux, Python 2.7 (build.xml: Failed to find version-tag string) #414
  • Buildozer not finding aidl #413
  • buildozer android created apk fails if application source kept in multiple files #411
  • Python 3 unicode print () / copy to clipboard crashes app on Android #404
  • checking whether the C compiler works… no #402
  • configure: error: C compiler cannot create executables #395
  • ConfigParser.NoOptionError: No option ‘p4a.local_recipes’ in section: ‘app’ (android_new) #394
  • Google has changed the type of archive the new NDK #393
  • Why does buildozer build and pull python for android from old_toolchain branch ? #389
  • buildozer android_new does not show the presplash #387
  • Error when using buildozer android_new with python3crystax #386
  • Command failed: tar xzf android-sdk_r20-linux.tgz #383
  • When will you add requests lib to recipes? #382
  • Presplash does not work with «android_new» as target. #380
  • Build for Android is Inconsistent with the Linux Version #378
  • [question] What are the supported OS ? #369
  • AttributeError: ‘AnsiCodes’ object has no attribute ‘LIGHTBLUE_EX’ #366
  • splash image not hide after kivy loaded #364
  • app always crash in android #360
  • Plyer not available in buildozer android_new #358
  • Runs empty directory instead of binary (android_new) #357
  • App built with buildozer does not open on android #356
  • Error when running buildozer android_new debug #354
  • ios list_identities returns no identities #353
  • buildozer not working #350
  • error: Cython does not appear to be installed #349
  • AttributeError: ‘Context’ object has no attribute ‘hostpython’ #347
  • osx packaging results in venv error #345
  • Requirement example requirements = kivy,requests fails #344
  • Unavailability of important packages #343
  • no way to change bootstrap #341
  • Apk built with buildozer and multiple python file crashes #331
  • Please upgrade the documentation #255
  • Buildozer doesn’t recognize «profile» option anymore #254
  • Try to build with caldav requirement fails #248
  • Trouble building for older android versions #240
  • removing old apk file seems to fail before installing the new one #238
  • Build fails due to python-distribute.org being down #200
  • I am struggling with building an apk #153
  • fresh android sdk install requires sdk update #151
  • FYI — Ubuntu 14.04 Necessary Java Path Adjustment #141
  • Cannot compile iri2uri.py in httplib2 #135
  • can’t add django to requirement #130
  • add an ssh target #1

Merged pull requests:

  • close #452 as suggested by SpotlightKid #489 (pat1)
  • Update README.rst #487 (matletix)
  • Made buildozer run p4a using the current sys.executable #484 (inclement)
  • ios: refactor deprecated PackageApplication command #483 (kived)
  • android_new: change skip_update to skip all updates #465 (ZingBallyhoo)
  • android_new: add «android.arch» config option #458 (ZingBallyhoo)
  • Fix Py3 Incompatable str + bytes issue. #456 (FeralBytes)
  • spec file: dont use fullscreen by default #447 (rafalo1333)
  • spec file: use portrait orientation by default #446 (rafalo1333)
  • Add presplash background color support for android_new toolchain #436 (rnixx)
  • Fix file_matches to never return None #432 (inclement)
  • Fixed 64 bit detection (it failed under python3) #409 (inclement)
  • Added p4a.local_recipes to default.spec and handled its absence #405 (inclement)
  • Adding README.rst entries for how to use buildozer with python3 #403 (andyDoucette)
  • Update installation.rst (Ubuntu16.04) #399 (FermiParadox)
  • Update quickstart.rst #398 (FermiParadox)
  • Add p4a.local_recipes to buildozer.spec to specify a local recipe dir… #385 (cidermole)
  • Always pass required args to p4a in android_new #375 (inclement)
  • Changed p4a command order to work with argparse #374 (inclement)
  • buildozer has no attribute builddir #351 (nilutz)
  • throw error early if running in venv #346 (kived)
  • allow selection of bootstrap for android_new #342 (kived)
  • bump version to 0.33dev #340 (kived)
  • trying to fix Kivy install for OS X builds #316 (derPinguin)
  • update installation info #256 (kiok46)

v0.32 (2016-05-09)

Full Changelog

Closed issues:

  • When is the support coming to build windows .exe using buildozer? #333
  • outdated openssl #332
  • ios deployment fails (buildozer —verbose ios debug deploy) #330
  • Can’t add uuid pytz datetime time dbf to requirements #329
  • AttributeError: ‘NoneType’ object has no attribute ‘startswith’ #326
  • android.p4a_dir use old toolchain? #325
  • Switch from pygame to sdl2 easily #313
  • IOError: [Errno 2] No such file or directory: «/home/andrew/CODE/Python/kivy-test-android/.buildozer/android/platform/python-for-android/dist/helloworld/bin/HelloWorld-‘1.0’-debug.apk» #312
  • Marshmallow sdk not found #310
  • Install Buildozer: Finished processing dependencies for buildozer==0.32dev #304
  • Bump default min SDK to 13: Fix crash on orientation change bug #302
  • Disable «Open with file manager» when USB cable is connected in virtual machine #299
  • Check presence of main.py during build time #298
  • Py3: ‘Buildozer’ object has no attribute ‘critical’ #297
  • The splash screen isn’t automatically resized #292
  • buildozer don’t work if whitespace in path #287
  • buildozer help fail #285
  • Buildozer.spec ‘s title of your application can not be a Chinese character #284
  • How to build apk with a cython file #283
  • pip no longer has a —download-cache option, so downloading requirements has stopped working #279
  • Cython2 not recognized in Fedora23 ? #278
  • Buildozer VIrtual Machine Error: /jni/application/src/’: Not a directory #277
  • buildozer android debug deploy run hangs #275
  • Is it possible to move the .buildozer folder somewhere else? #273
  • configure: error: C compiler cannot create executables #272
  • buildozer deploy error #271
  • Cannot set Android API version #268
  • Support python3 #265
  • App crash when changing orientation #264
  • Broken update command #261
  • error while deploying android #257
  • jnius/jnius.c: No such file or directory #251
  • Implement source.include_patterns #245
  • Buildozer Python 3 Compatability Issues #175

Merged pull requests:

  • prepare for release 0.32 #339 (kived)
  • use p4a —color argument #338 (kived)
  • fix changing android branch #337 (kived)
  • use cp -a not cp -r #336 (akshayaurora)
  • improve build directory handling, add values to default.spec #335 (kived)
  • fix incorrect api/minapi values #334 (kived)
  • fix bad placement of expanduser() #328 (kived)
  • use custom source dirs for android_new #324 (kived)
  • use p4a revamp —storage-dir option #323 (kived)
  • add adb and p4a commands to android/android_new #322 (kived)
  • fix py3 str has no decode issue #321 (kived)
  • let p4a revamp handle pure python requirements #320 (kived)
  • fix icons for ios target #319 (kived)
  • support using custom kivy-ios source dir #318 (kived)
  • disable bitcode for ios target #317 (kived)
  • Add window option for target android_new #315 (pythonic64)
  • fix usage exception #311 (kived)
  • add python3 compatibility to verbose output for android build (#221) #303 (pohmelie)
  • Allow app title to contain Unicode characters #293 (udiboy1209)
  • use ios-deploy version 1.7.0 #291 (cbenhagen)
  • Add spec option to skip automated update of installed android package #290 (pastcompute)
  • Fix issues with android.p4a_dir spec file property #288 (pastcompute)
  • Remove pip —download-cache flag (fixes #279) #282 (cbenhagen)
  • put bin/ in builddir if specified in buildozer.spec #274 (jabbalaci)
  • Implement source.include_patterns #269 (udiboy1209)
  • Updated Licence Year #266 (CodeMaxx)
  • fix android.branch option #250 (tshirtman)

v0.31 (2016-01-07)

Full Changelog

Closed issues:

  • Logo aspect ratio problem #263
  • Is there a way to seperate building environment and building apk? #259
  • buildozer must be ran with sudo #258
  • Invalid NDK platform #253
  • Q:compile error #252
  • Please update SDK url #249
  • java.lang.NoSuchMethodException: isSupportChangeBadgeByCallMethod [] #243
  • AttributeError: ‘NoneType’ object has no attribute ‘group’ #242
  • Error: Flag ‘-a’ is not valid for ‘list sdk’. #241
  • Provide custom path for android SDK to buildozer #237
  • kivy examples seem to need __version__ #236
  • pyliblo #235

Merged pull requests:

  • OS X Target for Bulldozer #262 (akshayaurora)
  • kill easy_install #244 (techtonik)
  • install requires virtualenv #239 (cbenhagen)
  • Fixed Space in app path issue. Fixes #13 #231 (dvenkatsagar)

0.30 (2015-10-04)

Full Changelog

Closed issues:

  • subprocess.CalledProcessError: Command ‘[‘ant’, ‘debug’]’ returned non-zero exit status 1 #234
  • Cannot use numpy with buildozer #232
  • Problem downloading ndk version > r9d #229
  • Error likely to missing 32 bit packages #228
  • Bulldozer can’t download new ndks 10x… #227
  • Error while trying to install Buildozer in Windows 10 #225
  • Making reverse engineering .apk harder #224
  • Buildozer wont compile libraries with cython 0.23 or 0.22 #223
  • These are the errors I get when I try to package the file… #222
  • Buildozer installs platform despite setting ndk & sdk paths #220
  • Can’t find config.ini buildozer solution #219
  • Ant error: SDK does not have any Build Tools installed #218
  • Buildozer fails because of build-tools package name #217
  • ImportError: No module named pygments #216
  • buildozer android camera #215
  • Error when first time Building apk #212
  • cannot import name spawnu #211
  • Buildozer recompiles p4a when a custom for of plyer is used. #210
  • Add android.ant_path to default.spec #209
  • Problems with adding wav, ogg and ttf files #208
  • cython issue with kivy and buildozer development versions #207
  • subprocess.CalledProcessError: Command ‘[‘ant’, ‘debug’]’ returned non-zero exit status 1 #205
  • Buildozer isn’t building if I try to include some requirements #195
  • Cant build APK for android.api = 10 #193
  • Doc error: «buildozer clean» does not exist #189
  • Can’t install pillow requirement #188
  • #error from Cython compilation #150
  • Space in app path path name causes ./distribute -m kivy to fail #13

Merged pull requests:

  • Changed p4a download to pull old_toolchain branch #233 (inclement)
  • Added support for downloading and handling android ndk r10 versions. Fixes #229 and #227 #230 (dvenkatsagar)
  • make _read_version_subdir return parse(‘0’) instead of [0], otherwise… #206 (denys-duchier)

v0.29 (2015-06-01)

Full Changelog

Fixed bugs:

  • version problem with split #201

Closed issues:

  • buildozer android release hangs at «compile platform» #199
  • Hang up at Fetching https://dl-ssl.google.com/android/repository/addons_list-2.xml #198
  • Python 3 Import error on urllib.request. #187

Merged pull requests:

  • needs testing, should fix #201 using pypa implementation of PEP440 #202 (tshirtman)
  • check for complete dist instead of dist dir #197 (kived)
  • fix ios targets xcode command #194 (cbenhagen)
  • Windows fix #192 (jaynakus)
  • some python 3 compatibility #191 (pohmelie)
  • allow custom source folders in buildozer.spec #185 (kived)
  • use upstream pexpect instead of shipping it #176 (tshirtman)

v0.27 (2015-03-08)

Full Changelog

Closed issues:

  • subprocess.CalledProcessError: Command ‘[‘ant’, ‘debug’]’ returned non-zero exit status 1 #183
  • Buildozer get error during packaging for android #182
  • Bug with android.p4a_whitelist in buildozer.spec file. #180
  • You need an option for git https #178
  • Buildozer .apk file creation issue #177
  • sudo buildozer Fails #174
  • Buildozer iOS Apps Won’t Open #171
  • always show python-for-android output on failure #170
  • Buildozer tries to install android sdk every time you try to compile an android application. #169
  • automatic installation of android sdk fails due to unicode parsing error #166
  • Move from fruitstrap to ios-deploy #107
  • buildozer ios debug build fails on MacOS Mavericks #83
  • gdb doesn’t work anymore with Xcode 5 #54
  • buildozer ios debug deploy fails on running fruitstrap at 70% with error AMDeviceInstallApplication failed #9

Merged pull requests:

  • fix black text in log #184 (kived)

0.26 (2015-01-28)

Full Changelog

Merged pull requests:

  • ensure whitelist always has a list #172 (kived)

0.25 (2015-01-27)

Full Changelog

0.24 (2015-01-27)

Full Changelog

0.23 (2015-01-27)

Full Changelog

0.22 (2015-01-27)

Full Changelog

v0.21 (2015-01-14)

Full Changelog

Merged pull requests:

  • removed some indentation in example info, added to actual comments inste… #168 (chozabu)

0.19 (2014-12-17)

Full Changelog

0.18 (2014-12-17)

Full Changelog

Closed issues:

  • buildozer can’t download python libs due to ssl certificate check fail #164
  • Buildozer feature redirect .buildozer folder outside your project #162
  • Buildozer fails on clean build #161
  • pjnius build fails on Arch Linux when requiring netifaces #159
  • error compiling with buildozer #158
  • C compiler cannot create executables #152
  • Requirements needing commas instead of spaces (like p4a) is non-obvious #147

Merged pull requests:

  • fix build error and allow redirecting build folder #163 (olymk2)
  • Remove duplicated checkbin(). #160 (attakei)
  • added note about buildozer not having anything to do with buildozer.io #157 (nickyspag)
  • Fixed logic to compare with “non installed” with “minor version upped» #156 (attakei)
  • Set «UTF-8» to java file.encoding for android update command explicitly #155 (attakei)
  • added example to default.spec requirements showing comma seperation #148 (chozabu)

0.17 (2014-09-22)

Full Changelog

0.16 (2014-09-22)

Full Changelog

Closed issues:

  • install_android_packages is too slow to run in china. #143
  • Buildozer setup.py fails with Module ImportError #140
  • buildozer downloads Android SDK 20 during every call to deploy app #137
  • Buildozerv0.15: lib/pexpect.py is not Python 3 compatable #131
  • Keep on gettting version error #129
  • arm-linux-androideabi-gcc: fatal error: no input files #127
  • I am new to python and buildozer, using buildozer to compile my first android app #125
  • I am new to python and buildozer, using buildozer to compile my first android app, #124
  • Command Failed #122
  • Exception: Cython cythonnot found #120
  • Enable use for packaging OSX apps #114
  • Errors on ‘buildozer android debug deploy run’ #113
  • Fail to download Android SDK in Linux and Python 3.3 #110
  • Unable to add «requirements» buildozer.spec #109
  • TypeError: ‘encoding’ is an invalid keyword argument for this function #106
  • Custom activity #33
  • Buildozer fails to install on Windows #27
  • support blacklist changes in python-for-android #17

Merged pull requests:

  • Test in file_rename if target directory exists. #144 (droundy)
  • Fix for android.library_references path issue #139 (excessivedemon)
  • Specs doc revision #134 (dessant)
  • Make pexpect.py Python 3 Compatable #133 (FeralBytes)
  • Added check for buildozer running as root #128 (inclement)
  • Add link to the right android python project #119 (techtonik)
  • Execute buildozer as «python -m buildozer» #118 (techtonik)
  • Fix #115 #116 (manuelbua)

0.15 (2014-06-02)

Full Changelog

Closed issues:

  • Do not set permissions (ug+x) if already set #115
  • UTF-8 Encoding Error, __init.py__ 0.15-dev #108
  • incorrect minapi android manifest value #93
  • libpython wait4 linker error #92
  • fcntl import error #88
  • No Python 3 Support #84
  • Uncaught exception on missing cython #80
  • Where are custom python-for-android recipes meant to go? #76
  • Error compiling Cython file: #73
  • Zlib still giving issues on Ubuntu 13.04 #72
  • DBAccessError permission denied in app #71
  • Selective update of depencencies #70
  • 32-bit SDK installed on 64-bit system #69
  • wrong version regex #67
  • sdk update fails on license question #66
  • x86 and armeabi-v7 libs #63
  • Missing dependenced during compilation #59
  • Bad magic number when reading generated state.db file in VMware Ubuntu guest #42
  • x86 apk support on buildozer #11

Merged pull requests:

  • Ignore UTF-8 decoding errors. Closes #108 #112 (cbenhagen)
  • chmod ug+x android_cmd #111 (cbenhagen)
  • p4a whitelist #98 (b3ni)

0.14 (2014-04-20)

Full Changelog

0.13 (2014-04-20)

Full Changelog

0.12 (2014-04-20)

Full Changelog

0.11 (2014-04-20)

Full Changelog

Closed issues:

  • Text provider #105
  • No installation instructions #104

0.10 (2014-04-09)

Full Changelog

Closed issues:

  • Android SDK installation not working anymore #101
  • Buildozer almost completes and then errors saying file exists #99
  • Java compilernot found #95
  • Absolute path problem #91
  • Error when running: buildozer —verbose android debug deploy run #89
  • buildozer.spec passing requirements #87
  • debugging «Command failed» is tedious #86
  • No module named sqlite3 #56
  • Garden packages are unsupported #39
  • python-for-android repo is hard-coded in buildozer #37
  • virtualenv-2.7 hardcoded #22
  • Buildozer error no build.py #21

Merged pull requests:

  • Fixed garden install for newer virtualenvs #100 (brousch)
  • fix ln if soft link existed #96 (pengjia)
  • Added realpath modifier to p4a_dir token #94 (inclement)
  • Documented env var checking and fixed a bug in the p4a_dir check #85 (inclement)
  • Delete dist dir if running distribute.sh #81 (inclement)
  • implement the clean command. #79 (akshayaurora)
  • Garden requirements #41 (Ian-Foote)

0.9 (2014-02-13)

Full Changelog

Closed issues:

  • Command failed: ./distribute.sh -m «kivy» error message #77
  • Error importing _scproxy #68
  • Package names beginning with a number cause an obscure crash with an unclear error message #64
  • failing to compile sample android app with buildozer #61
  • Default android.sdk setting causes sensor rotate on Android to fail #32
  • Add wakelock to options #31

Merged pull requests:

  • Updated Android NDK default version to 9c #82 (brousch)
  • Add ‘bin’ to suggested default directory excludes #78 (joseph-jnl)
  • Clarified wording in README #75 (inclement)
  • Check for package name starting with number #65 (inclement)
  • [FIX] Detect 32/64 bit on Windows, to download Android NDK #62 (alanjds)
  • Added —private and —dir Android storage option #58 (brousch)
  • Added a ‘serve’ command to serve bin/ over SimpleHTTPServer #49 (brousch)

0.8 (2013-10-29)

Full Changelog

Fixed bugs:

  • _patch_application_sources breaks from __future__ imports #35

Closed issues:

  • unresolved domain: pygame.org #34

Merged pull requests:

  • Add ability to choose python-for-android directory #60 (inclement)
  • Update default Android NDK to r9 #53 (brousch)
  • Added android.wakelock option #51 (brousch)
  • Fixed another ‘Unknown’ typo #48 (brousch)
  • Fixed spelling of ‘Unknown’ #47 (brousch)
  • Fixed missing ‘r’ on ANDROIDNDKVER environment export #46 (brousch)
  • make sure android.branch works with fresh clone #44 (akshayaurora)
  • Fixed a typo in setdefault description #40 (nithin-bose)
  • Package paths #38 (Ian-Foote)
  • add applibs in path for service too #26 (tshirtman)
  • fix distribute install before installing every dependencies, fix a few i… #25 (tshirtman)

0.7 (2013-09-11)

Full Changelog

Closed issues:

  • Builds fail on Ubuntu 13.04 with zlib.h missing #18
  • «buildozer android update» fails with an error about android.branch #12
  • Problem Ubuntu compilation on network drive #10
  • [app] «android.permission» contain an unknown permission #6
  • buildozer on ios fails at: Command failed: tools/build-all.sh #5
  • Automatically installing Android SDK fails in file_rename called from _install_android_sdk #4
  • buildozer does not support ~ in android.sdk_path #3

Merged pull requests:

  • Fix typo ‘versionning’ -> ‘versioning’. #29 (Ian-Foote)
  • Fixed hard-coded Android API 14 #23 (brousch)
  • Fixed #18: Builds fail on Ubuntu 13.04 with zlib.h missing. #20 (roskakori)
  • Europython sprint updates #19 (fabiankreutz)
  • copy the generated apk back from remote #16 (akshayaurora)
  • android.add_jars config option #15 (bob-the-hamster)
  • Ouya support #14 (bob-the-hamster)

0.2 (2012-12-20)

* This Change Log was automatically generated by github_changelog_generator

В наши дни каждый разработчик может столкнуться с необходимостью работы над мобильным или веб-приложением на Python. В Python нет встроенных инструментов для мобильных устройств, тем не менее существуют пакеты, которые можно использовать для создания мобильных приложений. Это Kivy, PyQt и даже библиотека Toga от Beeware.

Содержание

  • Принципы работы фреймворка Kivy Python
  • Установка Kivy
  • Работа с виджетами в Kivy
  • Запуск программы «Hello, Kivy!»
  • Отображение виджета Image в Kivy Python
  • Разметка (Layout) в UI Kivy
  • Добавление событий в Kivy
  • Использование языка дизайна KV
  • Создание приложения Kivy Python
  • Создаем apk приложения для Android на Python
  • Создание приложений для iPhone (iOS) на Python
  • Создание exe приложений для Windows на Python используя Kivy
  • Создание приложений для macOS на Python используя Kivy

Библиотеки являются основными элементами мобильного мира Python. Однако, говоря о Kivy, нельзя игнорировать преимущества данного фреймворка при работе с мобильными приложениями. Внешний вид приложения автоматически подстраивается под все платформы, разработчику при этом не нужно компилировать код после каждой поправки. Кроме того, здесь для создания приложений можно использовать чистый синтаксис Python.

В руководстве будут разобраны следующие темы:

  • Работа с виджетами Kivy;
  • Планировка UI и лейауты;
  • Добавление событий;
  • Использование языка KV;
  • Создание приложения-калькулятора;
  • Упаковка приложения для iOS, Android, Windows и macOS.

Разбор данного руководства предполагает, что читатель знаком с объектно-ориентированным программированием. Для введения в курс дела можете просмотреть статью об Объектно-ориентированном программировании (ООП) в Python 3.

Приступим!

Принципы работы фреймворка Kivy Python

Kivy был создан в 2011 году. Данный кросс-платформенный фреймворк Python работает на Windows, Mac, Linux и Raspberry Pi. В дополнение к стандартному вводу через клавиатуру и мышь он поддерживает мультитач. Kivy даже поддерживает ускорение GPU своей графики, что во многом является следствием использования  OpenGL ES2. У проекта есть лицензия MIT, поэтому библиотеку можно использовать бесплатно и вкупе с коммерческим программным обеспечением.

Во время разработки приложения через Kivy создается интуитивно понятный интерфейс (Natural user Interface), или NUI. Его главная идея в том, чтобы пользователь мог легко и быстро приспособиться к программному обеспечению без чтения инструкций.

Kivy не задействует нативные элементы управления, или виджеты. Все его виджеты настраиваются. Это значит, что приложения Kivy будут выглядеть одинаково на всех платформах. Тем не менее, это также предполагает, что внешний вид вашего приложения будет отличаться от нативных приложений пользователя. Это может стать как преимуществом, так и недостатком, все зависит от аудитории.

Установка Kivy

У Kivy есть множество зависимостей, поэтому лучше устанавливать его в виртуальную среду Python. Можно использовать встроенную библиотеку Python venv или же пакет virtualenv.

Виртуальная среда Python создается следующим образом:

$ python3 m venv my_kivy_project

По ходу данного действия исполняемый файл Python 3 будет скопирован в папку под названием my_kivy_project, куда также будут добавлено несколько других папок.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Для использования виртуальной среды ее нужно активировать. На Mac или Linux это можно сделать, выполнив следующую команду, будучи внутри папки my_kivy_project:

Команда для Windows точно такая же, но активировать скрипт нужно в другом месте — через папку Scripts, а не bin.

После активации виртуальной среды Python можно запустить pip для установки Kivy. На Linux и Mac нужно выполнить следующую команду:

$ python m pip install kivy

Инсталляция на Windows несколько сложнее. В официальной документации фреймворка изучите пункт, касающийся установки Kivy на Windows. Пользователи Mac также могут скачать файл dmg и установить Kivy данным образом.

В случае возникновения проблем во время установки Kivy на вашу платформу изучите дополнительные инструкции, с которыми можно ознакомиться через страницу загрузки.

Работа с виджетами в Kivy

Виджеты — это отображаемые на экране элементы управления, которыми пользователь может оперировать. Любой инструментарий графического интерфейса пользователя поставляется с набором виджетов. Типичными представителями виджетов, что вы не раз использовали, являются кнопки, выпадающие списки и вкладки. Внутри фреймворка Kivy встроено много виджетов.

Запуск программы «Hello, Kivy!»

Принцип работы Kivy можно уловить, взглянув на следующее приложение «Hello, World!»:

from kivy.app import App

from kivy.uix.label import Label

class MainApp(App):

    def build(self):

        label = Label(text=‘Hello from Kivy’,

                      size_hint=(.5, .5),

                      pos_hint={‘center_x’: .5, ‘center_y’: .5})

        return label

if __name__ == ‘__main__’:

    app = MainApp()

    app.run()

Каждому приложению Kivy требуется создать подкласс App и переопределить метод build().  Сюда вы помещаете код UI или вызываете другие функции, которые определяют код UI. В данном случае создается виджет Label и передается text, size_hint и pos_hint. Последние два аргумента не обязательны.

size_hint говорит Kivy о размерах что нужно использовать при создании виджета. Используются два числа:

  1. Первое число x указывает на размер ширины элемента управления.
  2. Второе число y указывает на размер высоты элемента управления.

Значение обоих чисел должно быть в промежутке между 0 и 1. Значение по обоих показателей по умолчанию равно 1. Также можно задействовать pos_hint, что используется для позиционирования виджета. В коде, размещенном выше, указывается, что виджет должен быть размещен в центре осей x и y.

Для запуска приложения нужно инициализировать класс MainApp и вызвать метод run(). После этих действий на экране появится следующее:

App Hello from Kivy

Kivy также выводит в stdout довольно много текста:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

[INFO   ] [Logger      ] Record log in /home/mdriscoll/.kivy/logs/kivy_190607_2.txt

[INFO   ] [Kivy        ] v1.11.0

[INFO   ] [Kivy        ] Installed at «/home/mdriscoll/code/test/lib/python3.6/site-packages/kivy/__init__.py»

[INFO   ] [Python      ] v3.6.7 (default, Oct 22 2018, 11:32:17)

[GCC 8.2.0]

[INFO   ] [Python      ] Interpreter at «/home/mdriscoll/code/test/bin/python»

[INFO   ] [Factory     ] 184 symbols loaded

[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)

[INFO   ] [Text        ] Provider: sdl2([‘text_pango’] ignored)

[INFO   ] [Window      ] Provider: sdl2([‘window_egl_rpi’] ignored)

[INFO   ] [GL          ] Using the «OpenGL» graphics system

[INFO   ] [GL          ] Backend used <sdl2>

[INFO   ] [GL          ] OpenGL version <b‘4.6.0 NVIDIA 390.116’>

[INFO   ] [GL          ] OpenGL vendor <b‘NVIDIA Corporation’>

[INFO   ] [GL          ] OpenGL renderer <b‘NVS 310/PCIe/SSE2’>

[INFO   ] [GL          ] OpenGL parsed version: 4, 6

[INFO   ] [GL          ] Shading version <b‘4.60 NVIDIA’>

[INFO   ] [GL          ] Texture max size <16384>

[INFO   ] [GL          ] Texture max units <32>

[INFO   ] [Window      ] auto add sdl2 input provider

[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked

[INFO   ] [Base        ] Start application main loop

[INFO   ] [GL          ] NPOT texture support is available

Это может быть полезно для отладки приложения.

Далее добавим виджет Image и посмотрим, чем он отличается от Label.

Отображение виджета Image в Kivy Python

В Kivy есть несколько видов виджетов, связанных с изображениями. Для загрузки картинок с жесткого диска можно задействовать Image, а при использовании адреса URL подойдет AsyncImage. К следующем примере берется стандартный класс Image:

from kivy.app import App

from kivy.uix.image import Image

class MainApp(App):

    def build(self):

        img = Image(source=‘/path/to/real_python.png’,

                    size_hint=(1, .5),

                    pos_hint={‘center_x’:.5, ‘center_y’:.5})

        return img

if __name__ == ‘__main__’:

    app = MainApp()

    app.run()

В данном коде импортируется Image из подпакета kivy.uix.image. Класс Image принимает много разных параметров, однако единственным для нас нужным является source, что указывает Kivy, какое изображение должно быть загружено. Здесь передается полный путь к выбранному изображению. Оставшаяся часть кода такая же, как и в прошлом примере.

После запуска кода должно выводиться нечто подобное:

Load Image Kivy

Текст из предыдущего примера был заменен картинкой.

Теперь рассмотрим, как добавить и оптимально расположить несколько виджетов в приложении.

Разметка (Layout) в UI Kivy

У каждого фреймворка есть свой собственный метод для размещения виджетов. К примеру, в wxPython используются классификаторы, а в Tkinter будет задействован лейаут, или менеджер геометрии. В Kivy за это отвечают Лейауты (Layouts). Доступно несколько различных типов Лейаутов. Чаще всего используются следующие виды:

  • BoxLayout;
  • FloatLayout;
  • GridLayout.

Найти полный список доступных Лейаутов можно в документации Kivy. Рабочий исходный код можно найти в kivy.uix.

Рассмотрим BoxLayout на примере следующего кода:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import kivy

import random

from kivy.app import App

from kivy.uix.button import Button

from kivy.uix.boxlayout import BoxLayout

red = [1,0,0,1]

green = [0,1,0,1]

blue =  [0,0,1,1]

purple = [1,0,1,1]

class HBoxLayoutExample(App):

    def build(self):

        layout = BoxLayout(padding=10)

        colors = [red, green, blue, purple]

        for i in range(5):

            btn = Button(text=«Button #%s» % (i+1),

                         background_color=random.choice(colors)

                         )

            layout.add_widget(btn)

        return layout

if __name__ == «__main__»:

    app = HBoxLayoutExample()

    app.run()

Здесь из kivy.uix.boxlayout импортируется модуль BoxLayout и затем устанавливается. После этого создается список цветов, которые представляют собой цвета RGB (Red-Blue-Green).

В конечном итоге формируется цикл для range из 5, результатом чего является кнопка btn для каждой итерации. Сделаем вещи немного интереснее и поставим в качестве фона кнопки background_color случайный цвет. Теперь можно добавить кнопку в лейаут при помощи layout.add_widget(btn).

После запуска кода выведется нечто подобное:

Kivy Hbox Layout

Здесь представлены 5 кнопок, окрашенных случайным образом, по одной для каждой итерации цикла for.

Во время создания лейаута следует учитывать следующие аргументы:

  • padding: Отступ padding между лейаутом и его дочерними элементами уточняется в пикселях. Для этого можно выбрать один из трех способов:
    1. Список из четырех аргументов: [padding_left, padding_top, padding_right, padding_bottom]
    2. Список из двух аргументов: [padding_horizontal, padding_vertical]
    3. Один аргумент: padding=10
  • spacing: При помощи данного аргумента добавляется расстояние между дочерними виджетами.
  • orientation: Позволяет изменить значение orientation для BoxLayout по умолчанию — с горизонтального на вертикальное.

Добавление событий в Kivy

Как и многие другие инструментарии GUI, по большей части Kivy полагается на события. Фреймворк отзывается на нажатие клавиш, кнопки мышки или прикосновение к сенсорному экрану. В Kivy задействован концепт Часов (Clock), что дает возможность создать своего рода график для вызова определенных функций в будущем.

В Kivy также используется концепт Свойств (Properties), что работает с EventDispatcher. Свойства помогают осуществить проверку достоверности. Они также запускают события, когда виджет меняет размер или позицию.

Добавим событие для кнопки из предыдущего кода:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from kivy.app import App

from kivy.uix.button import Button

class MainApp(App):

    def build(self):

        button = Button(text=‘Hello from Kivy’,

                        size_hint=(.5, .5),

                        pos_hint={‘center_x’: .5, ‘center_y’: .5})

        button.bind(on_press=self.on_press_button)

        return button

    def on_press_button(self, instance):

        print(‘Вы нажали на кнопку!’)

if __name__ == ‘__main__’:

    app = MainApp()

    app.run()

В данном коде вызывается button.bind(), а событие on_press ссылается на MainApp.on_press_button().

Этот метод неявно принимает экземпляр виджета, который является самим объектом кнопки. Сообщение будет выводиться на stdout всякий раз при нажатии пользователем на кнопку.

Использование языка дизайна KV

Kivy предоставляет язык дизайна KV, что можно использовать в приложениях Kivy. Язык KV позволяет отделить дизайн интерфейса от логики приложения. Он придерживается принципа разделения ответственности и является частью архитектурного паттерна Модель-Представление-Контроллер (Model-View-Controller).  Предыдущий пример можно обновить, используя язык KV:

from kivy.app import App

from kivy.uix.button import Button

class ButtonApp(App):

    def build(self):

        return Button()

    def on_press_button(self):

        print(‘Вы нажали на кнопку!’)

if __name__ == ‘__main__’:

    app = ButtonApp()

    app.run()

С первого взгляда данный код может показаться несколько странным, так как кнопка Button создается без указания атрибутов или привязывания к ним событий. Здесь Kivy автоматически ищет файл с таким же названием, что и у класса, только строчными буквами и без части App в названии класса.

В данном случае названием класса является ButtonApp, поэтому Kivy будет искать файл button.kv. Если такой файл существует, и он также форматирован должным образом, тогда Kivy использует его при загрузке UI. Попробуйте создать такой файл и добавить следующий код:

<Button>:

    text: ‘Press me’

    size_hint: (.5, .5)

    pos_hint: {‘center_x’: .5, ‘center_y’: .5}

    on_press: app.on_press_button()

Действия каждой строки:

  • Строка 1 соответствует вызову Button в коде Python. Kivy должен осмотреть инициализированный объект для определения кнопки;
  • Строка 2 устанавливает text кнопки;
  • Строка 3 устанавливает ширину и высоту при помощи size_hint;
  • Строка 4 устанавливает позицию кнопки через pos_hint;
  • Строка 5 устанавливает обработчик событий on_press. Для указания Kivy места обработчика событий используется app.on_press_button(). Здесь Kivy будет искать метод .on_press_button() в классе Application.

Вы можете установить все ваши виджеты и лейауты внутри одного или нескольких файлов языка KV. Язык KV также поддерживает импорт модулей Python в KV, создавая динамичные классы, и это далеко не предел. Ознакомиться с полным перечнем его возможностей можно в гиде Kivy по языку KV.

Теперь мы можем приступить к созданию настоящего рабочего приложения.

Создание приложения Kivy Python

Создание чего-то полезное несомненно является отличным способом выучить новый навык. Учитывая данное утверждение, давайте используем Kivy при создании калькулятора, который будет поддерживать следующие операции:

  • Сложение;
  • Вычитание;
  • Умножение;
  • Деление.

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

Kivy Calculator

Теперь, когда у нас есть в наличии целевой UI, может составить код:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.button import Button

from kivy.uix.textinput import TextInput

class MainApp(App):

    def build(self):

        self.operators = [«/», «*», «+», «-«]

        self.last_was_operator = None

        self.last_button = None

        main_layout = BoxLayout(orientation=«vertical»)

        self.solution = TextInput(

            multiline=False, readonly=True, halign=«right», font_size=55

        )

        main_layout.add_widget(self.solution)

        buttons = [

            [«7», «8», «9», «/»],

            [«4», «5», «6», «*»],

            [«1», «2», «3», «-«],

            [«.», «0», «C», «+»],

        ]

        for row in buttons:

            h_layout = BoxLayout()

            for label in row:

                button = Button(

                    text=label,

                    pos_hint={«center_x»: 0.5, «center_y»: 0.5},

                )

                button.bind(on_press=self.on_button_press)

                h_layout.add_widget(button)

            main_layout.add_widget(h_layout)

        equals_button = Button(

            text=«=», pos_hint={«center_x»: 0.5, «center_y»: 0.5}

        )

        equals_button.bind(on_press=self.on_solution)

        main_layout.add_widget(equals_button)

        return main_layout

Калькулятор работает следующим образом:

  • В строках с 8 по 10 создается список operators и несколько полезных значений, last_was_operator и last_button, которые будут использованы чуть позже.
  • В строках с 11 по 15 создается лейаут верхнего уровня main_layout, к нему также добавляется виджет только для чтения TextInput.
  • В строках с 16 по 21 создается вложенный список из списков, где есть большая часть кнопок для калькулятора.
  • В строке 22 начинается цикл for для кнопок. Для каждого вложенного списка делается следующее:
    1. В строке 23 создается BoxLayout с горизонтальной ориентацией.
    2. В строке 24 начинается еще один цикл for для элементов вложенного списка.
    3. В строках с 25 по 39 создаются кнопки для ряда и связываются обработчиком событий, после чего кнопки добавляются к горизонтальному BoxLayout из строки 23.
    4. В строке 31 этот лейаут добавляется к main_layout.
  • В строках с 33 по 37 создается кнопка равно (=) и привязывается к обработчику событий, после чего она добавляется к main_layout.

Далее создается обработчик событий .on_button_press(). Код будет выглядеть следующим образом:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

def on_button_press(self, instance):

    current = self.solution.text

    button_text = instance.text

    if button_text == «C»:

        # Очистка виджета с решением

        self.solution.text = «»

    else:

        if current and (

            self.last_was_operator and button_text in self.operators):

            # Не добавляйте два оператора подряд, рядом друг с другом

            return

        elif current == «» and button_text in self.operators:

            # Первый символ не может быть оператором

            return

        else:

            new_text = current + button_text

            self.solution.text = new_text

    self.last_button = button_text

    self.last_was_operator = self.last_button in self.operators

Почти все виджеты приложения вызывают .on_button_press(). Это работает следующим образом:

  • Строка 41 принимает аргумент instance, в результате чего можно узнать, какой виджет вызвал функцию.
  • Строки между 42 и 43 извлекают и хранят значения solution и text кнопки.
  • Строки c 45 по 47 проверяют, на какую кнопку нажали. Если пользователь нажимает с, тогда очищается solution. В противном случае используется утверждение else.
  • Строка 49 проверяет, было ли у решения предыдущее значение.
  • Строки с 50 по 52 проверяют, была ли последняя нажатая кнопка оператором. Если да, тогда solution обновляться не будет. Это необходимо для предотвращения создания двух операций в одном ряду. К примеру, 1 * / будет недействительным утверждением.
  • Строки с 53 по 55 проверяют, является ли первый символ оператором. Если да, тогда solution обновляться не будет, так как первое значение не может быть значением оператора.
  • Строки с 56 по 58 переходят к условию else. Если никакое из предыдущих значений не найдено, тогда обновляется solution.
  • Строка 59 устанавливает last_button к метке последней нажатой кнопки.
  • Строка 60 устанавливает last_was_operator к значению True или False в зависимости от того, был символ оператором или нет.

Последней частью кода будет .on_solution():

def on_solution(self, instance):

    text = self.solution.text

    if text:

        solution = str(eval(self.solution.text))

        self.solution.text = solution

Здесь берется текущий текст из solution и используется встроенный в Python eval() для исполнения. Если пользователь создал формулу вроде 1+2, тогда eval() запустит код и вернет результат. В конце результат устанавливается как новое значение виджета solution.

На заметку: порой eval() бывает опасным, так как он может запустить произвольный код. Многие разработчики избегают его использование именно по этой причине. Тем не менее, ввиду задействования только целых чисел, операторов и точки в качестве вводных данных для eval(), в данном контексте его можно использовать безопасно.

При запуске данного кода на рабочем столе компьютера приложение будет выглядеть следующим образом:

KV Calculator

Полный текст кода примера калькулятора представлен ниже:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.button import Button

from kivy.uix.textinput import TextInput

class MainApp(App):

    def build(self):

        self.operators = [«/», «*», «+», «-«]

        self.last_was_operator = None

        self.last_button = None

        main_layout = BoxLayout(orientation=«vertical»)

        self.solution = TextInput(

            multiline=False, readonly=True, halign=«right», font_size=55

        )

        main_layout.add_widget(self.solution)

        buttons = [

            [«7», «8», «9», «/»],

            [«4», «5», «6», «*»],

            [«1», «2», «3», «-«],

            [«.», «0», «C», «+»],

        ]

        for row in buttons:

            h_layout = BoxLayout()

            for label in row:

                button = Button(

                    text=label,

                    pos_hint={«center_x»: 0.5, «center_y»: 0.5},

                )

                button.bind(on_press=self.on_button_press)

                h_layout.add_widget(button)

            main_layout.add_widget(h_layout)

        equals_button = Button(

            text=«=», pos_hint={«center_x»: 0.5, «center_y»: 0.5}

        )

        equals_button.bind(on_press=self.on_solution)

        main_layout.add_widget(equals_button)

        return main_layout

    def on_button_press(self, instance):

        current = self.solution.text

        button_text = instance.text

        if button_text == «C»:

            # Очистка виджета с решением

            self.solution.text = «»

        else:

            if current and (

                self.last_was_operator and button_text in self.operators):

                # Не добавляйте два оператора подряд, рядом друг с другом

                return

            elif current == «» and button_text in self.operators:

                # Первый символ не может быть оператором

                return

            else:

                new_text = current + button_text

                self.solution.text = new_text

        self.last_button = button_text

        self.last_was_operator = self.last_button in self.operators

    def on_solution(self, instance):

        text = self.solution.text

        if text:

            solution = str(eval(self.solution.text))

            self.solution.text = solution

if __name__ == «__main__»:

    app = MainApp()

    app.run()

Пришло время разместить приложение в Google Play или в AppStore!

По завершении составления кода вы можете поделиться своим приложением с другими. Хорошим способом сделать это может стать превращение вашего кода в приложения для смартфона на Android. Для этого вначале нужно установить пакет buildozer через pip:

Затем создается новая папка, после чего нужно перейти в нее через терминал. Затем выполняется следующая команда:

После этого создается файл buildozer.spec, который будет использован для конфигурации сборки. К примеру, первые две строчки файла спецификации можно редактировать следующим образом:

[app]

# (str) Название вашего приложения

title = KvCalc

# (str) Название упаковки

package.name = kvcalc

# (str) Домен упаковки (нужен для упаковки android/ios)

package.domain = org.kvcalc

Не бойтесь посмотреть оставшуюся часть файла для выяснения того, что еще можно поменять.

На данный момент приложение почти готово к сборке, однако для начала нужно установить зависимости для buildozer.  После их установки скопируйте ваше приложение калькулятора в новую папку и переименуйте его в main.py. Этого требует buildozer. Если файл будет назван неверно, тогда процесс сборки завершится неудачей.

Теперь можно запустить следующую команду:

$ buildozer v android debug

Этап сборки займет время! На моем компьютере на это ушло около 15-20 минут. Здесь все зависит от вашего железа, так что времени может потребоваться еще больше. Расслабьтесь, налейте чашечку кофе или прогуляйтесь. Buildozer скачает те элементы Android SDK, которые нужны для процесса сборки. Если все идет по плану, тогда в папке bin появится файл под названием, напоминающим что-то вроде kvcalc-0.1-debug.apk.

Далее требуется связать телефон Android с компьютером и перенести туда файл apk. Затем откройте менеджер файлов телефона и кликните на файл apk. Android должен спросить, хотите ли вы установить приложение. Есть вероятность появления предупреждения, ведь приложение было скачано не из Google Play. Тем не менее, вы по-прежнему сможете установить его.

Вот как выглядит калькулятор, запущенный на Samsung S9:

KV Calc Android

У buildozer также есть несколько других команд, которые вы можете использовать. Изучите документацию, чтобы подробнее узнать об этом.

При необходимости добиться более детального управления упаковку можно осуществить через python-for-android. Здесь это обсуждаться не будет, но если интересно, ознакомьтесь, как еще можно быстро начать проект.

Создание приложений для iPhone (iOS) на Python

Инструкция для сборки приложения для iOS будет немного сложнее, нежели для Android. Для получения последней информации всегда проверяйте обновления официальной документации Kivy.

Вам нужен будет компьютер с операционной системой OS X: MacBook или iMac. На Linux или Windows вы не сможете создать приложения для Apple.

Перед упаковкой приложения для iOS на Mac необходимо выполнить следующие команды:

$ brew install autoconf automake libtool pkgconfig

$ brew link libtool

$ sudo easy_install pip

$ sudo pip install Cython==0.29.10

После успешной установки нужно скомпилировать при использования следующих команд:

$ git clone git://github.com/kivy/kivyios

$ cd kivyios

$ ./toolchain.py build python3 kivy

Если вы получаете ошибку, где говорится, что iphonesimulator не найден, тогда поищите способ решение проблемы на StackOverflow, после чего попробуйте запустить команды вновь.

Если вы получаете ошибки SSL, тогда скорее всего у вас не установлен OpenSSL от Python. Следующая команда должна это исправить:

$ cd /Applications/Python 3.7/

$ ./Install Certificates.command

Теперь вернитесь назад и запустите команду toolchain опять.

После успешного выполнения всех указанных выше команд можете создать проект Xcode при помощи использования скрипта toolchain. Перед созданием проекта Xcode переименуйте ваше главное приложение в main.py, это важно. Выполните следующую команду.

./toolchain.py create <title> <app_directory>

Здесь должна быть папка под названием title, внутри которой будет проект Xcode. Теперь можно открыть проект Xcode и работать над ним отсюда. Обратите внимание, что если вы хотите разместить свое приложение на AppStore, вам понадобится создать аккаунт разработчика на developer.apple.com и заплатить годовой взнос.

Создание exe приложений для Windows на Python используя Kivy

Упаковать приложение Kivy для Windows можно при помощи PyInstaller. Если ранее вы никогда не работали с ним, тогда изучите тему использования PyInstaller для упаковки кода Python в исполняемый файл.

Для установки PyInstaller можно использовать pip:

$ pip install pyinstaller

Следующая команда упакует ваше приложение:

Команда создаст исполняемый файл Windows, а вместе с ним еще несколько других файлов. Аргумент -w говорит PyInstaller, что приложение открывается в оконном режиме и не является приложение для командной строки. Если вы хотите, чтобы PyInstaller создал только один исполняемый файл, тогда можете передать в дополнение к -w аргумент --onefile.

Создание приложений для macOS на Python используя Kivy

Как и в случае с Windows, для создания исполняемого файла Mac можно также использовать PyInstaller. Единственным условием является запуск следующей команды на Mac:

$ pyinstaller main.py w onefile

Результатом станет один исполняемый файл в папке dist. Название исполняемого файла будет таким же, как и название файла Python, что был передан PyInstaller.

Если вы хотите уменьшить размер исполняемого файла или использовать в приложении GStreamer, тогда для получения дополнительной информации изучите тему упаковки для macOS.

Заключение

Kivy является действительно интересным фреймворком GUI, что можно использовать для создания пользовательских интерфейсов и мобильных приложений для Android и iOS. Внешне приложения Kivy будут отличаться от нативных приложений выбранной платформы. В том случае, если вы хотите выделяться на фоне конкурентов, это может быть выгодным преимуществом.

В данном руководстве были рассмотрены основы Kivy, среди которых стоит выделить добавление виджетов, привязку событий, планировку виджетов и лейауты, а также использование языка KV. В результате мы получили рабочее приложение Kivy и рассмотрели способы его переноса на другие платформы, в том числе мобильные.

В Kivy есть множество виджетов и концептов, которые не были рассмотрены в статьи. Для дальнейшего изучения темы можете изучить официальный сайт Kivy, где размещены разнообразные руководства, примеры приложений и многое другое.

Рекомендации

Для дальнейшего изучения Kivy ознакомьтесь со следующими ресурсами:

  • Гид программирования на Kivy 
  • Документация по упаковке приложений Kivy
  • Сборка приложений GUI через Python

Чтобы посмотреть, как создать приложение с графическим интерфейсом при использовании другого GUI фреймфорка Python, можете ознакомиться со статьями о wxPython.

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

E-mail: vasile.buldumac@ati.utm.md

Образование
Universitatea Tehnică a Moldovei (utm.md)

  • 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
  • 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

Test Environment

Feodra 31 with latest updates installed

What is Kivy

Kivy is a Python framework for developing Multitouch GUI Applications for cross platform devices. Kivy provides its own kivy language which help in separating the presentation from the business logic.

What is Buildozer

Buildozer is an automation tool which helps in packaging the mobile applications. Its mostly takes care all the dependencies required for building the package like python-for-android, Android SDK, NDK etc. Currently buildozer supports packaging for Android and iOS devices. Buildozer prepares a buildozer.spec file for your respective applications which describes about the application requirements and settings. These are used to create package for Android and iOS devices.

In this article we will look at how we can package a Python Kivy application into .apk format for Android device using builddozer. Here we are working on this build and deploy process using Fedora 31 Linux OS.

What is Android SDK and NDK

Android SDK (ie. software development kit) is a set of development tools used to develop applications for Android platform. Android NDK (i.e native development kit) is a set of tools that allows use of C and C++ code with Android. It provides platform specific libraries to manage native activites.

In this article we will look at how we can package a Python Kivy application into .apk format for Android device using builddozer. Here we are working on this build and deploy process using Fedora 31 Linux OS.

Given the brief description about some of the terminologies, lets get started with the building an android package from python kivy application.

Procedure –

Step1: Clone the buildozer git repository

$ git clone https://github.com/kivy/buildozer.git

Once the git repository is clone it will download the respective files related to the tool as shown below Downloaded files.

$ ls -ltr buildozer
total 144
-rw-rw-r-- 1 admin admin   8017 May 30 17:32 README.md
-rw-rw-r-- 1 admin admin     93 May 30 17:32 MANIFEST.in
-rw-rw-r-- 1 admin admin   1081 May 30 17:32 LICENSE
-rw-rw-r-- 1 admin admin   2149 May 30 17:32 Dockerfile
-rw-rw-r-- 1 admin admin 105372 May 30 17:32 CHANGELOG.md
drwxrwxr-x 6 admin admin   4096 May 30 17:32 buildozer
drwxrwxr-x 3 admin admin   4096 May 30 17:32 docs
-rw-rw-r-- 1 admin admin    921 May 30 17:32 tox.ini
drwxrwxr-x 4 admin admin   4096 May 30 17:32 tests
-rw-rw-r-- 1 admin admin   2551 May 30 17:32 setup.py

Step2: Install the buildozer tool using the setup.py

This step is going to install a lot of packages into the python libraries path

$ sudo python setup.py install

Step3: Navigate to your kivy applicaiton project directory and initialize the project

In this article i am using a simple Kivy custom ball bounce application. The source code for the same is available at the following git repository – https://github.com/novicejava1/python/tree/master/kivy

Kivy project directory

$ ls -ltr
total 28
-rw-rw-r-- 1 admin admin   898 May 16 02:15 pong.kv
-rwxr-xr-x 1 admin admin  1905 May 22 09:25 main.py

Now, lets initialize the application to be built by executing the below.

Initialize project

$ buildozer init
File buildozer.spec created, ready to customize!
$ ls -ltr
total 24
-rw-rw-r-- 1 admin admin   898 May 16 02:15 pong.kv
-rwxr-xr-x 1 admin admin  1905 May 22 09:25 main.py
-rw-rw-r-- 1 admin admin 10489 May 30 17:37 buildozer.spec

As you could see from the above folder structure, after running the init command it has created a buildozer.spec file which can be further customized as per our requirement. As our focus in this article is to build and deploy the application to android, we will the spec file with the default settings.

Step4: Enable USB debugging and install via USB

As we are going to build and deploy the Kivy application to the attached Android device. Lets attach the Android device to the Fedora machine and enable USB debugging. Also we need to enable allow for installing application using USB option in the screenshot shown below from an Android device.

Step5: Dependencies to be taken cared 

Buildozer will try to take care of a lot of dependencies but there are chances that your build might fail due to some dependencies which could not be taken cared but it will highlight in the STDOUT output indicating where and why it got failed.

Let me highlight a few dependencies that had to be taken cared manually for the below build process to succeed.

Install dependencies

$ sudo dnf install Python3-Cython java-1.8.0-openjdk-devel patch dh-autoreconf zlib-devel libffi-devel openssl-devel

Enable pypi.python.org as trusted host and upgrade pip if required to the latest available version.

$ pip install --trusted-host pypi.python.org pytest-xdist
$ pip install --trusted-host pypi.python.org --upgrade pip

Step6: Run the build and deploy from the application directory

Build project

$ buildozer android debug deploy run

This basically means we are launching the buildozer tool to start android build in debug mode and deploy the application to the device and run it. Here its going to download and install the required packages and softwares (i.e SDK, NDK) to complete the build process.

If everyting goes fine and all the dependencies are taken cared. You will be able to see your Android package build in bin directory and also pushed into your device and started.

Here is the sample sinppet of the output showing a successful build.

Successfull Installation log snippet

...
# Android packaging done!
# APK myapp-0.1-armeabi-v7a-debug.apk available in the bin directory
# Run '/home/admin/.buildozer/android/platform/android-sdk/platform-tools/adb devices'
# Cwd None
List of devices attached
5780e62d device

# Deploy on 5780e62d
# Run '/home/admin/.buildozer/android/platform/android-sdk/platform-tools/adb install -r 
"/home/admin/stack/develop/kivy/brick/bin/myapp-0.1-armeabi-v7a-debug.apk"'
# Cwd /home/admin/.buildozer/android/platform
Performing Push Install
/home/admin/stack/develop/kivy/brick/bin/myapp-0.1-armeabi-v7a-debug.apk: 1 file pushed, 
0 skipped. 0.8 MB/s (28395173 bytes in 33.751s)
 pkg: /data/local/tmp/myapp-0.1-armeabi-v7a-debug.apk
Success
# Application pushed.
# Run on 5780e62d
...
Starting: Intent { act=org.kivy.android.PythonActivity 
cmp=org.test.myapp/org.kivy.android.PythonActivity }
# Application started.

Hope you enjoyed this article. Thank you for reading..

  • Перейти на CTF площадку Игры Кодебай

    Выполняйте задания по кибербезопасности в формате CTF и получайте бесценный опыт. Ознакомиться с подробным описанием можно тут.

  • B правой части каждого сообщения есть стрелки и . Не стесняйтесь оценивать ответы. Чтобы автору вопроса закрыть свой тикет, надо выбрать лучший ответ. Просто нажмите значок в правой части сообщения.

  • #1

Здрасте, меня интересует, можно ли скомпилировать код на питоне под Андроид, но исключительно на Windows, без Ubuntu, и без Linux? И так же, без виртуальной машины? Мне без разницы с помощью какого инструмента мне писать код( я про kivy, и т.п. ), для меня главное, что бы я мог получить apk-файл без виртуальной машины на Windows.
Если это не возможно, то прошу также предлогать и конструкторы, в которые можно вставить код, и скомпилировать под Android…
Прошу предлагать

ЛЮБЫЕ

варианты, спасибо

Pernat1y


  • #2

Откуда такая нелюбовь к линуксу?

Ссылка скрыта от гостей

Там и для Windows есть мануал (не проверял).

f22

f22

Codeby Team


  • #3

Здрасте, меня интересует, можно ли скомпилировать код на питоне под Андроид, но исключительно на Windows, без Ubuntu, и без Linux? И так же, без виртуальной машины? Мне без разницы с помощью какого инструмента мне писать код( я про kivy, и т.п. ), для меня главное, что бы я мог получить apk-файл без виртуальной машины на Windows.
Если это не возможно, то прошу также предлогать и конструкторы, в которые можно вставить код, и скомпилировать под Android…
Прошу предлагать

ЛЮБЫЕ

варианты, спасибо

Ну первая же ссылка в гугле, друзья…
kivy/python-for-android

  • #4

Установка SDK для работы python for Android:

Пользователи Windows должны создать виртуальную машину с установленной ОС GNU Linux, а затем вы можете следовать описанным инструкциям на своей виртуальной машине.

но исключительно на Windows, без Ubuntu, и без Linux? И так же, без виртуальной машины?

Откуда я это взял? —

Ссылка скрыта от гостей

Откуда такая нелюбовь к линуксу?

Я не не люблю Линукс, просто я не имею возможно на нём работать, т.к. у меня есть только слабый ноутбук, и на нём стоит Windows, который не тянет виртуальную машину.
Buildozer под windows не работает

  • IMG_20201005_233248.jpg

    IMG_20201005_233248.jpg

    173,1 КБ

    · Просмотры: 203

Последнее редактирование: 06.10.2020

  • #5

Buildozer под windows не работает

На Windows не работает, только Linux или Linux

Оригинальный текст воспроизводится в:https://blog.csdn.net/Rong_Toa/article/details/79810423

Живой URL: На этом сайте есть подробный процесс установки, я просто носильщик.

Библиотека Python Kivy-Open source для быстрой разработки приложений, использующая инновационные пользовательские интерфейсы, такие как приложения мультитач.

Моя версия на Python:

D:test>python --version

Python 3.6.4

Шаги по установке кивы:

1. Убедитесь, что у вас установлена ​​последняя версия pip и wheel

python -m pip install --upgrade pip wheel setuptools

2. Установочные зависимости

python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew

python -m pip install kivy.deps.gstreamer

Если вы столкнулись с ошибкой памяти, добавьте

–no-cache-dir.

Если установленная версия Python больше 3.5, вместо glew вы можете использовать следующее:

python -m pip install kivy.deps.angle

3. Установить кивы

python -m pip install kivy

4. Установите кивый пример:

python -m pip install kivy_examples

Примеры моей установки:

C:UsersToaAppDataLocalProgramsPythonPython36sharekivy-examples>

Поэтому я запускаю программу main.py следующим образом;

python C:UsersToaAppDataLocalProgramsPythonPython36sharekivy-examplesdemoshowcasemain.py

Появится следующее окно (это пример):

В процессе установки я могу ошибаться на определенном этапе, но я просто повторяю это снова и снова, просто отлично.

Ниже приведен небольшой пример игры, который поставляется с kivy. Исходя из приведенного выше пути установки, исходный код модифицированной программы:

C:UsersToaAppDataLocalProgramsPythonPython36sharekivy-examplestutorialspong

Создайте main.py и pong.kv в одной папке, их содержимое выглядит следующим образом:

main.py

from kivy.app import App

from kivy.uix.widget import Widget

from kivy.properties import NumericProperty, ReferenceListProperty,

ObjectProperty

from kivy.vector import Vector

from kivy.clock import Clock





class PongPaddle(Widget):

score = NumericProperty(0)



def bounce_ball(self, ball):

if self.collide_widget(ball):

vx, vy = ball.velocity

offset = (ball.center_y - self.center_y) / (self.height / 2)

bounced = Vector(-1 * vx, vy)

vel = bounced * 1.1

ball.velocity = vel.x, vel.y + offset





class PongBall(Widget):

velocity_x = NumericProperty(0)

velocity_y = NumericProperty(0)

velocity = ReferenceListProperty(velocity_x, velocity_y)



def move(self):

self.pos = Vector(*self.velocity) + self.pos





class PongGame(Widget):

ball = ObjectProperty(None)

player1 = ObjectProperty(None)

player2 = ObjectProperty(None)



def serve_ball(self, vel=(4, 0)):

self.ball.center = self.center

self.ball.velocity = vel



def update(self, dt):

self.ball.move()



# bounce of paddles

self.player1.bounce_ball(self.ball)

self.player2.bounce_ball(self.ball)



# bounce ball off bottom or top

if (self.ball.y < self.y) or (self.ball.top > self.top):

self.ball.velocity_y *= -1



# went of to a side to score point?

if self.ball.x < self.x:

self.player2.score += 1

self.serve_ball(vel=(4, 0))

if self.ball.x > self.width:

self.player1.score += 1

self.serve_ball(vel=(-4, 0))



def on_touch_move(self, touch):

if touch.x < self.width / 3:

self.player1.center_y = touch.y

if touch.x > self.width - self.width / 3:

self.player2.center_y = touch.y





class PongApp(App):

def build(self):

game = PongGame()

game.serve_ball()

Clock.schedule_interval(game.update, 1.0 / 60.0)

return game





if __name__ == '__main__':

PongApp().run()

pong.kv

#:kivy 1.0.9



<PongBall>:

size: 50, 50

canvas:

Ellipse:

pos: self.pos

size: self.size



<PongPaddle>:

size: 25, 200

canvas:

Rectangle:

pos:self.pos

size:self.size



<PongGame>:

ball: pong_ball

player1: player_left

player2: player_right



canvas:

Rectangle:

pos: self.center_x-5, 0

size: 10, self.height



Label:

font_size: 70

center_x: root.width / 4

top: root.top - 50

text: str(root.player1.score)



Label:

font_size: 70

center_x: root.width * 3 / 4

top: root.top - 50

text: str(root.player2.score)



PongBall:

id: pong_ball

center: self.parent.center



PongPaddle:

id: player_left

x: root.x

center_y: root.center_y



PongPaddle:

id: player_right

x: root.width-self.width

center_y: root.center_y

Эффект:

——————— Эта статья взята из блога Koma_Wong’s CSDN. Для получения полного текстового адреса, пожалуйста, нажмите: https://blog.csdn.net/Rong_Toa/article/details/79810423 ? utm_source = copy

1. Brief:

  • Kivy is a framework which enable you to write cross platform app via python, and buildozer is a tool to package your code. Their documentation really sucks, this is why I wrote this to save you tons of time.
  • Make sure you have follow through How to run Kivy application via python3 under OS X? and make it work.
  • It’s tested for Kivy 1.9.1, Python 3.5.2 and Buildozer 0.32 on OS X Sierra 10.12.1
  • The first time packaging could be time consuming and throttling your laptop but that is OK, after downloading and compiling the libs, the future packaging could be fast

2. Tips which worth a seperate section

There are 3 sources of documentation for buildozer (Yes, 3 sources…):

  • [Recommend] Github
  • Readthedocs.io
  • Official Kivy site

According to my tested experiences, here are their use cases:

  • Github: If you want install and find the latest command
  • Readthedocs.io: find some specific meanings of parameters
  • Official Kivy site: find some introduction to buildozer

3. Install buildozer:

1
2
3
4
5

pip install buildozer


sudo pip install https://github.com/kivy/buildozer/archive/master.zip

4. Preparation

If this is your first installing and running buildozer, you need to follow this section carefully. Applies to Buildozer 0.32. For the future version, Section 6 may help.
If you have already installed some of them, you can skip it.

1
2
brew install autoconf automake
pip install colorama appdirs sh jinja2 six

5. Running

  • Initialise the configuration file, this will generate a new file in the current project folder named buildozer.spec
    • buildozer init
  • Package, deploy and running on android device (connect your device first)
    • buildozer android_new debug deploy run
  • If still fails, and even with log_level = 2, you couldn’t find the actural error, then try modifying the following line in buildozer.spec, works on Buildozer 0.32:
    • from requirements = kivy
    • to requirements = hostpython2, kivy

6. How to make it work (could be helpful even for future version)

The most tough part comes from the fact that buildozer may update the 3rd party libraries it use in furture version, so you need to figure out which libraries it needs.

First of all, open the file named buildozer.spec, find the line, log_level = 1, modify 1 to 2. So that you can see more detailed errors.

Then try to run the command “buildozer android_new debug deploy run” again, figure out which library it lack, you can only find them one by one.

There are currently 2 types of dependency errors:

  • Python package
    • ERROR: The appdirs Python module could not be found, please install it.
    • Solution: Install the python module by “pip install appdirs”
  • Native package
    • [WARNING]: Missing executable: autoconf is not installed
    • Solution: Install it by “brew install autoconf”
    • Some libraries may have the different name, e.g., “libtoolize is not installed”, but you should “brew install libtool”, hope it helps.

7. Miscellaneous

  • There will be a consistent error : “libtoolize is not installed” for buildozer 0.32 even you have installed it. Not a problem.
  • If it doesn’t running or even failed deploying, you can still copy the APK to your device and do a manual install. The APK is located in the bin/ under the current project, if you haven’t modified the according lines in buildozer.spec.
  • Using the following command if you wanna making a release package:
    • buildozer android_new release deploy run

Thanks for reading!

Follow me (albertgao) on twitter, if you want to hear more about my interesting ideas.

Понравилась статья? Поделить с друзьями:
  • Как установить bs4 python 3 windows
  • Как установить browser sync на windows 10
  • Как установить brawl stars на ноутбук windows 10
  • Как установить brawl stars на компьютер windows 10
  • Как установить bpwin на windows 10