How to Convert Python Code into an Android .apk [that doesn't crash!] | Kivymd, Buildozer Tutorial
You created an android app with python using Kivy or Kivymd, but it is still in .py format. How do you convert it into an installable .apk file that dose’nt crash for reasons you can’t figure out and do it as quickly as possible? Don’t worry, I got you covered. Read on.
I created a simple rock-paper-scissor app with python using the kivy and kivymd packages (you can check out it’s code here). And then I went on a frustating journey of trying to convert it into an installable android app that doesn’t crash as soon as you open it. I did it. In this post I’ll simplify the process for you and how to make sure your app dose not crash.
If you have no experience with Kivy or Kivymd, you can get started with this tutorial which teaches you to create a simple application in 9 minutes. But even though the apps that you create using python and kivymd look great and have material design. They are still in .py format. So how do you convert your python programs into installable .apk files?
This is where the buildozer and Google Collab comes in. Buildozer is a tool for packaging mobiles application easily. It automates the entire build process and downloads the prerequisites like python-for-android, Android SDK, NDK, etc. And Google Colaboratory, or “Colab” for short, allows you to write and execute any python code through the browser. It requires no setup to use and provides free access to computing resources including GPUs from Google.
Here is a simple step-by-step process for converting .py to .apk
STEP 1: Use these pre-written commands
Open this colab notebook, and you will find some prewritten commands. But don’t execute any command yet! Come back here after checking it out and wait for my commands 😉
Start executing the commands one by one until you reach this command !buildozer init , don’t execute it yet.

STEP 2: Import your .py file (and assets you used in your app)
After you import your .py file, rename it to main.py otherwise buildozer won’t recognize which python program it has to work on.

STEP 3: Run the “!buildozer” init command
When you run the !buildozer init command, it will generate a buildozer.spec file, open it by double clicking on it. You can edit the contents of this file to change the package name of your app, application name, app icon, splash screen image, your baby’s diapers and much more. Skim through it, see what changes you can make. But don’t execute the !buildozer -v android debug command yet!!

STEP 4: Making sure your app doesn’t crash!!
I did all this and then I executed the next command, which is !buildozer -v android debug . It generated a .apk file, I happily transfered it to my phone and installed. But when I opened it, it crash. I tried debugging my app, I ventured into the deep forests of Stackoverflow and Quora discussions of people who were having similar problems, but nothing worked. It took me two days to figure it out. Here’s how I solved the problem.
In the contents of buildozer.spec file there is a requirements section. And along with python3 , kivy and kivymd you have to add pillow to the requirements. Okay, now, What the hell is pillow !? I don’t remember using any package named “pillow” in my code. Well, turns out, pillow or PIL (Python Image Library) is python package which kivymd depends on for stuff. So this is how the requirements section of your buildozer.spec should look like (bottom image):

Don’t forget to save your buildozer.spec file after making changes.
STEP 5: Execute “!buildozer -v android debug”
Run the !buildozer -v android debug and wait. It will probably take more than 15 minutes. It will ask you for confirmation by entering “y” one or two times in the middle of the process, so look out for that.

Once it’s done all the processing, you’ll see a new folder has appeared on the left hand side by the name bin . Inside the bin you will find a .apk file, transfer it in your phone. Install it, test it, and hopefully it doesn’t crash. Your welcome.
7. Создание простого приложения Kivy
Приложение Kivy представляет из себя простой файл Python, который содержит код Kivy. Файл в нашем приложении будет называться «main.py». Причина в том, что при создании мобильного приложения должен быть файл с именем «main.py», который является входом приложения. В приложении, которое будет создано, будет три виджета Kivy, которые представляют собой ввод текста (text input), ярлык (label) и кнопку (button). Эти виджеты располагаются вертикально в окне при использовании коробочной схемы расположения инструментов. Они появятся в соответствии с тем порядком, в котором были добавлены в коробочную схему расположения. Другими словами, текстовый ввод будет первым виджетом, ярлык вторым и кнопка в самом низу. Когда кнопка нажата, текст, введенный в текстовый ввод, будет отображаться в ярлыке. Вот код Kivy этого приложения.
- import kivy.uix.boxlayout
- import kivy.uix.textinput
- import kivy.uix.label
- import kivy.uix.button
- class SimpleApp(kivy.app.App):
- def build(self):
- self.textInput = kivy.uix.textinput.TextInput()
- self.label = kivy.uix.label.Label(text=”Your Message.”)
- self.button = kivy.uix.button.Button(text=”Click Me.”)
- self.button.bind(on_press=self.displayMessage)
- self.boxLayout = kivy.uix.boxlayout.BoxLayout(orientation=”vertical”)
- self.boxLayout.add_widget(self.textInput)
- self.boxLayout.add_widget(self.label)
- self.boxLayout.add_widget(self.button)
- return self.boxLayout
- def displayMessage(self, btn):
- self.label.text = self.textInput.text
- if __name__ == “__main__”:
- simpleApp = SimpleApp()
- simpleApp.run()
Метод сборки — это то, что вызывается после запуска приложения, и, таким образом, оно используется для инициализации окна графического интерфейса Kivy. Три виджета создаются, а затем добавляются в макет окна. Метод bind привязывает метод обратного вызова к кнопке, чтобы выполняться при нажатии. Метод обратного вызова называется «displayMessage», который устанавливает текстом ярлыка текст, который введён в виджет текстового ввода . Приложения запускаются, только если файл main.py выполняется, гарантируя, что переменная «__name__» имеет значение «__main__» внутри оператора if. Делать так — хорошая практика. Для запуска приложения необходимо выполнить два шага. Сначала нужно активировать созданную ранее виртуальную среду Kivy с именем «mykivyinstall». Затем, запустить файл приложения «main.py» после перехода в папку, в которой он существует. Эти шаги показаны на рисунке 3.
На рисунке 4 показано окно с тремя созданными ранее виджетами. Обратите внимание, что высота окна делится поровну между тремя виджетама так, чтобы каждый виджет имел одну третью высоты окна. В этом примере сообщение «Hello Kivy» вводится в поле текстового ввод. Когда кнопка нажата, сообщение появится в ярлыке.
На этом этапе можно сказать, что приложение Kivy для рабочего стола успешно создано. Теперь мы можем начать упаковку этого проекта как приложения для Android.
8. Установка Buildozer
Инструмент Buildozer используется для упаковки проекта в качестве приложения для Android. После установки Buildozer автоматизирует процесс создания приложения для Android. Чтобы установить Buildozer, необходимо разрешить некоторые зависимости. В дополнение к установленным ранее Cython и git, есть некоторые другие библиотеки, которые должны быть установлены. На основе инструкций по установке взятых с http://buildozer.readthedocs.io/en/latest/installation.html, все зависимости можно скачать и установить с помощью следующих команд Ubuntu:
Buildozer может быть установлен с помощью этой команды. Эта команда гарантирует, что Buildozer будет установлен и обновлен.
После успешной установки Buildozer, давайте подготовим все необходимые файлы, чтобы успешно создать приложение для Android.
9. Создание файла buildozer.spec
Структура нашего проекта показана на рисунке 5. В папке с именем simpleapp размещен файл main.py, созданный ранее. Красота Kivy заключается в том, что этот же файл Python будет использоваться без изменений в приложении для Android. Но есть и другой файл с именем buildozer.spec, который необходим для создания приложения. Этот файл содержит информацию об Android-приложении, такую как название и версия. Как создать этот файл?
Файл buildozer.spec может быть сгенерирован с использованием инструмента Buildozer. Измените текущий рабочий каталог на каталог, в котором размещён файл приложения main.py, а затем выполните следующую команду:
Появится сообщение, указывающее, что был создан файл buildozer.spec, как показано на рисунке 6.
Далее перечислены некоторые из важных свойств приложения Android в файле buildozer.spec:
Например, заголовок (title) содержит заголовок приложения, исходный каталог (source directory) ссылается на каталог приложения, который устанавливается в этом случае как текущий каталог, версия приложения, версии Python и Kivy и прочее. Эти поля находятся внутри раздела [app] файла спецификации. Вы можете проверить спецификации приложения пройдя по этой ссылке http://buildozer.readthedocs.io/en/latest/specifications.html. Вы также можете отредактировать файл спецификации, чтобы изменить все поля, которые, по вашему мнению, требуют редактирования.
После подготовки всех файлов, необходимых для создания Android приложения, давайте наконец его создадим.
10. Создание приложения для Android с помощью Buildozer
Buildozer — хороший инструмент для создания приложения для Android, потому что он готовит среду в соответствии со всеми требованиям по созданию успешного приложения. Эти такие требования такие, как python-for-android, Android SDK, NDK и другие. Внутри каталога приложения его можно создать, используя следующую команду:
На рисунке 7 показан ответ при вводе команды. При создании приложения в первый раз, Buildozer должен загрузить все эти зависимости. Это займет некоторое время, пока они загрузятся и установятся. Потерпите.
После выполнения команды файл APK будет найден в следующем каталоге проекта: /simpleapp/.buildozer/android/platform/build/dists/simpleapp/bin. Файл APK можно перенести на устройство Android для его запуска. Также можно подключить устройство Android к машине, создать, развернуть и запустить приложение, используя одну команду, которая выглядит следующим образом:
На рисунке 8 показан запуск приложения для Android.
11. Используемые источники
Филипс, Дасти. Создание приложений в Kivy: Мобильный софт вместе с Python. “O’Reilly Media, Inc.”, 2014.
Запаковка проекта на Python для Android на самом смартфоне.

15:00 18-03-2012
Zaterehniy


Искал способ как запаковать свой собственый проект на python в apk файл, без помощи пк и вот наконец- таки такая возможность появилась. Об этом собственно и поговорим в данной статье.
вступление
1.что для этого необходимо. Подготавливаем проект.
2.Структура проекта. Пакуем наше приложение в apk файл.
Положение дел.
Благодаря стараниям отечественных и зарубежных разработчиков, на андроиде появилась возможность писать и собирать свои проекты на java прямо на смартфоне. Все это благодаря интегрированной среде разработки. В небольшой срок появились и начали активно развиваться несколько интересных проектов. Коротко расскажу о двух из них. Первым привлекшим мое внимание стал проект anjedi. В отличии от предыдущих попыток в данной програме был реализован удобный интерфейс, навигация по проекту и все необходимые инструменты для быстрой запаковки и тестирования собранного приложения. Позднее случайно наткнулся на aide в маркете. Данная ide отличалась двухоконным интерфейсом, автодополнением и лог ошибок. Так как в свободное время писал на питоне используя sl4a мне стало интересно возможно ли собрать собственный проект на смартфоне. Стал копать в этом направлении.
Как вообще собрать приложение написанное на python для андроида ? На официальном сайте описывается способ запаковки. Качаем шаблон программы, в Eclipse создаем новый проект из готового исходника открываем скрипт и заменяем его содержание своим кодом. Собираем проект, получаем готовый апк, переносим на смартфон любым способом, устанавливаем, запускаем и наблюдаем работу приложения(не зыбываем установить питон и компоненты).
В первых версиях anjedi не было возможности паковать сторонние проекты не созданные в самой программе. Такая поддержка появилась недавно. Тогда то я и начал от версии к версии тестировать на предмет сборки шаблона на питоне. Однако никак не получалось скомпилировать. На 40% сборки приложение зависает а через несколько минут закрывается с ошибкой. Пока что с помощью anjedi не палучается собрать, по крайней мере у меня. Отписал разрабу может в дельнейшем поправят.
В последней версии aide 1.0 beta9 так же появилась возможность собирать проекты со стандартной структурой. Первым делом попробовал собрать шаблон и вот все получилось.
что нам понадобится
-Для начала установим sl4a и python. Этот пункт я описывал в своей статье — питон на андроид. начало и стандартный шаблон Cсылка
-далее установим aide. Начиная с версии 1.0 beta9 поддерживается запаковка любых проектов для андроид.
-файловый менеджер. Я использую Total comander и root explorer.
-текстовый редактор. Встроенный в aide редактор тормозит при открытии больших файлов, поэтому предлогаю пользоваться сторонним. Посоветовать могу 920 text editor . Автоопределение кодировок, шустрый, удобный редактор с подсветкой синтаксиса.
когда все установлено можно приступать к работе. Для начала напишем к примеру простенькую программу на питон используя sl4a. После того скачаем шаблон для упаковки нашего будущего проекта. распакуем архив и папку с исходниками положим по пути sdcard/AppProjects/ .В этой папке по умолчанию располагаются проекты для работы с ними в нашей ide. Рассмотрим структуру проекта подробнее.
Программа содержит все необходимое для работы питон скрипта. Дополнительные библиотеки, описание элементов интерфейса в xml, java код . Остановлюсь на том что пригодится нам.
скриншот
Name already in use
python-for-android / doc / source / quickstart.rst
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Getting up and running on python-for-android (p4a) is a simple process and should only take you a couple of minutes. We’ll refer to Python for android as p4a in this documentation.
- requirements: For p4a, all your app’s dependencies must be specified via —requirements similar to the standard requirements.txt. (Unless you specify them via a setup.py/install_requires) All dependencies will be mapped to «recipes» if any exist, so that many common libraries will just work. See «recipe» below for details.
- distribution: A distribution is the final «build» of your compiled project + requirements, as an Android project assembled by p4a that can be turned directly into an APK. p4a can contain multiple distributions with different sets of requirements.
- build: A build refers to a compiled recipe or distribution.
- bootstrap: A bootstrap is the app backend that will start your application. The default for graphical applications is SDL2. You can also use e.g. the webview for web apps, or service_only/service_library for background services. Different bootstraps have different additional build options.
- recipe: A recipe is a file telling p4a how to install a requirement that isn’t by default fully Android compatible. This is often necessary for Cython or C/C++-using python extensions. p4a has recipes for many common libraries already included, and any dependency you specified will be automatically mapped to its recipe. If a dependency doesn’t work and has no recipe included in p4a, then it may need one to work.
p4a is now available on Pypi, so you can install it using pip:
You can also test the master branch from Github using:
p4a has several dependencies that must be installed:
- ant
- autoconf (for libffi and other recipes)
- automake
- ccache (optional)
- cmake (required for some native code recipes like jpeg’s recipe)
- cython (can be installed via pip)
- gcc
- git
- libncurses (including 32 bit)
- libtool (for libffi and recipes)
- libssl-dev (for TLS/SSL support on hostpython3 and recipe)
- openjdk-8
- patch
- python3
- unzip
- virtualenv (can be installed via pip)
- zlib (including 32 bit)
- zip
On recent versions of Ubuntu and its derivatives you may be able to install most of these with:
On Arch Linux you should be able to run the following to install most of the dependencies (note: this list may not be complete):
Installing Android SDK
python-for-android is often picky about the SDK/NDK versions. Pick the recommended ones from below to avoid problems.
Basic SDK install
You need to download and unpack the Android SDK and NDK to a directory (let’s say $HOME/Documents/):
For the Android SDK, you can download ‘just the command line tools’. When you have extracted these you’ll see only a directory named tools , and you will need to run extra commands to install the SDK packages needed.
For Android NDK, note that modern releases will only work on a 64-bit operating system. The minimal, and recommended, NDK version to use is r25b:
Platform and build tools
First, install an API platform to target. The recommended *target* API level is 27, you can replace it with a different number but keep in mind other API versions are less well-tested and older devices are still supported down to the recommended specified *minimum* API/NDK API level 21:
Second, install the build-tools. You can use $SDK_DIR/tools/bin/sdkmanager —list to see all the possibilities, but 28.0.2 is the latest version at the time of writing:
Configure p4a to use your SDK/NDK
Then, you can edit your
/.bashrc or other favorite shell to include new environment variables necessary for building on android:
You have the possibility to configure on any command the PATH to the SDK, NDK and Android API using:
- —sdk-dir PATH as an equivalent of $ANDROIDSDK
- —ndk-dir PATH as an equivalent of $ANDROIDNDK
- —android-api VERSION as an equivalent of $ANDROIDAPI
- —ndk-api VERSION as an equivalent of $NDKAPI
- —ndk-version VERSION as an equivalent of $ANDROIDNDKVER
Build a Kivy or SDL2 application
To build your application, you need to specify name, version, a package identifier, the bootstrap you want to use (sdl2 for kivy or sdl2 apps) and the requirements:
Note on —requirements : you must add all libraries/dependencies your app needs to run. Example: —requirements=python3,kivy,vispy . For an SDL2 app, kivy is not needed, but you need to add any wrappers you might use (e.g. pysdl2).
This p4a apk . command builds a distribution with python3, kivy, and everything else you specified in the requirements. It will be packaged using a SDL2 bootstrap, and produce an .apk file.
- Python 2 is no longer supported by python-for-android. The last release supporting Python 2 was v2019.10.06.
Build a WebView application
To build your application, you need to have a name, version, a package identifier, and explicitly use the webview bootstrap, as well as the requirements:
Please note as with kivy/SDL2, you need to specify all your additional requirements/dependencies.
You can also replace flask with another web framework.
Replace —port=5000 with the port on which your app will serve a website. The default for Flask is 5000.
Build a Service library archive
To build an android archive (.aar), containing an android service , you need a name, version, package identifier, explicitly use the service_library bootstrap, and declare service entry point (See :ref:`services <arbitrary_scripts_services>` for more options), as well as the requirements and arch(s):
You can then call the generated Java entrypoint(s) for your Python service(s) in other apk build frameworks.
Exporting the Android App Bundle (aab) for distributing it on Google Play
Starting from August 2021 for new apps and from November 2021 for updates to existings apps, Google Play Console will require the Android App Bundle instead of the long lived apk.
python-for-android handles by itself the needed work to accomplish the new requirements:
This p4a aab . command builds a distribution with python3, kivy, and everything else you specified in the requirements. It will be packaged using a SDL2 bootstrap, and produce an .aab file that contains binaries for both armeabi-v7a and arm64-v8a ABIs.
The Android App Bundle, is supposed to be used for distributing your app. If you need to test it locally, on your device, you can use bundletool <https://developer.android.com/studio/command-line/bundletool>
You can pass other command line arguments to control app behaviours such as orientation, wakelock and app permissions. See :ref:`bootstrap_build_options` .
If anything goes wrong and you want to clean the downloads and builds to retry everything, run:
If you just want to clean the builds to avoid redownloading dependencies, run:
If something goes wrong and you don’t know how to fix it, add the —debug option and post the output log to the kivy-users Google group or the kivy #support Discord channel.
You can see the list of the available recipes with:
If you are contributing to p4a and want to test a recipes again, you need to clean the build and rebuild your distribution:
You can write «private» recipes for your application, just create a p4a-recipes folder in your build directory, and place a recipe in it (edit the __init__.py ):
Every time you start a new project, python-for-android will internally create a new distribution (an Android build project including Python and your other dependencies compiled for Android), according to the requirements you added on the command line. You can force the reuse of an existing distribution by adding:
This will ensure your distribution will always be built in the same directory, and avoids using more disk space every time you adjust a requirement.
You can list the available distributions:
And clean all of them:
python-for-android checks in the current directory for a configuration file named .p4a . If found, it adds all the lines as options to the command line. For example, you can add the options you would always include such as:
Overriding recipes sources
You can override the source of any recipe using the $P4A_recipename_DIR environment variable. For instance, to test your own Kivy branch you might set:
The specified directory will be copied into python-for-android instead of downloading from the normal url specified in the recipe.