Python on Android

 

There are an increasing number of resources about different ways of running Python on Android. Kivy (and its subprojects) are commonly mentioned, as one of the most mature and popular ways to do so, but one thing that gets less attention is the details of what you can do with Python itself once it’s running on the device - what are the limitations of this? Can we use any Python module? What about calling Android APIs, can we perform all of the functions of a Java application? These are all somewhat leading questions, they are things addressed by Kivy or its associated projects, and in this post I’ll summarise some of the most interesting and important details.

python-for-android

Before anything else, let’s look quickly at the tool Kivy actually uses to get Python on Android; the unimaginatively-named python-for-android project. The basic functionality of this tool is to first build a distribution, an Android project directory that includes all the components Kivy needs to run, compiled for Android by its NDK. This includes in particular the Python interpreter itself, plus Kivy and the libraries it depends on - currently Pygame and SDL amongst others, although we are working to modernise this bit. The distribution also includes a Java bootstrap, a normal app structure whose job is to display Kivy’s OpenGL surface and to mediate between Kivy and Android. All these components can then be bundled into an APK with the user’s Python script and different settings (icon, name, orientation etc.) to taste.

This is only the basic procedure, the APK can (and does) include much more than just these essentials. Amongst other things, most of the Python standard library is built in by default, and pure Python modules can be included easily so in general you can perform tasks using just the same libraries you would on the desktop. Libraries with compiled components are more complex, but can be built and included as long as python-for-android has a compilation recipe for them (or you provide your own) - these are often quite simple, just setting some compilation flags and running the normal build procedure, although some modules need additional patching. Python-for-android includes quite a few recipes by default, including very popular modules like numpy, sqlite3, twisted and even django!

The above is the basics of how python-for-android works but is far from the whole story, and you can check the documentation for more information about building your own APKs - in particular, we recommend using Buildozer, which gives python-for-android a more convenient interface and can manage some dependencies (in particular the Android SDKand NDK) automatically. This is also quite focused on Kivy itself, but we’re trying to move to make it easier for other projects to use the same toolchain - the core process of building and including Python should be similar, but there’s no need for the bootstrap app at the end to support only Kivy’s specific needs.

Calling Android APIs with PyJNIus

In normal Android application development, interaction with the Android API is an important part of how your app behaves - getting sensor data, creating notifications, vibrating, pausing and restarting, or just about anything else. Kivy takes care of the essentials for you, but many of these are things you’ll still want to manage yourself from Python. For this reason we have the PyJNIus project, also developed under the Kivy organisation, which automatically wraps Java code in a Python interface.

As a simple example, here’s the Python code to have an Android device vibrate for 10s:

from jnius import autoclass

# We need a reference to the Java activity running the current
# application, this reference is stored automatically by
# Kivy's PythonActivity bootstrap:
PythonActivity = autoclass('org.renpy.android.PythonActivity')
activity = PythonActivity.mActivity Context = autoclass('android.content.Context')
vibrator = activity.getSystemService(Context.VIBRATOR_SERVICE) vibrator.vibrate(10000) # the argument is in milliseconds

If you’re familiar with the Android API, you’ll notice that this is very similar to the Java code you’d use for the same task; PyJNIus just lets us call the same API directly from Python. Most of the Android API can be called from Python in the same way, letting you achieve the same things as a normal Java application.

The main disadvantages of using PyJNIus directly are that it requires some understanding of how the Android API is structured, and that it is quite verbose - though the latter just reflects the nature of the equivalent Java code. For this reason, the Kivy project set includes Plyer.

Plyer: A platform-independent API for platform-specific features

The Plyer project takes a step back from the specific implementation details of individual platforms in order to try to create a simple, pythonic interface for a subset of (mostly) shared functionality. For instance, the vibration example above would become

from plyer.vibrator import vibrate
vibrate(10) # in Plyer, the argument is in seconds

Further, Plyer is not just for Android but would try to do something appropriate on any of its supported platforms - currently Android, iOS, Linux, Windows and OS X (on iOS,PyOBJus fulfils a similar role to PyJNIus on Android). The vibrator is actually a bad example as only Android is currently implemented, but other APIs such as checking the battery (from plyer import battery; print(battery.status)) or text-to-speech (from plyer import tts; tts.speak('hello world')) would already work on both desktop and mobile devices, and others such as the compass or gyroscope sensors or sending SMS messages would work on both Android and iOS.

Plyer is very much under development, with new API wrapper contributions very welcome, and is the subject of a (second) GSoC project this year. We hope that it will become increasingly feature-complete.

Not just for Kivy

All of these tools have been shaped in their current form by the needs of Kivy, but are really more generic Python tools; Plyer specifically avoids any Kivy dependency, and PyJNIus only makes an assumption about how to access the JNI environment on Android. We hope that these tools can be more generally useful to anyone running Python on Android; for instance, you can already experiment with PyJNIus using the QPython Android app. Python-for-android is more tied to Kivy’s current toolchain but this is a detail under review, and we’re happy to discuss the details of Android compilation with anyone interested.

Overall, a lot is possible with Python on Android, despite how different the Python environment is to the Java development that is directly targeted. But there’s much more that could be done - if you’re interested, now is a great time to dive in!

Python on Android的更多相关文章

  1. 收藏的技术文章链接(ubuntu,python,android等)

    我的收藏 他山之石,可以攻玉 转载请注明出处:https://ahangchen.gitbooks.io/windy-afternoon/content/ 开发过程中收藏在Chrome书签栏里的技术文 ...

  2. uiautomator2 使用Python测试 Android应用

    GitHub地址:https://github.com/openatx/uiautomator2 介绍 uiautomator2 是一个可以使用Python对Android设备进行UI自动化的库.其底 ...

  3. 【Android】让Python在Android系统上飞一会儿

    第一节 在手机上配置Python运行环境 1.下载和安装 Scripting Layer for Android (SL4A) Scripting Layer for Android (SL4A) 是 ...

  4. 转 让Python在Android系统上飞一会儿

    让Python在Android系统上飞一会儿 地址: http://blog.csdn.net/ccwwff/article/details/6208260

  5. Python进行Android开发步骤

    移动应用开发 1. 建立开发环境 下载软件开发包(SDK):        http://developer.android.com/sdk/index.html        adt-bundle- ...

  6. 用python开发android应用 【转载】

    用python开发android应用 [转载] 转载自:http://www.miui.com/thread-995114-1-1.html Python是动态语言,比较简洁.Android不直接支持 ...

  7. python for android : BeautifulSoup 有 bug

    BeautifulSoup 善于网页数据分析 .可是 python for android : BeautifulSoup 有 bug , text = h4.a.text 仅仅能取得 None,因此 ...

  8. Python 制作Android开发 所需的适配不同分辨率的套图

    使用Python做起工具来还真是爽,简单,方便,快捷.今天忙活了一下,制作出一个比较实用的小工具. 自动化套图制作,适配不同屏幕 尤其是对于android开发来说,要适配不同屏幕就需要多套切图,那么. ...

  9. Python在Android系统上运行

    下载 Scripting Layer for Android (SL4A) https://github.com/damonkohler/sl4a https://www.tutorialspoint ...

随机推荐

  1. Java高级--Java线程运行栈信息的获取 getStackTrace()

    我们在Java程序中使用日志功能(JDK Log或者Log4J)的时候,会发现Log系统会自动帮我们打印出丰富的信息,格式一般如下:为了免去解析StackTrace字符串的麻烦,JDK1.4引入了一个 ...

  2. mybatis13 resultMap

    resultMap(入门) resultType :指定输出结果的类型(pojo.简单类型.hashmap..),将sql查询结果映射为java对象 . 使用resultType注意:sql查询的列名 ...

  3. 使用dom4j对xml文件进行增删改查

    1.使用dom4j技术对dom_demo.xml进行增删改查 首选要下载dom4j的jar包 在官网上找不到,网上搜索了一下在这个链接:http://sourceforge.net/projects/ ...

  4. c语言输入输出

    一 #include "stdio.h"int main(){ FILE *fp; int ninzu=0; char name[100]; double hsum=0.0; do ...

  5. HDU 4336 Card Collector(容斥)

    题意:要收集n种卡片,每种卡片能收集到的概率位pi,求收集完这n种卡片的期望.其中sigma{pi} <=1; 思路:容斥原理.就是一加一减,那么如何算期望呢.如果用二进制表示,0表示未收集到, ...

  6. 第一篇:APUE-操作系统IO模型

    操作系统IO模型   操作系统IO模型 声明:如下内容是根据APUE和mycat两本著作中关于I/O模式的一些内容加上自己的一些理解整理而成,仅供学习使用. 本节内容 UNIX下可用的五种I/O模型 ...

  7. WPF 格式化输出- IValueConverter接口的使用

    以前在用ASP.NET 做B/S系统时,可以方便地在GRIDVIEW DATAList等数据控件中,使用自定义的代码逻辑,比如 使用 <%# GetBalance(custID) %> 这 ...

  8. [XML] ResourceManager一个操作Resource的帮助类 (转载)

    点击下载 ResourceManager.zip /// <summary> /// 类说明:Assistant /// 编 码 人:苏飞 /// 联系方式:361983679 /// 更 ...

  9. 深入理解自定义ListView

    深入理解自定义ListView ListView原理 他是一个系统的原生控件,用列表的形式来显示内容.如果内容过过有1000条左右,我们可以通过手势的上下滑动来查看数据.ListView也不是爆出OO ...

  10. js基础知识之_入门变量和运算符

    js页面效果学习 (轮播图,文字滚动效果等等) javascript能来做什么 1.数据验证 2.将动态的内容写入网页中(ajax) 3.可以对时间做出响应 4.可以读写html中的内容 5.可以检测 ...