[Tutorial] How to build Python for Android with Ubuntu and Buildozer

Welcome,

I’m Aron, from Byte::Debugger();, and in this post we are going to see how to compile Python targeting Android with Ubuntu(tested on Ubuntu 14.04) and Buildozer!! This process works with others Linux distros, but I’ll need to find the appropriate package. So, let’s start.

I – Installing buildozer

You can read the full documentation here, it’s well documented!

Buildozer itself doesn’t depend on any library, and works on Python 2.7 and >= 3.3. I recommend you to use Python 2.7.

First, we need to download PIP, a tool for installing and managing Python packages.

 # apt-get install python-pip

Now, to install buildozer run:

pip install --upgrade buildozer

If everything works fine, you will see the output: Successfully installed buildozer

II –  Targeting Android

If you target Android, you must install at least Cython, few build libs, and a Java SDK. Some binaries of the Android SDK are still in 32 bits, so you need few 32bits libraries available.

First, we need to install Cython:

# apt-get install python2.7-dev
# pip install --upgrade cython

Now, make the 32 bits lib available:

# dpkg --add-architecture i386

After it, you can update and install the necessary packages:

# apt-get update
# apt-get install build-essential ccache git lib32z1 libncurses5:i386 libstdc++6:i386 python2.7 openjdk-7-jdk unzip zlib1g-dev zlib1g:i386

Ok, now we have everything to start with Python development for Android!! Let’s try it!

III – Simple example

Let’s create a hello world to test if everything is working. In this hello world, I’m going to use kivy. If you don’t have Kivy installed, run the following command:

# apt-get install python-kivy

Now, create a new file with the name main.py, and make sure to add the line __version__ = “1.0” in your file, because buildozer will try to find this line to determine the app version.

To test it, write this simple hello world:


__version__ = “1.0”
from kivy.app import App
from kivy.uix.button import Button
 
class Hello(App):
    def build(self):
        btn = Button(text='Hello World')
        return  btn
 
Hello().run()

Now, open your terminal and go to the main.py folder. After it, create a buildozer.spec file, with:

buildozer init

You can open the buildzoer.spec file  and change your app settings, as the name, developer, and this kind of stuff.

To build your project, run:

buildozer -v android debug

This command will download python-for-android, Android SDK and Android NDK for you. If it’s the first time that you are building, you can go and drink some coffee, because it need to download a big chain of libs and build it, so if your computer/internet is slow, it can take a long time. I’m going to drink a cup of coffee, I hope to see you soon! If you don’t have coffee or are tired of waiting, take a look in my blog, here you can find some tutorials and examples about coding: Python Mobile, Java Mobile, Processing IDE, Firefox OS, Arduino, and this kind of stuff.

After it, you everything works fine, you will see the message:

# Android packaging done!
# APK MyApplication-1.2.0-debug.apk available in the bin directory

Now, you can get the APK in the bin folder and install it in your device! If your device is connected in the USB, just run:

adb install bin/MyApplication-1.2.0-debug.apk

To install it!

The example app:

Screenshot_2014-06-30-22-07-56

That’s all, if you have any problem, suggestion, or anything, fell free and comment here! Thx for reading!

Aron

Advertisements

57 thoughts on “[Tutorial] How to build Python for Android with Ubuntu and Buildozer

  1. Reblogged this on Byte::Debugger(); and commented:

    How to download and install Buildozer on Ubuntu, targeting Android development with Pytohn. Take a look!

    • Im getting an error at the very end when it tries to package my app. It says that my directory that contains my .py folder cant be found. Here is an error snippet:
      #############################################################
      Entering in ARM environment
      Compiler found at /home/goshfather/.buildozer/android/platform/android-ndk-r9c/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-gcc
      Leaving ARM enviromnent
      All done !
      # Remove temporary build files
      # Remove directory and subdirectory /home/goshfather/Desktop/game/.buildozer/android/platform/python-for-android/build
      # Distribution compiled.
      # Build the application #8
      # Copy application source from /home/goshfather/Desktop/game
      # Create directory /home/goshfather/Desktop/game/.buildozer/android/app
      # Copy /home/goshfather/Desktop/game/main.py
      # Package the application
      # Captured version: 1.0
      Traceback (most recent call last):
      File “/usr/local/bin/buildozer”, line 11, in
      sys.exit(main())
      File “/usr/local/lib/python2.7/dist-packages/buildozer/scripts/client.py”, line 13, in main
      Buildozer().run_command(sys.argv[1:])
      File “/usr/local/lib/python2.7/dist-packages/buildozer/__init__.py”, line 961, in run_command
      self.target.run_commands(args)
      File “/usr/local/lib/python2.7/dist-packages/buildozer/target.py”, line 85, in run_commands
      func(args)
      File “/usr/local/lib/python2.7/dist-packages/buildozer/target.py”, line 97, in cmd_debug
      self.buildozer.build()
      File “/usr/local/lib/python2.7/dist-packages/buildozer/__init__.py”, line 193, in build
      self.target.build_package()
      File “/usr/local/lib/python2.7/dist-packages/buildozer/targets/android.py”, line 499, in build_package
      self._update_libraries_references(dist_dir)
      File “/usr/local/lib/python2.7/dist-packages/buildozer/targets/android.py”, line 655, in _update_libraries_references
      with io.open(project_fn, ‘w’, encoding=’utf-8′) as fd:
      IOError: [Errno 2] No such file or directory: ‘/home/goshfather/Desktop/game/.buildozer/android/platform/python-for-android/dist/”myapp”/project.properties’
      #############################################################

    • Thanks again for this helpful writeup.
      I have the basic project successfully built and running.

      1) I was wondering what emulators people are using?
      2) Is there an easy way to run your project in the emulator from:
      A) the command line,
      B) from within python IDEs like WingWare IDE or PyCharm?
      3) What happens if you want to add new packages to your python installation that buildozer is using (after you’ve already initially built)? I want to be able to use plyer. If you pip install plyer to your system’s default python installation, the next time you run “buildozer -v android debug”, does it dynamically include new python modules into your build?

      Thanks in advance

    • #buildozer -v android build
      getting stuck at below line.. what to do?
      Refresh Sources:
      Fetching https://dl-ssl.google.com/android/repository/addons_list-2.xml

  2. If you have adb set up on your computer correctly, you can even use buildozer to deploy and run the APK on your device: `buildozer android debug deploy run`

    • Hi Ben, thanks for your comment

    • I have the basic project successfully built and running.

      1) I was wondering what emulators people are using?
      2) Is there an easy way to run your project in the emulator from:
      A) the command line,
      B) from within python IDEs like WingWare IDE or PyCharm?
      3) What happens if you want to add new packages to your python installation that buildozer is using (after you’ve already initially built)? I want to be able to use plyer. If you pip install plyer to your system’s default python installation, the next time you run “buildozer -v android debug”, does it dynamically include new python modules into your build?

      Thanks in advance

    • Grim, et al. Looking for opinions on Hoa#8nivn&na217;s SFHs and the town of Hackettstown. Considering a new one in Hackettstown, wondering what anyone knows about the town. Have two small kids, so education and recreation are a huge factor.Any comments from folks that know would be appreciated.-Anth

  3. if you get a version error doing this, just comment out the method 1 option in the .spec file and uncomment the method 2 version in the spec file

    see issue – https://github.com/kivy/buildozer/issues/129

  4. […] [Tutorial] How to build Python for Android with Ubuntu and Buildozer […]

  5. […] [Tutorial] How to build Python for Android with Ubuntu and Buildozer […]

  6. How can I sign a app for Google Play?

  7. Hi, i followed your step and i got this Error:
    ~$ buildozer -v android debug
    # Check configuration tokens
    # Ensure build layout
    # 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.17.5 (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 /usr/local/bin/cython
    # Search for Java compiler (javac)
    # -> found at /usr/lib/jvm/java-7-openjdk-amd64/bin/javac
    # Search for Java keytool (keytool)
    # -> found at /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/keytool
    # Install platform
    # Run ‘git clone git://github.com/kivy/python-for-android’
    # Cwd /home/mk/.buildozer/android/platform
    Cloning into ‘python-for-android’…
    fatal: unable to connect to github.com:
    github.com[0: 192.30.252.128]: errno=Connection timed out

    # Command failed: git clone git://github.com/kivy/python-for-android

  8. HI, finally it has produced this error:
    Package the application
    Traceback (most recent call last):
    File “/usr/local/bin/buildozer”, line 9, in
    load_entry_point(‘buildozer==0.17-dev’, ‘console_scripts’, ‘buildozer’)()
    File “/usr/local/lib/python2.7/dist-packages/buildozer-0.17_dev-py2.7.egg/buildozer/scripts/client.py”, line 13, in main
    Buildozer().run_command(sys.argv[1:])
    File “/usr/local/lib/python2.7/dist-packages/buildozer-0.17_dev-py2.7.egg/buildozer/__init__.py”, line 961, in run_command
    self.target.run_commands(args)
    File “/usr/local/lib/python2.7/dist-packages/buildozer-0.17_dev-py2.7.egg/buildozer/target.py”, line 85, in run_commands
    func(args)
    File “/usr/local/lib/python2.7/dist-packages/buildozer-0.17_dev-py2.7.egg/buildozer/target.py”, line 97, in cmd_debug
    self.buildozer.build()
    File “/usr/local/lib/python2.7/dist-packages/buildozer-0.17_dev-py2.7.egg/buildozer/__init__.py”, line 193, in build
    self.target.build_package()
    File “/usr/local/lib/python2.7/dist-packages/buildozer-0.17_dev-py2.7.egg/buildozer/targets/android.py”, line 478, in build_package
    version = self.buildozer.get_version()
    File “/usr/local/lib/python2.7/dist-packages/buildozer-0.17_dev-py2.7.egg/buildozer/__init__.py”, line 657, in get_version
    ‘ (looking for `{1}`)’.format(fn, regex))
    Exception: Unable to find capture version in ./main.py
    (looking for `__version__ = [‘”](.*)[‘”]`)

    It not created archives .APK in folder bin.
    Thanks for this tutorial

  9. Just replaced __version__ = “1.0” by __version__ = ‘1.0’ and it worked.

  10. Nice article, thank you for writing this up. Though unless I missed something, in your installation instructions:
    the installation of python2.7-dev should appear first before pip installing cython as the header files in python2.7-dev are a required dependency to install cython.

    Also, after first installing python2.7-dev, I ended up installing cython version 0.20.1 from Synaptic instead of from the command line which had complained:

    warning: no files found matching ‘*.pyx’ under directory ‘Cython/Debugger/Tests’
    warning: no files found matching ‘*.pxd’ under directory ‘Cython/Debugger/Tests’
    warning: no files found matching ‘*.h’ under directory ‘Cython/Debugger/Tests’
    warning: no files found matching ‘*.pxd’ under directory ‘Cython/Utility’

    And trying to install lib32z1, I get:
    E: Unable to locate package lib32z1-dev

  11. Thanks Aron. I had already answered my own question. I am completely new to mobile development. It would be nice if, in their instruction, the main site with the tutorial (buildozer) would have a side comment mentioning that developer mode needs to be enabled on the target device before using their command (deploy run or logcat):
    buildozer -v android debug deploy run logcat
    Just saying, if it’s a tutorial for developing android apps, the above information (enable dev mode) probably should be included. Anyway, after enabling developer mode, the above command works flawlessy.
    Thanks for the link. Maybe it will help clarify to others just starting out too.

  12. […] [Tutorial] How to build Python for Android with Ubuntu and Buildozer […]

  13. […] [Tutorial] How to build Python for Android with Ubuntu and Buildozer […]

  14. […] [Tutorial] How to build Python for Android with Ubuntu and Buildozer […]

  15. […] [Tutorial] How to build Python for Android with Ubuntu and Buildozer […]

  16. Hi!
    I am using ubuntu 14.04 for building apk file using kivy.
    I had tried both, steps given on your web portal and on Kivy packaging instructions.
    But buildozer -v android debug is terminating with error of Cython being unable to found. Though I can check that I have Cython.
    Some of the lines related to error :-
    1. /usr/include -I/home/jp/Desktop/test1/buildozer/.buildozer/android/platform/python-for-android/build/python-install/include/python2.7 -c kivy/graphics/texture.c -o build/temp.linux-x86_64-2.7/kivy/graphics/texture.o
    arm-linux-androideabi-gcc: error: kivy/graphics/texture.c: No such file or directory
    arm-linux-androideabi-gcc: fatal error: no input files
    compilation terminated.
    error: command ‘ccache’ failed with exit status 1

    Error compiling Cython file:
    2. Earlier there was also mention of cython not found while checking for dependencies.

    What can be probable reason?

  17. It said: 1. Check build dependencies for Ubuntu
    Packages missing: cython
    It might break the compilation, except if you installed thoses packages manually.

    2. .c -o build/temp.linux-x86_64-2.7/kivy/graphics/vertex_instructions.o
    kivy/graphics/vertex_instructions.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
    #error Do not use this file, it is the result of a failed Cython compilation.
    ^
    error: command ‘ccache’ failed with exit status 1
    # Command failed: ./distribute.sh -m “kivy” -d “myapp”

  18. Can’t fix this problem:

    Ubuntu 14.04.1 LTS

    $ cython –version
    Cython version 0.22

    $ ccache –version
    ccache version 3.1.9
    …………………………..
    Detected compiler is unix
    building ‘kivy.graphics.texture’ extension
    ccache arm-linux-androideabi-gcc -DANDROID -mandroid -fomit-frame-pointer –sysroot /home/dev/.buildozer/android/platform/android-ndk-r9c/platforms/android-14/arch-arm -DNDEBUG -DANDROID -mandroid -fomit-frame-pointer –sysroot /home/dev/.buildozer/android/platform/android-ndk-r9c/platforms/android-14/arch-arm -fPIC -I/home/dev/.buildozer/android/platform/android-ndk-r9c/platforms/android-14/arch-arm/usr/include -I/home/dev/timetable/.buildozer/android/platform/python-for-android/build/python-install/include/python2.7 -c kivy/graphics/texture.c -o build/temp.linux-x86_64-2.7/kivy/graphics/texture.o
    kivy/graphics/texture.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
    #error Do not use this file, it is the result of a failed Cython compilation.
    error: command ‘ccache’ failed with exit status 1
    # Command failed: ./distribute.sh -m “kivy” -d “TimeTable”

  19. […] [Tutorial] How to build Python for Android with Ubuntu and Buildozer […]

  20. It’s normal in linux. Tutorial not actual after 1-2 weeks because
    package not found
    or error dureing compilation
    and other reason …

    Need dancing with drums to make simple example 🙂

  21. What is an easy way to create an Android package for Kivy?

    The easiest way to build an apk for kivy is buildozer. Must have: Linux(Mint or Ubuntu 14.04) Follow this link:https://kivyspacegame.wordpress.com/2014/06/30/tutorial-how-to-build-python-for-android-with-ubuntu-and-buildozer/ And the app must be in a f…

  22. well i build the apk and successfully installed it in my phone but it is huge, 36.9 MB. It is just a Hello world button why it is so big????

    • Make sure that the files you want to build is only in the folder and other projects should be located outside the folder so as to not to compile every thing for you

  23. please how can i add external modules like peewee or sqlalchemy for database interaction

  24. hi. i could follow through all steps well but the apk crashes on my devices on opening with error:
    trebuchet crashed.

    crash report (excerpt):

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cyanogenmod.trebuchet/com.android.launcher3.Launcher}: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.appwidget.AppWidgetHostView$ParcelableSparseArray instead. This usually happens when two views of different type have the same id in the same hierarchy. This view’s id is id/0x3. Make sure other views do not use the same id.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3980)
    at android.app.ActivityThread.access$1000(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5294)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
    Caused by: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.appwidget.AppWidgetHostView$ParcelableSparseArray instead. This usually happens when two views of different type have the same id in the same hierarchy. This view’s id is id/0x3. Make sure other views do not use the same id.
    at android.view.View.onRestoreInstanceState(View.java:13780)
    at android.widget.TextView.onRestoreInstanceState(TextView.java:3784)
    at android.view.View.dispatchRestoreInstanceState(View.java:13756)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2894)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2894)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2894)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2894)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2894)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2894)
    at android.view.View.restoreHierarchyState(View.java:13734)
    at com.android.internal.policy.impl.PhoneWindow.restoreHierarchyState(PhoneWindow.java:2060)
    at android.app.Activity.onRestoreInstanceState(Activity.java:1023)
    at com.android.launcher3.Launcher.onRestoreInstanceState(Launcher.java:2360)
    at android.app.Activity.performRestoreInstanceState(Activity.java:978)
    at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1162)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)

    any ideas what could cause this?

  25. #buildozer -v android debug

    getting stuck at below stage
    Refresh Sources:
    Fetching https://dl-ssl.google.com/android/repository/addons_list-2.xml

  26. Hi, I’ve followed these steps, and also tried several other methods and tutorials to convert to an apk from kivy and I keep coming up short. I get to the step, buildozer -v android debug , but it errors at that point. This is the error I am receving:

    # Install platform
    # Run ‘git clone -b old_toolchain –single-branch https://github.com/kivy/python-for-android.git python-for-android’
    # Cwd /home/kivy/Desktop/test/.buildozer/android/platform
    Cloning into ‘python-for-android’…
    # Apache ANT found at /home/kivy/.buildozer/android/platform/apache-ant-1.9.4
    # Android SDK found at /home/kivy/.buildozer/android/platform/android-sdk-20
    # Android NDK found at /home/kivy/.buildozer/android/platform/android-ndk-r9c
    # Run ‘/home/kivy/.buildozer/android/platform/android-sdk-20/tools/android list sdk -u -e’
    # Cwd /home/kivy/.buildozer/android/platform
    Error: Invalid or corrupt jarfile /home/kivy/.buildozer/android/platform/android-sdk-20/tools/lib/archquery.jar
    Error: Invalid or corrupt jarfile /home/kivy/.buildozer/android/platform/android-sdk-20/tools/lib/archquery.jar
    Exception in thread “main” java.lang.NoClassDefFoundError: com/android/sdkuilib/internal/widgets/MessageBoxLog
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2625)
    at java.lang.Class.getMethod0(Class.java:2866)
    at java.lang.Class.getMethod(Class.java:1676)
    at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
    Caused by: java.lang.ClassNotFoundException: com.android.sdkuilib.internal.widgets.MessageBoxLog
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    … 6 more
    # Command failed: /home/kivy/.buildozer/android/platform/android-sdk-20/tools/android list sdk -u -e
    #
    # 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

    Sorry if this has already been addressed but I’ve tried searching for the answer here and elsewhere for hours and haven’t been able to figure it out.

    Thanks for any help you can offer.

  27. I followed to the last step which involves these command ++bulldozer – v android debug
    It gave me these error:: seriously speaking I can’t paste all the error outputs here. Thanks guys for reply::

    Traceback (most recent call last):
    File “build.py”, line 517, in
    make_package(args)
    File “build.py”, line 365, in make_package
    subprocess.check_call([ANT, arg])
    File “/usr/lib/python2.7/subprocess.py”, line 541, in check_call
    raise CalledProcessError(retcode, cmd)
    subprocess.CalledProcessError: Command ‘[‘ant’, ‘debug’]’ returned non-zero exit status 1
    # Command failed: python build.py –name Ttutorials –version 0.1 –package org.test.myapp –sdk 19 –minsdk 9 –private /home/pythonguy/kivyinstall/.buildozer/android/app –orientation sensor –window debug
    #
    # 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

  28. Pls. I have been trying to include kivymd with my buildozer,but has not been downloading it. it always returns “kivymd not found because it is not a recipe”

  29. Hi

    The tutorial is great. Thanks. I was able to create a basic “hello world” application and move/install it to my android phone. Few questions:

    1. Even though its just a “hello world” app, it still is more than 200 mb size. Any idea why. I am using pycharm IDE on ubuntu and I also have several other python libraries ( nltk, machine learning, visualizations etc etc) installed. When I was compiling my app, it saw it was referring those thing also. Am I correct.

    2. When I try to run the app on phone, its keeps giving message ‘Loading…’ and then I guess it crashes. Also my phone starts giving the message that storage space is going down. I guess its due to first reason above.

    Any idea how to fix above things

    • Congrats on writing the hello world app,but if you compiled it with bulldozer then your app should be less than 10mb ..I think you should check out the parameters in the buildozer.spec file and add the folders that you don’t want to be included in the build. I’m sure you getting that huge size because the build added some unnecessary stuffs

  30. Debian ‘dpkg’ package management program version 1.18.10 (i386).
    This is free software; see the GNU General Public License version 2 or
    later for copying conditions. There is NO warranty.
    # Check configuration tokens
    # zlib headers must be installed, run: sudo apt-get install zlib1g-dev

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s