Python for Android: Start Building Kivy Cross-Platform Applications | by Ahmed Gad | Towards Data Science

This tutorial goes through steps required to create an Android application using Kivy cross-platform Python framework using Linux Ubuntu distribution. Before starting installing Kivy and getting it up and running, it is required to install its dependencies. Most of the time is used for preparing the Kivy environment by installing libraries required for its operation. In this tutorial, Kivy itself is to be installed in a virtual environment.
The platform used in this tutorial is Linux Ubuntu 18.04 with Python 3.6.5. Some differences will exist when running Kivy on other platforms. To be able to install libraries, navigate through directories of the OS, copy/delete/extract files, run Python scripts, the reader should have a basic understanding of Linux terminal commands and Python.
This tutorial has the following sections:
IntroductionInstalling Kivy DependenciesCreating Virtual Environment for Installing KivyInstalling CythonInstalling KivyImporting KivyCreating Simple Kivy ApplicationInstalling BuildozerCreating buildozer.spec FileBuilding Android Application using BuildozerReferences
Introduction
Installing Kivy Dependencies
Creating Virtual Environment for Installing Kivy
Installing Cython
Installing Kivy
Importing Kivy
Creating Simple Kivy Application
Installing Buildozer
Creating buildozer.spec File
Building Android Application using Buildozer
References
Kivy is used to create natural user interfaces with the advantages of abstraction and modularity. It decouples the developer from unnecessary and complex details and just gives simple APIs for doing complex tasks. As a result, you should determine what backend libraries that Kivy will use to do its tasks. We are going to use SDL (Simple DirectMedia Layer) the cross-platform library for low level access to graphics hardware via OpenGL. Besides SDL, other libraries such as GStreamer is used to handle audio and video. Because such libraries are written in C, Cython is required.
Based on the Kivy Linux installation instructions (https://kivy.org/docs/installation/installation-linux.html), here are the required libraries to be installed to get SDL2 and GStreamer. Note that you could choose which Python version to use in Kivy by using python and python-dev for Python 2 or using python3 and python3-dev for Python 3. Pip is installed below for later use in preparing the Kivy virtual environment.
ahmed-gad@ubuntu:~$ sudo apt install -y \python-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 \libgstreamer1.0 \gstreamer1.0-plugins-base \gstreamer1.0-plugins-good
After preparing the Kivy dependencies, we can start installing Kivy by creating its virtual environment. It is not required to use a virtual environment to run Kivy but it is recommended to separate Kivy from other already existing projects.
Before starting creating the virtual environment, we should make sure that tools required for creating it are already installed and updated. The following command ensures that the virtualenv and setuptools tools are already existing and updated.
ahmed-gad@ubuntu:~$ sudo pip install --upgrade pip virtualenv setuptools
virtualenv is used to create isolated Python environments. For more info about benefits of virtual environments, you can visit this page https://virtualenv.pypa.io/en/stable/. setuptools is used for packaging Python projects.
After that, we are ready to create the Kivy virtual environment. The following command creates an environment called mykivyinstall.
ahmed-gad@ubuntu:~$ virtualenv --no-site-packages mykivyinstall
The — no-site-packages argument is used to isolate the environment from the main Python installation. This is to work freely on that project without affecting any other project.
After issuing that command, it is expected to get a new folder in the current directory named according to the virtual environment name as in figure 1.
The previous command will use the default Python interpreter within the environment. It may be Python 2 and we are looking to work with Python 3. For such reason, we could explicitly specify which Python interpreter to use using the -p option as in the following command:
ahmed-gad@ubuntu:~$ virtualenv --no-site-packages -p /usr/bin/python3 mykivyinstall
After creating the virtual environment, we can activate it to start installing Kivy. It can be activated based on the following command.
ahmed-gad@ubuntu:~$ . mykivyinstall/bin/activate
The dot (.) in the previous command is a built-in command that executes the content of the file passed as an argument. It is a synonym for the command source. As a result, the previous command is identical to this command:
ahmed-gad@ubuntu:~$ source mykivyinstall/bin/activate
The command prompt should change after activating the virtual environment to be as follows:
(mykivyinstall) ahmed-gad@ubuntu:~$
Before installing Kivy, Cython is to be installed in such environment according to the following command:
(mykivyinstall) ahmed-gad@ubuntu:~$ pip install cython=0.25.2
Note that the version of Cython is dependent on the version of Kivy to be installed. In the current date, the latest Kivy version is 1.10.0 and it requires Cython 0.25.2 and this is why it is used in the above command. After that, we are ready for installing Kivy.
Kivy could be installed using pip according to the following command:
(mykivyinstall) ahmed-gad@ubuntu:~$ pip install kivy
After that command, it is expected to have Kivy downloaded and installed automatically. But please note that installation of Kivy is the hard part because there are many dependencies that are variant based on the machine, platform, and what libraries you already have and what are missing. The process is not straightforward and you should look for alternative ways to solve the installation errors. For example, Kivy could be installed by using a wheel file or by cloning its github project according to the following command:
(mykivyinstall) ahmed-gad@ubuntu:~$ pip install git+https://github.com/kivy/kivy.git@master
After reaching is stage, it is expected to have Kivy installed and working successfully on your machine. We can test that environment by importing Kivy as in figure 2. The virtual environment is activate, Python is activated, and Kivy got imported successfully.
After making sure Kivy is running well, we are ready to create our first Kivy application.
The Kivy application is just a simple Python file holding the Kivy code. The file in our application will be named “main.py”. The reason is that when building the mobile application, there must be a file named “main.py”, which is the entrance of the application. The application to be created will have three Kivy widgets which are text input, label, and button. These widgets are layed vertically in a window using box layout. They will appear according to the order of being added to the box layout. In other words, the text input will be the first widget, label second, and button at the bottom. When the button got clicked, the text entered in the text input will be displayed on the label. Here is the Kivy code of the application.
1.  import kivy.app
import kivy.uix.boxlayoutimport kivy.uix.textinputimport kivy.uix.labelimport kivy.uix.buttonclass 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.boxLayoutdef displayMessage(self, btn):self.label.text = self.textInput.textif __name__ == "__main__":simpleApp = SimpleApp()simpleApp.run()
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()
The build method is what is called after the app runs and thus it is used to initialize the Kivy GUI window. The three widgets are created then added to the box layout. The bind method attaches a callback method to the button to be executed when clicked. The callback method is named “displayMessage” that sets the label text to the text entered in the text input widget. The applications runs only if the main.py file is executed by ensuring that the “__name__” variable has a value “__main__” inside the if statement. It is good practice to do that. In order to run the application, there are two steps required. First one is to activate the Kivy virtual environment named “mykivyinstall” created previously. Second one is to run the application “main.py” file after navigating to the folder in which it exists. These steps are shown in figure 3.
Figure 4 shows the window with the three widgets created previously. Note that the window height is divided equally across its three widgets so that each widget has one third of the window height. In this example, “Hello Kivy” message is entered in the text input. When the button got clicked, the message will appear on the label.
Up to this point, a Kivy desktop application is created successfully. We can now start packaging this project as an Android app.
The Buildozer tool is used to package the project as an Android app. Once installed, Buildozer automates the process of building the Android app. In order to install Buildozer, there are some dependencies. In addition to Cython and git installed previously, there are some other libraries to be installed. Based on the installation instructions in http://buildozer.readthedocs.io/en/latest/installation.html, all dependencies can be downloaded and installed using the following Ubuntu commands:
ahmed-gad@ubuntu:~$ sudo dpkg --add-architecture i386ahmed-gad@ubuntu:~$ sudo get install build-essential ccache libncurses5:i386 libstdc++6:i386 libgtk2.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libidn11:i386 python2.7 python2.7-dev openjdk-8-jdk unzip zlib1g-dev zlib1g:i386
Buildozer can be installed using this command. This command ensures that Buildozer is installed and upgraded.
ahmed-gad@ubuntu:~$ sudo install –upgrade buildozer
After installing Buildozer successfully, let us prepare all required files in order to build the android application successfully.
Our project structure is as shown in figure 5. There is a folder named simpleapp in which the main.py file created previously is placed. The beauty of Kivy is that the same Python file will be used unchanged in the Android app. But there is also another file named buildozer.spec which is essential in order to build the app. This file holds information about the Android app such as title and version. How to create that file?
The buildozer.spec file can be generated using Buildozer tool. After making the current working directory to the directory in which the application main.py file is placed, issue the following command:
ahmed-gad@ubuntu:~/Desktop/simpleapp$ buildozer init
A message will appear indicating that the buildozer.spec file is created as in figure 6.
Some of the important properties of the Android app inside the buildozer.spec file are as follows:
[app]title = Simple Applicationpackage.name = simpleapppackage.domain = org.simpleappsource.dir = .source.include_exts = py,png,jpg,kv,atlasversion = 0.1requirements = kivyorientation = portraitosx.python_version = 3osx.kivy_version = 1.9.1fullscreen = 0
For example, title holds the title of the application, source directory referes to the directory of the application which is set in this case as the current directory, app version, Python and Kivy versions, and others. These fields are inside the [app] section of the specification file. You can check the app specifications in this link http://buildozer.readthedocs.io/en/latest/specifications.html. You can also edit the specification file to change whatever fields you see it is worth modification.
After preparing all files required to build the Android app, let us start building it.
Buildozer is a good tool for building the Android application because it prepares the environment by all requirements in order to build the app successfully. These requirements are such as python-for-android, Android SDK, NDK, and others. Inside the app directory, it can be build using the following command:
ahmed-gad@ubuntu:~/Desktop/simpleapp$ buildozer android release
Figure 7 shows the response when the command entered. When building the application for the first time, Buildozer have to download all of these dependencies. It will take time until they are downloaded and installed. Be patient.
After the command got executed, the APK file will be found at this location under project directory /simpleapp/.buildozer/android/platform/build/dists/simpleapp/bin. The APK file could be transferred to an Android device to run it. Also it is possible to connect an Android device to the machine, building, deploying, and running the app using a single command which is as follows:
ahmed-gad@ubuntu:~/Desktop/simpleapp$ buildozer android release deploy run
Figure 8 shows the run of the Android application.
Phillips, Dusty. Creating Apps in Kivy: Mobile with Python. “O’Reilly Media, Inc.”, 2014.
https://kivy.org/docs/installation/installation-linux.html
https://virtualenv.pypa.io/en/stable/
https://kivy.org/docs/guide/architecture.html
https://github.com/kivy/kivy/blob/master/kivy/
http://buildozer.readthedocs.io/en/latest/installation.html
https://buildozer.readthedocs.io/en/stable/quickstart.html
The original article is available at LinkedIn in this page: https://www.linkedin.com/pulse/python-android-start-building-kivy-cross-platform-applications-gad
For contacting the author: