6. 在Android上使用 Python
*************************

Python 在 Android 上与桌面平台上不同。 在桌面平台上，Python 通常是作为
系统资源安装的，该计算机的任何用户都可以使用。 然后，用户通过运行
**python** 可执行文件并在交互提示符中输入命令，或运行脚本。

在安卓系统中，没有将安装作为系统资源的概念。 软件分发的唯一单位是"应用
程序"。 也没有可以运行 **python** 可执行文件或与 Python REPL 交互的控
制台。

因此，在 Android 上使用 Python 的唯一方式是嵌入模式，即编写本地
Android 应用，使用 "libpython" 嵌入 Python 解释器，并使用 Python 嵌入
API 调用 Python 代码。然后，完整的 Python 解释器、标准库和所有 Python
代码都会打包到您的应用程序中，供其单独使用。

Python 标准库在 Android 上有一些明显的遗漏和限制。 详情参见 API 可用性
指南。


6.1. 将 Python 添加到 Android 应用
==================================

大多数开发者应当使用下列工具之一，它们将提供更便捷的体验：

* Briefcase，来自 BeeWare 项目

* 来自 Kivy 项目的 Buildozer

* Chaquopy

* pyqtdeploy

* Termux

If you're sure you want to do all of this manually, read on. You can
use the testbed app as a guide; each step below contains a link to the
relevant file.

* 首先，获取针对 Android 的 Python 构建版：

  * 最简单的方式是从 python.org 下载 Android 发布版。 下面提及的
    "prefix" 目录将位于软件包的最高层级。

  * Or if you want to build it yourself, follow the instructions in
    Platforms/Android/README.md. The "prefix" directory will be
    created under "cross-build/*HOST*".

* Add code to your build.gradle file to copy the following items into
  your project. All except your own Python code can be copied from
  "prefix/lib":

  * 在 JNI 库中:

    * "libpython*.*.so"

    * "lib*_python.so" （外部库，如 OpenSSL）

  * 在您的资源文件中：

    * "python*.*" (Python 标准库)

    * "python*.*/site-packages" （您自己的 Python 代码）

* Add code to your app to extract the assets to the filesystem.

* Add code to your app to start Python in embedded mode. This will
  need to be C code called via JNI.


6.2. 为 Android 构建 Python 软件包
==================================

Python 软件包可以作为针对 Android 构建的 wheel 文件并在 PyPI 上发布。
完成此任务的推荐工具是 cibuildwheel，它将自动化设置交叉编译环境、构建
wheel 以及在模拟器上进行测试等所有细节。
