Python on Android

时间:2023-02-10 10:54:20

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. svm心得体会(2)

    昨天和李老师讨论一会还是有所得的,虽然我发誓要早睡又泡汤了,又无原则晚睡了. 总结一下有这么几点心得认识: (1)MATLAB再带的svm工具箱得不到参数,必须在路径中添加libsvm工具箱,安装在M ...

  2. YY一下微信线下支付的场景

    在上一篇文章里面提到了 <跨行清算的实现原理>,这次来分析一下线下支付的场景和流程. 今天看到一篇文章:http://www.huxiu.com/article/23248/1.html? ...

  3. touches

    e.touches.length//有多少个手指接触头

  4. caffe初步实践---------使用训练好的模型完成语义分割任务

    caffe刚刚安装配置结束,乘热打铁! (一)环境准备 前面我有两篇文章写到caffe的搭建,第一篇cpu only ,第二篇是在服务器上搭建的,其中第二篇因为硬件环境更佳我们的步骤稍显复杂.其实,第 ...

  5. C&num;中调用存储过程:带输入输出参数

    using (SqlConnection conn = new SqlConnection(this.GetConnectionString(this.WMPDBName))) { SqlComman ...

  6. Linux功能-验证网络配置

    显示IP地址.设别和MAC地址等信息# ip addr show br0 订正:以下截图中硬件mac地址为第三行的"link/ether"一行所在的地方. ip命令可用在网络性能方 ...

  7. Request、Request&period;Form、Request&period;QueryString 用法的区别

    Request.Form:获取以POST方式提交的数据. Request.QueryString:获取地址栏参数(以GET方式提交的数据). Request:包含以上两种方式(优先获取GET方式提交的 ...

  8. maven系列(1)-maven的介绍与安装

    maven的介绍 maven是大名鼎鼎的Apache下的java构建工具. Apache Maven is a software project management and comprehensio ...

  9. git 使用事项

    基本安装可查看 http://help.github.com 如果删除了本地的文件,要恢复相关文件,在github存在(别人增加的),则:git pull <远程主机名> <远程分支 ...

  10. Android 动态注册JNI函数

    1.JNI函数注册方式 在Android开发中,由于种种原因我们需要调用C/C++代码,在这个时候我们就需要使用jni了, jni在使用时要对定义的函数进行注册,这样java才能通过native关键字 ...