- 3 Ways to Convert Python App into APK
- Building Android Apps With Python: Part -1
- Step by Step Guide to Build Android Apps using Python
- The Challenge
- Conclusion
- How to convert kivy/kivymd app to apk in Windows?
- Преобразование Python кода в исполняемые файлы Windows и Android
- реклама
- Подготовка
- В исполняемый файл Windows
- PyInstaller
- реклама
- реклама
- реклама
- В исполняемый файл Android
- Buildozer
3 Ways to Convert Python App into APK
In August 2020, I started a medium blog series called Building Android App in Python, where I explained the usage of Kivy and Kivymd. These libraries allow you to create cross-platform apps using Python. In that series, I described how android apps are configured in Python, it’s limitations, and various key elements that build up an android app. At the end of the series (3rd part), I mentioned that I will convert an app into APK and deploy it on a cloud platform. Here is the article about the same! Here I will discuss three ways in which this conversion can be performed. If you haven’t followed this series or you are unaware of this library then I highly recommend you that check out the first part of the series:
Building Android Apps With Python: Part -1
Step by Step Guide to Build Android Apps using Python
The Challenge
The Python apps build with Kivy cannot be directly transferred to android phones as these devices only support APK (Android Application Package) and we need to package them properly. This conversion process is only possible on a Linux system (for now) as the main components of this conversion, buildozer and python-for-android are currently supported on Linux based systems only. This adds up a challenge for budding developers who generally who use a windows machine for all the coding purpose. Other challenges include failed app conversions, app crashing on the start, or not able to connect to the internet. While some issues need extra attention from your side, I will provide you 3 different ways to successfully convert the Python app to APK.
Before moving ahead, let’s look at the flow of the conversion:
- Making sure that the app entry point file is named as main.py
- Installing the dependencies.
- Initialize the buildozer
- Edit the specs file
- Start the process
We will see 1,2 and 4 steps in detail in upcoming sections as they don’t require any explicit change but it is necessary to understand how to configure the buildozer specs properly.
The buildozer spec file is automatically generated while initializing the buildozer. The file contains the whole configuration and the app is built following this only. There are a few lines that need to be modified in that file before proceeding with the next steps (There are a total of 339 lines in the actual file):
The source code for both the apps (Python file, APK, and buildozer spec) can be found at this GitHub repository.
If you don’t want to use the APK generated into your devices then you simply host them online using a free service called Appetize.io which allows you to run android apps in browsers!
Conclusion
In this article, we saw how to configure the deployment file needed to convert the Python file into APK. Then we saw 3 different ways to do this conversion. A local machine is the best option but if don’t want to mess with your system then I would suggest Google Colab as it has great processing power. If you are looking for CI/CD type solution then GitHub actions will suit your requirements. With this, we come to an end of this article as well as the development series.
If you don’t want to miss such articles then make sure to follow me on medium to receive all the notifications. With that said, Sayonara!
You can connect with me here:
How to convert kivy/kivymd app to apk in Windows?
In this article, I will explain how we can convert a cross-platform application made using kivy/kivymd in python on Windows to an APK file without the need for a Linux machine. For this, I will use the online platform called Google Colab.
After logging into google colab, let’s prepare the environment for the conversion process. Do not forget to upload the project you are working on. Follow these commands step by step:
!sudo apt install -y git zip unzip openjdk-8-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev
!pip3 install --upgrade Cython==0.29.19 virtualenv
!sudo apt-get install -y \ python3-pip \ build-essential \ git \ python3 \ python3-dev \ ffmpeg \ libsdl2-dev \ libsdl2-image-dev \ libsdl2-mixer-dev \ libsdl2-ttf-dev \ libportmidi-dev \ libswscale-dev \ libavformat-dev \ libavcodec-dev \ zlib1g-dev
!sudo apt-get install -y \ python3-pip \ build-essential \ git \ python3 \ python3-dev \ ffmpeg \ libsdl2-dev \ libsdl2-image-dev \ libsdl2-mixer-dev \ libsdl2-ttf-dev \ libportmidi-dev \ libswscale-dev \ libavformat-dev \ libavcodec-dev \ zlib1g-dev
!sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev zlib1g-dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev libreadline-dev libncursesw5-dev libffi-dev uuid-dev libffi6
!sudo apt-get install libffi-dev
Now our environment is ready. We can start the conversion process. We will use buildozer for this. Run this command to start Buildozer:
This command will create a configuration file named buildozer.spec for us. Now it’s time to edit this file. At least you should change the;
title , package.name , package.domain . After changing these, my suggestion is to make some more changes to avoid some problems. Let’s look at source.dir first, if your main.py file is in the same directory, there is no need to change it, but if not, you should write the path here. Afterwards, if you have used separate files such as png, txt, csv in the program, you should add the extension to source.include_exts . Now let’s change the most important, requirements . If you only used kivy, python3,kivy==2.0.0rc4 will be enough to do it this way.If you also used kivymd then you should add this https://github.com/kivymd/KivyMD/archive/master.zip . If you have used other libraries, run the pip install command, and it will show the downloaded packages. You can add them without specifying the version. If you want to use icon you can uncomment icon.filename and you can edit the path. If you want your app to be fullscreen, you can make fullscreen 1. We will need to clone python-for-android to avoid problems such as not showing some symbols.
Then we need to edit it in spec file. p4a.source_dir = /path/to/your/python-for-android and p4a.branch = develop . Finally, if you need permissions on android you have to write them.We are done with spec file for now. Now we can start the conversion process by this command:
!buildozer -v android debug
When you first run this process, it may take up to 15-20 minutes depending on your internet speed. When the process is finished, your bin/*.apk file is ready and you can download it to the phone. If the application does not work, you can create a log file from the phone. For this, try to run the application after clicking on the settings / developer option / bug report. After waiting for a while, it will also show the process in the notification bar. You can now see the errors by sharing it to your computer. You can also check out my project that I made using kivymd. Mehmet Karagoz.
Преобразование Python кода в исполняемые файлы Windows и Android
Сегодня рассмотрим способы преобразования обычного Python файла в исполняемый файл.
реклама
Исполняемый файл- это тип файла, который может быть установлен или активирован на устройстве без необходимости в дополнительном ПО или библиотеках. Преобразовав свой Python-скрипт в исполняемый файл exe/apk, вы защитите свой код от модификаций или прочтения, а также упростите работу с вашей программой.
Подготовка
Для начала я создам python скрипт для проверки его работоспособности после преобразования в исполняемый файл. Этот код рисует черный круг с помощью модуля turtle.
В исполняемый файл Windows
PyInstaller
реклама
Это один из популярных инструментов для создания исполняемых файлов из файлов Python. Он позволяет упаковать все зависимости вашего проекта в один исполняемый файл. Чтобы использовать PyInstaller, установите его с помощью команды в командной строке:
Теперь переходим в директорию с .py файлом
реклама
Наиболее часто используемые аргументы PyInstaller:
- —onefile или -F: Создает одиночный исполняемый файл, включая все зависимости.
- —onedir или -D: Создает исполняемый файл в виде набора файлов и папок, сохраняя зависимости в отдельной папке.
- —name или -n: Устанавливает имя исполняемого файла.
- —icon или -i: Устанавливает лого для исполняемого файла (должна быть в формате .ico).
- —noconsole или -w: Исполняемый файл будет запускаться без консольного окна (для скрытия консольного вывода).
- —add-data или -a: Добавляет дополнительные файлы или папки, которые должны быть включены в исполняемый файл.
- —exclude-module или -x: Исключает указанный модуль из упаковки.
- —-hidden-import или -p: Указывает модули, которые должны быть включены в упаковку, но не обнаружены автоматически.
Теперь давайте скомпилируем наш код в exe файл. Для этого прописываем команду:
После завершения процесса появилось две папки: build и dist. Папка build используется программой для хранения временных данных, необходимых для сборки исполняемого файла. В папке dist хранится результат выполненной операции.
реклама
Собранный exe будет работать только в том случае, если находится в одной папке со всеми дополнительными файлами. Если его переместить или удалить доп. файлы, то он работать не будет.
Чтобы этого избежать можно использовать аргумент —onefile или -F
PyInstaller собрал все доп. файлы в архив и теперь в папке dist находится только нужный нам exe файл. Его можно переместить, а папки build и dist удалить.
В исполняемый файл Android
Buildozer
Это инструмент, ориентированный на Linux дистрибутивы для автоматизации сборки и упаковки приложений Python для платформы Android. Если у вас Windows, то необходимо использовать WSL или другие виртуальные машины. Ваш python файл должен быть совместимым с Android. Buidozer позволяет создавать apk из файлов Python с минимальными усилиями. Для установки прописываем это в командной строке linux:
sudo apt update && sudo apt upgrade && sudo apt install -y git zip unzip openjdk-17-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev && pip install buildozer
Теперь нужно создать .spec файл в котором будет храниться вся информация о приложении. Сначала перейдите в нужную директорию в командной строке.
Необходимо переименовать python файл в main.py. Открываем появивщийся buildozer.spec файл и переходим к настройке. Вот некоторые из наиболее часто используемых параметров, которые можно настроить:
- title — Название исполняемого файла.
- package.name — Имя пакета вашего исполняемого файла .
- package.domain — Доменное имя вашего приложения.
- source.dir — Путь к .py файлу.
- source.include_exts — Расширения файлов, которые должны быть включены в сборку.
- version — Версия исполняемого файла.
- requirements — Зависимости файла.
Прописываем эту команду для запуска сборки apk приложения:
В теории после сборки вы получите apk приложение. Но далеко не факт, что все получится без ошибок, с первого раза и получится вообще, ведь