Technical background

Although apple now occupies a large part of the market , But from the sales figures , Android still dominates the population . Here we introduce a method of using python Of kivy+buildozer For Android APP Development of a simple tutorial , From the whole process , The workload of environment deployment is very large , Maybe this is from 0 To 1 The difficulty of ? At the end of the article, we will conclude that , Which one is the easiest , I hope it can help you .

kivy Installation

The official recommendation is to use a virtual environment for installation and deployment , About the operation of virtual environment , The one I wrote before Blog There is a little more detail in , Here we give the operation steps first . Let's assume that we've used pip Installed virtualenv, So let's build a kivy Virtual environment for :

[dechin@dechin-manjaro kivy]$ virtualenv kivy_venv
created virtual environment CPython3.8.5.final.0-64 in 123ms
creator CPython3Posix(dest=/home/dechin/projects/2021-python/kivy/kivy_venv, clear=False, no_vcs_ignore=False, global=False)
seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/dechin/.local/share/virtualenv)
added seed packages: pip==21.0.1, setuptools==54.1.2, wheel==0.36.2
activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

After the construction is completed, a folder will be generated in the current directory :

[dechin@dechin-manjaro kivy]$ ll
Total usage 4
drwxr-xr-x 4 dechin dechin 4096 4 month 3 22:00 kivy_venv

We can use source ./kivy_env/bin/activate To activate the virtual environment in a different way , After activation, execute system operation instruction every time , A virtual environment ID will be displayed at the front of the command , For example, here we use pip To install kivy:

(kivy_venv)[dechin@dechin-manjaro kivy]$ python3 -m pip install kivy -i https://mirrors.cloud.tencent.com/pypi/simple
Looking in indexes: https://mirrors.cloud.tencent.com/pypi/simple
Collecting kivy
Downloading https://mirrors.cloud.tencent.com/pypi/packages/fd/4c/eb36890982bb11daaea68df62486ce36bde26cc9bec6a57e02c0e2aa8982/Kivy-2.0.0-cp38-cp38-manylinux2010_x86_64.whl (22.2 MB)
|████████████████████████████████| 22.2 MB 7.7 MB/s
Collecting pygments
Downloading https://mirrors.cloud.tencent.com/pypi/packages/3a/80/a52c0a7c5939737c6dca75a831e89658ecb6f590fb7752ac777d221937b9/Pygments-2.8.1-py3-none-any.whl (983 kB)
|████████████████████████████████| 983 kB 688 kB/s
Collecting Kivy-Garden>=0.1.4
Downloading https://mirrors.cloud.tencent.com/pypi/packages/7d/68/decaee596ff8168a39432eb3949fc7c0be952ebb9467806823bffc165d48/kivy-garden-0.1.4.tar.gz (6.8 kB)
Collecting docutils
Downloading https://mirrors.cloud.tencent.com/pypi/packages/9a/65/76aea825b59727b556cca74e28d68e4d73244d2e1e8a8945c29d6d3d5e11/docutils-0.17-py2.py3-none-any.whl (575 kB)
|████████████████████████████████| 575 kB 912 kB/s
Collecting requests
Downloading https://mirrors.cloud.tencent.com/pypi/packages/29/c1/24814557f1d22c56d50280771a17307e6bf87b70727d975fd6b2ce6b014a/requests-2.25.1-py2.py3-none-any.whl (61 kB)
|████████████████████████████████| 61 kB 1.0 MB/s
Collecting certifi>=2017.4.17
Downloading https://mirrors.cloud.tencent.com/pypi/packages/5e/a0/5f06e1e1d463903cf0c0eebeb751791119ed7a4b3737fdc9a77f1cdfb51f/certifi-2020.12.5-py2.py3-none-any.whl (147 kB)
|████████████████████████████████| 147 kB 726 kB/s
Collecting idna<3,>=2.5
Downloading https://mirrors.cloud.tencent.com/pypi/packages/a2/38/928ddce2273eaa564f6f50de919327bf3a00f091b5baba8dfa9460f3a8a8/idna-2.10-py2.py3-none-any.whl (58 kB)
|████████████████████████████████| 58 kB 644 kB/s
Collecting urllib3<1.27,>=1.21.1
Downloading https://mirrors.cloud.tencent.com/pypi/packages/09/c6/d3e3abe5b4f4f16cf0dfc9240ab7ce10c2baa0e268989a4e3ec19e90c84e/urllib3-1.26.4-py2.py3-none-any.whl (153 kB)
|████████████████████████████████| 153 kB 564 kB/s
Collecting chardet<5,>=3.0.2
Downloading https://mirrors.cloud.tencent.com/pypi/packages/19/c7/fa589626997dd07bd87d9269342ccb74b1720384a4d739a1872bd84fbe68/chardet-4.0.0-py2.py3-none-any.whl (178 kB)
|████████████████████████████████| 178 kB 827 kB/s
Building wheels for collected packages: Kivy-Garden
Building wheel for Kivy-Garden (setup.py) ... done
Created wheel for Kivy-Garden: filename=Kivy_Garden-0.1.4-py3-none-any.whl size=4532 sha256=70dd6bf0a005868e9aca0710f7b717432bda7925c0fac236b99d2527ec112b78
Stored in directory: /home/dechin/.cache/pip/wheels/c9/d0/d4/2cb72931b74be8ce5fbee5ed87d66366f356a3161ea772d015
Successfully built Kivy-Garden
Installing collected packages: urllib3, idna, chardet, certifi, requests, pygments, Kivy-Garden, docutils, kivy
Successfully installed Kivy-Garden-0.1.4 certifi-2020.12.5 chardet-4.0.0 docutils-0.17 idna-2.10 kivy-2.0.0 pygments-2.8.1 requests-2.25.1 urllib3-1.26.4

To speed up the installation , We used Tencent's pip Source . After installation , You can see in the installed list the kivy And its dependent components :

(kivy_venv)[dechin@dechin-manjaro kivy]$ python3 -m pip list
Package Version
----------- ---------
certifi 2020.12.5
chardet 4.0.0
docutils 0.17
idna 2.10
Kivy 2.0.0
Kivy-Garden 0.1.4
pip 21.0.1
Pygments 2.8.1
requests 2.25.1
setuptools 54.1.2
urllib3 1.26.4
wheel 0.36.2

kivy Of hello world

Good configuration kivy After the environment , We can test it directly on the computer python Written app example , such as kivy Of hello world:

# kivy_hello_world.py
import kivy
kivy.require('2.0.0') # Note the matching version number from kivy.app import App
from kivy.uix.label import Label class MyApp(App):
def build(self):
return Label(text='Hello world') if __name__ == '__main__':
MyApp().run()

It can be used directly python3 kivy_hello_world.py To execute , The execution result is shown in the figure below :

During execution, we can see a series of log output on the screen , When there is an error reporting problem , Query execution log is a necessary positioning means :

[INFO ] [Logger ] Record log in /home/dechin/.kivy/logs/kivy_21-04-03_1.txt
[INFO ] [Kivy ] v2.0.0
[INFO ] [Kivy ] Installed at "/home/dechin/projects/2021-python/kivy/kivy_venv/lib/python3.8/site-packages/kivy/__init__.py"
[INFO ] [Python ] v3.8.5 (default, Sep 4 2020, 07:30:14)
[GCC 7.3.0]
[INFO ] [Python ] Interpreter at "/home/dechin/projects/2021-python/kivy/kivy_venv/bin/python3"
[INFO ] [Factory ] 186 symbols loaded
[INFO ] [Image ] Providers: img_tex, img_dds, img_sdl2 (img_pil, img_ffpyplayer ignored)
[INFO ] [Text ] Provider: sdl2
[INFO ] [Window ] Provider: sdl2
[INFO ] [GL ] Using the "OpenGL" graphics system
[INFO ] [GL ] Backend used <sdl2>
[INFO ] [GL ] OpenGL version <b'4.6 (Compatibility Profile) Mesa 20.3.1'>
[INFO ] [GL ] OpenGL vendor <b'Intel'>
[INFO ] [GL ] OpenGL renderer <b'Mesa Intel(R) UHD Graphics 620 (WHL GT2)'>
[INFO ] [GL ] OpenGL parsed version: 4, 6
[INFO ] [GL ] Shading version <b'4.60'>
[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 ] [ProbeSysfs ] device match: /dev/input/event16
[INFO ] [MTD ] Read event from </dev/input/event16>
[INFO ] [Base ] Start application main loop
[INFO ] [GL ] NPOT texture support is available
[WARNING] [MTD ] Unable to open device "/dev/input/event16". Please ensure you have the appropriate permissions.
[INFO ] [Base ] Leaving application in progress...

Come here , Our first step is basically completed , But here's the thing , Here our program is still running on the computer , We need to package it into apk After the document , To run on the mobile phone .

Why you choose to use a virtual environment

Here's a single chapter , Here are some of the official ways to use virtual environments , In fact, this is what will be introduced later apk Packing has a lot to do with . We are packing apk In the process of , If there's something about python Dependency package , All need to be identified in the configuration file in advance . This is very important , It's better to specify a specific version number for installation , Otherwise, there will be packaging failure , If we go to the packaging stage to locate and solve such problems , It will be very troublesome .

apk Build environment configuration

We have adopted... Locally buildozer To carry out apk The construction of , If you rely on other local environments such as jdk And so on are all deployed , Install it directly in the virtual environment buildozer There is no problem . However, due to the lack of dependence in the local environment , So in order to avoid the confusion of environment switching , Here we use the virtual environment to show the basic methods of installation and use , But in practical application scenarios , We still use the local one directly python3 Environmental Science , Instead of virtual environments .

install buildozer

With others python It's the same as the library , We can go through pip Come on buildozer Install and manage :

(kivy_venv)[dechin@dechin-manjaro kivy]$ python3 -m pip install buildozer -i https://mirrors.cloud.tencent.com/pypi/simple
Looking in indexes: https://mirrors.cloud.tencent.com/pypi/simple
Collecting buildozer
Downloading https://mirrors.cloud.tencent.com/pypi/packages/ac/62/a53738c604ebc86d3b62f654c3169e8c0b4178a066d7398cf53377a5cb3b/buildozer-1.2.0-py3-none-any.whl (77 kB)
|████████████████████████████████| 77 kB 783 kB/s
Collecting sh
Downloading https://mirrors.cloud.tencent.com/pypi/packages/50/38/f7dcc62943d0870f02df9e2fa527b7f0cd86b233a80d6e503a08f3ef5ddc/sh-1.14.1-py2.py3-none-any.whl (40 kB)
|████████████████████████████████| 40 kB 1.7 MB/s
Collecting pexpect
Downloading https://mirrors.cloud.tencent.com/pypi/packages/39/7b/88dbb785881c28a102619d46423cb853b46dbccc70d3ac362d99773a78ce/pexpect-4.8.0-py2.py3-none-any.whl (59 kB)
|████████████████████████████████| 59 kB 1.0 MB/s
Collecting virtualenv
Downloading https://mirrors.cloud.tencent.com/pypi/packages/91/fb/ca6c071f4231e06a9f0c3bd81c15c233bbacd4a7d9dbb7438d95fece8a1e/virtualenv-20.4.3-py2.py3-none-any.whl (7.2 MB)
|████████████████████████████████| 7.2 MB 2.2 MB/s
Collecting ptyprocess>=0.5
Downloading https://mirrors.cloud.tencent.com/pypi/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl (13 kB)
Collecting distlib<1,>=0.3.1
Downloading https://mirrors.cloud.tencent.com/pypi/packages/f5/0a/490fa011d699bb5a5f3a0cf57de82237f52a6db9d40f33c53b2736c9a1f9/distlib-0.3.1-py2.py3-none-any.whl (335 kB)
|████████████████████████████████| 335 kB 721 kB/s
Collecting six<2,>=1.9.0
Downloading https://mirrors.cloud.tencent.com/pypi/packages/ee/ff/48bde5c0f013094d729fe4b0316ba2a24774b3ff1c52d924a8a4cb04078a/six-1.15.0-py2.py3-none-any.whl (10 kB)
Collecting appdirs<2,>=1.4.3
Downloading https://mirrors.cloud.tencent.com/pypi/packages/3b/00/2344469e2084fb287c2e0b57b72910309874c3245463acd6cf5e3db69324/appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB)
Collecting filelock<4,>=3.0.0
Downloading https://mirrors.cloud.tencent.com/pypi/packages/93/83/71a2ee6158bb9f39a90c0dea1637f81d5eef866e188e1971a1b1ab01a35a/filelock-3.0.12-py3-none-any.whl (7.6 kB)
Installing collected packages: six, ptyprocess, filelock, distlib, appdirs, virtualenv, sh, pexpect, buildozer
Successfully installed appdirs-1.4.4 buildozer-1.2.0 distlib-0.3.1 filelock-3.0.12 pexpect-4.8.0 ptyprocess-0.7.0 sh-1.14.1 six-1.15.0 virtualenv-20.4.3

After installation , It should be seen locally buildozer Installation position of :

(kivy_venv)[dechin@dechin-manjaro kivy]$ which buildozer
/home/dechin/projects/2021-python/kivy/kivy_venv/bin/buildozer

buildozer Basic use of

In terms of framework ,buildozer In fact, there are only two steps to use : First use init Generate configuration files , And then use buildozer debug You can construct a apk The file , With luck :)

(kivy_venv) [dechin@dechin-manjaro kivy]$ buildozer init
File buildozer.spec created, ready to customize!

According to the first step of the process, after the initialization is completed , The current directory will generate a buildozer.spec Configuration file for , Unlike other software , This configuration file is stinky and long , It's very inconvenient to modify , Extremely unfriendly to novices . however , Fortunately, you don't need to modify the configuration file to build it successfully apk.

(kivy_venv) [dechin@dechin-manjaro kivy]$ ll
Total usage 24
-rw-r--r-- 1 dechin dechin 10489 4 month 3 22:17 buildozer.spec
-rw-r--r-- 1 dechin dechin 243 4 month 3 22:06 kivy_hello_world.py
drwxr-xr-x 4 dechin dechin 4096 4 month 3 22:00 kivy_venv

When you execute the following command , Normally, trouble is just beginning :

(kivy_venv) [dechin@dechin-manjaro kivy]$ buildozer android debug deploy run
# Check configuration tokens
# Ensure build layout
# Create directory /home/dechin/.buildozer
# Create directory /home/dechin/.buildozer/cache
# Create directory /home/dechin/projects/2021-python/kivy/.buildozer
# Create directory /home/dechin/projects/2021-python/kivy/bin
# Create directory /home/dechin/projects/2021-python/kivy/.buildozer/applibs
# Create directory /home/dechin/.buildozer/android/platform/android/platform
# Create directory /home/dechin/projects/2021-python/kivy/.buildozer/android/platform
# Create directory /home/dechin/projects/2021-python/kivy/.buildozer/android/app
# Check configuration tokens
# Read available permissions from api-versions.xml
# Preparing build
# Check requirements for android
# Run 'dpkg --version'
# Cwd None
/bin/sh: That's ok 1: dpkg: Command not found
# Search for Git (git)
# -> found at /usr/bin/git
# Search for Cython (cython)
# -> found at /home/dechin/anaconda3/bin/cython
# Search for Java compiler (javac)
# Java compiler (javac) not found, please install it.

No, dpkg, No, jdk, In the reference link 5 There are also people who have specially sorted out all kinds of possible pits , Dependent on these environments , Why can't it be explained in advance in the document ? One more thing to note here is , although buildozer The official provided docker Solutions for , But we strongly don't recommend using the official docker Solution , Because of the official docker The solution is just buildozer The problem of , Don't solve other environmental dependence problems .

Build problem handling

The following is a summary of some problems encountered in the use process , It's to solve these problems , So we later gave up the way to continue testing in a virtual environment , Switch to a local environment to run directly . There's a difference to note ,buildozer Each initialization will generate a .buildozer The catalog of , And regular accounts and root Account number ~/ The catalog is different , First of all, we need to be clear about this . And if you use a virtual environment , In a virtual environment, an independent .buildozer Catalog .

dpkg Dependent installation of

We used the Arch Of Manjaro Linux System , Most of the software goes through pacman、yay and yaourt They can be downloaded directly , Of course , It's better to have a good configuration AUR Source , here dpkg We use it directly pacman To install :

[dechin-root kivy]# pacman -S dpkg
Resolving dependencies ...
Looking for package conflicts ... software package (1) dpkg-1.20.5-2 Download size : 1.75 MiB
Full installation size : 8.26 MiB :: Do you want to install ? [Y/n] Y
:: Getting package ......
dpkg-1.20.5-2-x86_64 1795.8 KiB 524 KiB/s 00:03 [#############################] 100%
(1/1) Checking the key in the key ring [#############################] 100%
(1/1) Checking package integrity [#############################] 100%
(1/1) Loading package file [#############################] 100%
(1/1) Checking for file conflicts [#############################] 100%
(1/1) Checking available storage [#############################] 100%
:: Processing package changes ...
(1/1) Installing dpkg [#############################] 100%
dpkg installs Debian package manager.
This is useful for those who want to create/modify DEB files.
However, *do not* use dpkg to install Debian packages in your ArchLinux machine.
This will break your system!
You will need to go back to Arch wiki and read the installation guide again.
You've been warned!
:: Running post transaction hook function ...
(1/1) Arming ConditionNeedsUpdate...

If there is no error in the middle, the installation is successful .

be based on docker Of buildozer programme

Although this containerization scheme is not very recommended , Because this container can solve too few problems , But here we're going to show buildozer How to configure and use the official container . First, download the official image :

[dechin-root kivy]# docker pull kivy/buildozer
Using default tag: latest
latest: Pulling from kivy/buildozer
5d3b2c2d21bb: Pull complete
3fc2062ea667: Pull complete
75adf526d75b: Pull complete
1e25f7347ef2: Pull complete
5f20dec9b37e: Pull complete
50f409884337: Pull complete
eee420e57cec: Pull complete
cf2da2cede0f: Pull complete
6581da051d43: Pull complete
e9f936019286: Pull complete
517947681358: Pull complete
Digest: sha256:b2923081b45829555cd27356fbc0ab364474c64d9879fa730eccd4ce63e22cc4
Status: Downloaded newer image for kivy/buildozer:latest
docker.io/kivy/buildozer:latest

When the download is complete , Bind the current directory to run the container image :

[dechin-root first_app]# docker run --volume "$(pwd)":/home/user/hostcwd kivy/buildozer
Buildozer 1.2.0.dev0

You can see help directly :

[dechin-root first_app]# docker run -it --volume "$(pwd)":/home/user/hostcwd kivy/buildozer --help
Usage:
buildozer [--profile <name>] [--verbose] [target] <command>...
buildozer --version Available targets:
ios iOS target, based on kivy-ios project
android Android target, based on python-for-android project Global commands (without target):
appclean Clean the .buildozer folder in the app directory.
distclean Clean the whole Buildozer environment.
help Show the Buildozer help.
init Create a 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
clean Clean the build and distribution
logcat Show the log from the device
p4a Run p4a commands. Args must come after --, or use --alias
to make an alias

First initialization , There is a problem of insufficient authority , At first, I thought it was a problem with the configuration of read and write permissions inside the container , So here we add to the container privileged jurisdiction , But after the implementation, we found that this problem still exists :

[dechin-root first_app]# docker run -it --volume "$(pwd)":/home/user/hostcwd --privileged=True kivy/buildozer init
Traceback (most recent call last):
File "/home/user/.local/bin/buildozer", line 8, in <module>
sys.exit(main())
File "/home/user/.local/lib/python3.8/site-packages/buildozer/scripts/client.py", line 13, in main
Buildozer().run_command(sys.argv[1:])
File "/home/user/.local/lib/python3.8/site-packages/buildozer/__init__.py", line 1010, in run_command
getattr(self, cmd)(*args)
File "/home/user/.local/lib/python3.8/site-packages/buildozer/__init__.py", line 1049, in cmd_init
copyfile(join(dirname(__file__), 'default.spec'), 'buildozer.spec')
File "/usr/lib/python3.8/shutil.py", line 261, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'buildozer.spec'

It may be a problem with local configuration file and directory permissions , Because the directory is generated under the normal account number , It's usually 644 Authority , So even if it's root Permission writing may also be the first , Simply change it to 777

[dechin-root kivy]# chmod -R 777 first_app/

Run again , It is found that configuration files can also be generated locally :

[dechin-root first_app]# docker run -it --volume "$(pwd)":/home/user/hostcwd --privileged=True kivy/buildozer init && ll
File buildozer.spec created, ready to customize!
Total usage 24
-rw-r--r-- 1 dechin dechin 12305 4 month 4 10:59 buildozer.spec
-rwxrwxrwx 1 root root 243 4 month 4 10:42 main.py
drwxrwxrwx 3 root root 4096 4 month 4 10:43 user

But this container image is different from the normal one , The entire container image can only execute buildozer Instructions , This is especially unfriendly to domestic users , Because what we lack is buildozer It's a bunch of environment dependent , There will be certain restrictions on the domestic network . For example, we show the running results below , Stuck in this place for a long time :

[dechin-root first_app]# docker run -it --volume "$(pwd)":/home/user/hostcwd --privileged=True kivy/buildozer android debug deploy run
# Check configuration tokens
# Ensure build layout
# Create directory /home/user/.buildozer
# Create directory /home/user/.buildozer/cache
# Create directory /home/user/hostcwd/.buildozer
# Create directory /home/user/hostcwd/bin
# Create directory /home/user/hostcwd/.buildozer/applibs
# Create directory /home/user/.buildozer/android/platform/android/platform
# Create directory /home/user/hostcwd/.buildozer/android/platform
# Create directory /home/user/hostcwd/.buildozer/android/app
# Check configuration tokens
# Read available permissions from api-versions.xml
# Preparing build
# Check requirements for android
# Run 'dpkg --version'
# Cwd None
Debian 'dpkg' package management program version 1.19.7 (amd64).
This is free software; see the GNU General Public License version 2 or
later for copying conditions. There is NO warranty.
# Search for Git (git)
# -> found at /usr/bin/git
# Search for Cython (cython)
# -> found at /home/user/.local/bin/cython
# Search for Java compiler (javac)
# -> found at /usr/lib/jvm/java-13-openjdk-amd64/bin/javac
# Search for Java keytool (keytool)
# -> found at /usr/lib/jvm/java-13-openjdk-amd64/bin/keytool
# Install platform
# Run 'git clone -b master --single-branch https://github.com/kivy/python-for-android.git python-for-android'
# Cwd /home/user/hostcwd/.buildozer/android/platform
Cloning into 'python-for-android'...

Network card will pop up many error reports after a long period of time :

Cloning into 'python-for-android'...
fatal: unable to access 'https://github.com/kivy/python-for-android.git/': GnuTLS recv error (-54): Error in the pull function.
# Command failed: git clone -b master --single-branch https://github.com/kivy/python-for-android.git python-for-android
# ENVIRONMENT:
# PATH = '/home/user/.buildozer/android/platform/apache-ant-1.9.4/bin:/home/user/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
# HOSTNAME = '69325b48f53a'
# TERM = 'xterm'
# USER = 'user'
# HOME_DIR = '/home/user'
# WORK_DIR = '/home/user/hostcwd'
# SRC_DIR = '/home/user/src'
# LANG = 'en_US.UTF-8'
# LANGUAGE = 'en_US.UTF-8'
# LC_ALL = 'en_US.UTF-8'
# HOME = '/home/user'
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2

In fact, this is the problem of the Internet , If you can go to Google , So you solved the problem at the same time . If the Internet doesn't work , Even if you can see it in the official store, you can't download and install it :

adb Log location apk problem

Suppose you have solved the problem mentioned above about visiting Google website , So the problem of environmental dependence has basically been solved , Just pay attention to jdk Follow gradle The version matching relationship of , What we use here is jdk-8, The same can be used yaourt To install . In the end, it's possible , After deploying to Android devices ,app The problem of the flashback . First of all, if we implement buildozer androiid debug deploy run, And protect Android phones at the same time USB Access and USB Debug the switch on , Well, the following message appears :

List of devices attached
xxx device # Deploy on xxx
# Run '/home/dechin/.buildozer/android/platform/android-sdk/platform-tools/adb install -r "/home/dechin/projects/2021-python/kivy/first_app/bin/myapp-0.1-armeabi-v7a-debug.apk"'
# Cwd /home/dechin/.buildozer/android/platform
Performing Streamed Install
Success
# Application pushed.
# Run on xxx
# Run '/home/dechin/.buildozer/android/platform/android-sdk/platform-tools/adb shell am start -n org.test.myapp/org.kivy.android.PythonActivity -a org.kivy.android.PythonActivity'
# Cwd /home/dechin/.buildozer/android/platform
Starting: Intent { act=org.kivy.android.PythonActivity cmp=org.test.myapp/org.kivy.android.PythonActivity }
# Application started.

But this is not the end , We found that on mobile phones apk Installed app There will be flashbacks , This is generally caused by the program error , We can connect USB In the state of debugging , Get into adb shell Check the log :

[dechin@dechin-manjaro first_app]$ adb shell
HWPCT:/ $ run-as org.test.myapp
HWPCT:/data/data/org.test.myapp
$ cd files/app/.kivy/logs/
HWPCT:/data/data/org.test.myapp/files/app/.kivy/logs
$ ls
kivy_21-04-06_0.txt
$ cat kivy_21-04-06_0.txt <
[INFO ] Logger: Record log in /data/user/0/org.test.myapp/files/app/.kivy/logs/kivy_21-04-06_0.txt
[WARNING] [Config ] Upgrading configuration in progress.
[WARNING] [Config ] Older configuration version detected (0 instead of 21)
[INFO ] Kivy: v1.11.1
[INFO ] Kivy: Installed at "/data/user/0/org.test.myapp/files/app/_python_bundle/site-packages/kivy/__init__.pyc"
[INFO ] Python: v3.8.1 (default, Apr 6 2021, 10:41:43)
[Clang 8.0.2 (https://android.googlesource.com/toolchain/clang 40173bab62ec7462
[INFO ] Python: Interpreter at ""
[WARNING] stderr: Traceback (most recent call last):
[WARNING] stderr: File "/home/dechin/projects/2021-python/kivy/first_app/.buildozer/android/app/main.py", line 4, in <module>
[WARNING] stderr: File "/home/dechin/projects/2021-python/kivy/first_app/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/__init__.py", line 138, in require
[WARNING] stderr: Exception: The version of Kivy installed on this system is too old. (You have 1.11.1, but the application requires 2.0.0)
HWPCT:/data/data/org.test.myapp/files/app/.kivy/log

We can see from the log that , This is because of the corresponding kivy The program version is too low , It needs to be modified buildozer.spec The configuration file . We find requirements here , It is found that neither of the two warehouses here specifies the version number , The solution we take here is to add the requirement of version number , And then remove .buildozer Catalog , Re install the environment .

requirements = python3,kivy

Revised as follows :

requirements = python3,kivy==2.0.0

And then re execute buildozer debug deploy run, The effect on the mobile phone interface is as follows ( If only run debug perhaps release, Then there's no need to connect the phone USB debugging , The operation here is equivalent to putting apk Transfer to the mobile phone to install and run ):



I was moved to cry ~~~

Review by the way vim Basic operation

The first is to show the line number , The interface just opened is as follows :



Use :set nu According to the line Numbers :



Use / perhaps ? Look up strings forward and backward , What I'm looking for here is kivy



When you find it, go back , The cursor moves to the front of the current target :



Shift+N Find the next target :

kivy String calculator case

Let's assume that the environmental problems have been solved , It's just writing kivy When it comes to programming , Let's test some simple cases : Output the result of string calculation according to the string , It's like python The command line inside the test in general . Of course , This requires us to do some preparatory work first .

kivy Button instance

First, let's test an example of a button , Study first kivy How to use the button in :

# main7.py
from kivy.app import App
from kivy.uix.togglebutton import ToggleButton class ToggleButtonApp(App):
def build(self):
#text Button label
#color Label text color
#background_color Button color
#font_size Label font size
TogBu=ToggleButton(text="Red",color=(0,1,0,1),background_color=(0.5,0,0.5,1),font_size=200)
return TogBu if __name__=="__main__":
ToggleButtonApp().run()

The interface of the execution result is as follows :



Click button :



Click the button again to return to the previous interface .

kivy Text box example

Due to the need to enter a text box , So we also have to test the basic use of text box :

# main8.py
from kivy.app import App
from kivy.uix.textinput import TextInput class TextInputApp(App):
def build(self):
text=TextInput(font_size=150)#font_size Enter the size of the text box
return text if __name__=="__main__":
TextInputApp().run()

The operation results are as follows : We can enter text on the interface :



But here's the thing , The font size we see on the computer is not consistent with that on the mobile phone , It should be adjusted according to the actual situation .

The core : pack math Warehouse to app in

Mathematical operation warehouse math yes python A very common library in , Here we plan to package it into an Android app in , In this way, we can call python Library to calculate some simple tasks . So our logic is like this : First of all math Function import , And then given two text boxes , One as an input window, one as an output window , Plus a button to run , That's all for work . The specific finished product code is as follows :

# main.py
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from math import * def message(self):
pop = Popup(text=self.text) class TextInputApp(App):
def build(self):
layout = BoxLayout(orientation='vertical', spacing=15, padding=10)
self.text=TextInput(font_size=150) # font_size Enter the size of the text box
self.out_text=TextInput(font_size=150)
button = Button(text="Run", size_hint=(1.0, 0.5),
pos_hint={"center_x":0.5, "center_y":0.5})
button.bind(on_press=self.press)
layout.add_widget(self.text)
layout.add_widget(self.out_text)
layout.add_widget(button)
return layout
def press(self, instance):
# pop = Popup(text=self.text.text)
try: # Capture exception , Avoid program interruptions
print (eval(self.text.text)) # eval Built in functions , Execute string instruction
self.out_text.text=str(eval(self.text.text))
except:
self.out_text.text="wrong input" # If it's illegal information , Output error
pass if __name__=="__main__":
TextInputApp().run()

Here are some basic running results :











The apk The files have also been sent to baidu.com for sharing , Interested friends can download and use :

link : https://pan.baidu.com/s/1M0mKFFuJw3Z-giA04mmTTg Extraction code :4a3q

Summary

be based on python You can also develop Android APP, This requires the use of kivy Library to develop , Re pass buildozer To build . The installation and use of these two libraries are relatively simple , We recommend direct deployment in the local system environment , The biggest difficulty is actually the deployment process and the modification of the configuration file , This is also a relatively basic operation . Finally, we demonstrated using text box and button events , add python Of eval() Functions and math Math warehouse , It can be called on the mobile terminal math The functions in the library are simple to perform mathematical calculations APP, And provides apk Download network disk address .

Copyright notice

The first link to this article is :https://www.cnblogs.com/dechinphy/p/kivy.html

author ID:DechinPhy

For more original articles, please refer to :https://www.cnblogs.com/dechinphy/

Reference link

  1. https://blog.csdn.net/hpwzjz/article/details/89703313
  2. https://kivy.org/doc/stable/gettingstarted/examples.html
  3. https://github.com/kivy/buildozer
  4. https://zhuanlan.zhihu.com/p/83335242
  5. https://zhuanlan.zhihu.com/p/33990951
  6. http://www.srcmini.com/68022.html
  7. https://blog.csdn.net/python__reported/article/details/108007036#t3
  8. https://blog.csdn.net/weixin_42269667/article/details/106517353
  9. https://blog.csdn.net/qq_37030400/article/details/107645903

python3 Use kivy More articles on generating Android programs

  1. AndroidStudio Learning notes - The first android app

    Take an undergraduate to do some projects that have something to do with Android , So take the opportunity to learn how to write Android programs . The first material comes from Google official , Portal :https://developer.android.com/training/basic ...

  2. C# Use Xamarin Development of portable mobile applications (8. Package and build Android APK And downsize ), Source code attached

    Preface Series catalog C# Use Xamarin Develop portable mobile application directory Source code address :https://github.com/l2999019/DemoApp Sure Star once , at will - - Say something .. Um. , Speak in front of the ...

  3. Analyze the application of observer mode in Android programs —— How to achieve cross interface Handler Communications

    Here we use github As an example, a project in , The address is :https://github.com/LiqiNew/HandlerFrame/tree/master/handlerFrame/src/ ...

  4. Delphi XE7 How to call the Android program of JAVA Of JAR, Use JAVA Class ?

    This article uses tools and full source code to download : http://download.csdn.net/detail/sunylat/8190765 Why do we have to Delphi XE7 Android program call JAVA Of JAR, Use JA ...

  5. Delphi XE7 In the development of Android programs, some useful help resources

    explain : To see the following resources , After opening help , Enter... In the search URL Last part , If you end up with “.html”, Delete it , Then search , Saw the . for example : I want to see the following FireMonkey Class diagram , Just type in the search &qu ...

  6. Just write Python Code one time , Android and IOS Of APP, Excellent

    Preface : use Python Write Android APP Definitely not the best choice , But it must be a very lazy choice We use kivy Develop Android APP,Kivy It's an open source framework for rapid cross platform application development , Use Python and Cython To write ...

  7. Use .NET WinForm Develop what you see is what you get IDE development environment , Implementation does not write code directly generated applications

    Get straight to the point , This is me 09 Year to 11 Projects written in spare time around , The original idea was simple , Make a tool that can drag and drop to generate application directly , Don't write code , Encapsulate all the business operations you can think of , Organize these business operations through configuration ...

  8. There is no extension for “.html” Registered build provider

    asp.net Tips “ There is no extension for “.html” Registered build provider ... ” terms of settlement , modify web.config file : <compilation debug="true"&g ...

  9. Use LabVIEW How to build an application (exe) And setup (installer)

    Main software :   LabVIEW Development Systems>>LabVIEW Professional Development System Major software versions :   2012 Main software ...

  10. Zero basis Android Learning notes -02 Android application life cycle

    An Android application life cycle goes through 7 Medium state , Not necessarily every time .Create,Start,ReStart,Pause,Resume,Stop,Destory. Overloading methods , use helloWorld Program to experience ...

Random recommendation

  1. css Highly adaptive

    What is highly adaptive ? Height adaptation means that the height can change with the size of the browser window , Typically used in some background interfaces, the upper column is fixed in height and used as a menu bar or navigation bar , The following column is height adaptive for displaying content . Height adaptation is not as simple as width adaptation , stay ...

  2. hudson install

    Hudson Just a continuous integration server ( Continuous integration tools ), To build a complete continuous integration management platform ,  SVN.Maven.Sonar And other tools can be integrated on demand .   1. install JDK And configure environment variables ( A little )  J ...

  3. Memcached source code analysis -- Analysis of change of state--reference

    This article mainly introduces the process of Memcached, libevent structure of the main thread and w ...

  4. 【iOS】Swift Class inheritance 、 Construction method 、 Destructor, etc

    One . Inheritance and rewriting ,  Prevent rewriting 1.1  Base class ,  Does not inherit any classes . Swift Don't want to OC perhaps Java Relay from Object class . Define a class , Does not inherit any classes , This class is the base class . [java] view plaincopy ...

  5. python obtain subprocess Return value after process execution

    test.py #coding=utf- import subprocess compilePopen = subprocess.Popen('gcc haha',shell=True,stderr= ...

  6. MetaMask Installation and use guide

    1.MetaMask( Light purse ) MetaMask It's a Google browser Chrome The plug-in type used on the Ethereum wallet , The wallet doesn't need to be downloaded , Just in Google browser or other browsers based on Google browser kernel ( Such as :360 Opera Portable - ...

  7. [LeetCode] 877. Stone Game == [LintCode] 396. Coins in a Line 3_hard tag: Section Dynamic Programming, game

    Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, ...

  8. C++——stoi function

    Copyright notice : This article is original , Reprint please state the source . 1. The function prototype , ); , ); 2. Parameter description str String object with the representation of an integr ...

  9. beego——URL structure

    If it can match URl, that beego It can also generate URL Do you ? Certainly. . UrlFor() Functions are used to build execution functions URL Of . It takes the string of the corresponding controller and function name as the first parameter , The rest of the parameters correspond to URL The variables in the . Unknown ...

  10. ten Chatbot The framework is introduced

    ten Chatbot The framework is introduced original  2016 year 12 month 13 Japan 16:01:23 4616 Chatbot list 1.  Artificial Intelligence Markup Language    ...