- Saved searches
- Use saved searches to filter your results more quickly
- License
- kivy/python-for-android
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Create a package for Android¶
- Buildozer¶
- Packaging with python-for-android¶
- Packaging your application for the Kivy Launcher¶
- Installation of Examples¶
- Release on the market¶
- Targeting Android¶
- Kivy — Создание мобильных приложений на Python
- Принципы работы фреймворка Kivy Python
- Установка Kivy
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Turn your Python application into an Android APK
License
kivy/python-for-android
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
* Made p4a apk build command more general - readme * Fix twice spelled - readme * updated p4a build command
Git stats
Files
Failed to load latest commit information.
README.md
python-for-android is a packaging tool for Python apps on Android. You can create your own Python distribution including the modules and dependencies you want, and bundle it in an APK or AAB along with your own code.
- Different app backends including Kivy, PySDL2, and a WebView with Python webserver.
- Automatic support for most pure Python modules, and built in support for many others, including popular dependencies such as numpy and sqlalchemy.
- Multiple architecture targets, for APKs optimised on any given device.
- AAB: Android App Bundle support.
For documentation and support, see:
Follow the quickstart instructions to install and begin creating APKs and AABs.
Quick instructions: install python-for-android with:
pip install python-for-android
(for the develop branch: pip install git+https://github.com/kivy/python-for-android.git )
Test that the install works with:
To build any actual apps, set up the Android SDK and NDK as described in the quickstart. Use the SDK/NDK API level & NDK version as in the quickstart, other API levels may not work.
With everything installed, build an APK with SDL2 with e.g.:
p4a apk --private PATH_TO_YOUR_APP_CODE --package=org.example.myapp --name "My application" --version 0.1 --bootstrap=sdl2 --requirements=python3,kivy
If you need to deploy your app on Google Play, Android App Bundle (aab) is required since 1 August 2021:
For full instructions and parameter options, see the documentation.
If you need assistance, you can ask for help on our mailing list:
We love pull requests and discussing novel ideas. Check out the Kivy project contribution guide and feel free to improve python-for-android.
See our documentation for more information about the python-for-android development and release model, but don’t worry about the details. You just need to make a pull request, we’ll take care of the rest.
The following mailing list and IRC channel are used exclusively for discussions about developing the Kivy framework and its sister projects:
python-for-android is released under the terms of the MIT License. Please refer to the LICENSE file.
In 2015 these tools were rewritten to provide a new, easier-to-use and easier-to-extend interface. If you’d like to browse the old toolchain, its status is recorded for posterity at https://github.com/kivy/python-for-android/tree/old_toolchain.
In the last quarter of 2018 the python recipes were changed. The new recipe for python3 (3.7.1) had a new build system which was applied to the ancient python recipe, allowing us to bump the python2 version number to 2.7.15. This change unified the build process for both python recipes, and probably solved various issues detected over the years. These unified python recipes require a minimum target api level of 21, Android 5.0 — Lollipop. If you need to build targeting an api level below 21, you should use an older version of python-for-android (<=0.7.1).
On March of 2020 we dropped support for creating apps that use Python 2. The latest python-for-android release that supported building Python 2 was version 2019.10.6.
On August of 2021, we added support for Android App Bundle (aab). As a collateral, now We support multi-arch apk.
This project exists thanks to all the people who contribute. [Contribute].
Thank you to all our backers! 🙏 [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
About
Turn your Python application into an Android APK
Create a package for Android¶
You can create a package for android using the python-for-android project. This page explains how to download and use it directly on your own machine (see Packaging your application into APK or AAB ) or use the Buildozer tool to automate the entire process. You can also see Packaging your application for the Kivy Launcher to run kivy programs without compiling them.
For new users, we recommend using Buildozer as the easiest way to make a full APK or AAB. You can also run your Kivy app without a compilation step with the Kivy Launcher app.
Kivy applications can be released on an Android market such as the Play store, with a few extra steps to create a fully signed AAB (Android App Bundle).
The Kivy project includes tools for accessing Android APIs to accomplish vibration, sensor access, texting etc. These, along with information on debugging on the device, are documented at the main Android page .
Buildozer¶
Buildozer is a tool that automates the entire build process. It downloads and sets up all the prerequisites for python-for-android, including the android SDK and NDK, then builds an apk that can be automatically pushed to the device.
Buildozer currently works only in Linux and macOS (You can still use it on Windows via WSL), and can significantly simplify the apk build.
Please find the installation instructions here
Including the “Targeting Android” section.
Afterwards, navigate to your project directory and run:
This creates a buildozer.spec file controlling your build configuration. You should edit it appropriately with your app name etc. You can set variables to control most or all of the parameters passed to python-for-android.
Finally, plug in your android device and run:
buildozer android debug deploy run
to build, push and automatically run the apk on your device.
Buildozer has many available options and tools to help you, the steps above are just the simplest way to build and run your APK. The full documentation is available here. You can also check the Buildozer README at https://github.com/kivy/buildozer.
Packaging with python-for-android¶
You can also package directly with python-for-android, which can give you more control but requires you to manually download parts of the Android toolchain.
Packaging your application for the Kivy Launcher¶
The Kivy launcher is an Android application that runs any Kivy examples stored on your SD Card. To install the Kivy launcher, you must:
- Go on Google Play Store and search for Kivy Launcher from kivy org
- Click on Install
- Select your phone… And you’re done!
If you don’t have access to the Google Play Store on your phone/tablet, you can download and install the APK manually from https://github.com/kivy/kivy-launcher/releases
Once the Kivy launcher is installed, you can put your Kivy applications in the Kivy directory in your external storage directory (often available at /sdcard even in devices where this memory is internal), e.g.
/sdcard/kivy/yourapplication>
should be a directory containing:
# Your main application file: main.py # Some info Kivy requires about your app on android: android.txt
The file android.txt must contain:
title=Application Title> author=Your Name> orientation=portrait|landscape>
These options are just a very basic configuration. If you create your own APK using the tools above, you can choose many other settings.
Installation of Examples¶
Kivy comes with many examples, and these can be a great place to start trying the Kivy launcher. You can run them as below:
#. Download the `Kivy demos for Android `_ #. Unzip the contents and go to the folder `kivydemo-for-android` #. Copy all the the subfolders here to
Release on the market¶
If you have built your own APK with Buildozer or with python-for-android, you can create a release version that may be released on the Play store or other Android markets.
To do this, you must run Buildozer with the release parameter (e.g. buildozer android release ), or if using python-for-android use the —release option to build.py. This creates a release AAB in the bin directory, which you must properly sign and zipalign. The procedure for doing this is described in the Android documentation at https://developer.android.com/studio/publish/app-signing.html#signing-manually — all the necessary tools come with the Android SDK.
Targeting Android¶
Kivy is designed to operate identically across platforms and as a result, makes some clear design decisions. It includes its own set of widgets and by default, builds an APK or AAB with all the required core dependencies and libraries.
It is possible to target specific Android features, both directly and in a (somewhat) cross-platform way. See the Using Android APIs section of the Kivy on Android documentation for more details.
Kivy — Создание мобильных приложений на Python
В наши дни каждый разработчик может столкнуться с необходимостью работы над мобильным или веб-приложением на Python. В Python нет встроенных инструментов для мобильных устройств, тем не менее существуют пакеты, которые можно использовать для создания мобильных приложений. Это Kivy, PyQt и даже библиотека Toga от Beeware.
Библиотеки являются основными элементами мобильного мира 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 создается следующим образом: