6. Android で Python を使う
***************************

Android における Pythonは、デスクトッププラットフォームにおける Python
とは異なります。 デスクトッププラットフォームでは、 Python は一般的に
コンピューターのどのユーザーでも使えるシステムリソースとしてインストー
ルされます。そして、ユーザーは **python** 実行可能ファイルを実行して対
話型プロンプトにコマンドを入力したり、 Python スクリプトを実行したりし
て、 Python を使用することができるのです。

Android においては、システムリソースとしてのインストールという概念はあ
りません。ソフトウェア配布が可能なのは、 "アプリ" だけです。また、
**python** 実行可能ファイルの実行したり、 Python の REPL を使用したり
する、コンソールも存在しません。

このため、 Python を Android 上で使うただ一つの方法は、埋め込みモード
、つまり、ネイティブ Android アプリケーションを書き、 "libpython" を使
用して Python インタープリタを埋め込み、そして Python 埋め込み API を
使用して Python コードを呼び出すことです。 それにより、完全な Python
インタープリタ、標準ライブラリ、及び Python のコードが、アプリにパッケ
ージ化され、独自の私的用途に使用されます。

Python の 標準ライブラリには、 Android におけるいくつかの重要な省略や
制限があります。詳細は API 利用可能性ガイド を参照してください。


6.1. Android アプリに Python を追加する
=======================================

ほとんどのアプリ開発者は、次のツールの一つを使用するべきです。これによ
り、はるかに簡単な体験が提供されます:

* BeeWare プロジェクトの Briefcase

* 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.

* First, acquire a build of Python for Android:

  * The easiest way is to download an Android release from python.org.
    The "prefix" directory mentioned below is at the top level of the
    package.

  * Or if you want to build it yourself, follow the instructions in
    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":

  * In your JNI libraries:

    * "libpython*.*.so"

    * "lib*_python.so" (external libraries such as OpenSSL)

  * In your assets:

    * "python*.*" (the Python standard library)

    * "python*.*/site-packages" (your own Python code)

* 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 packages can be built for Android as wheels and released on
PyPI. The recommended tool for doing this is cibuildwheel, which
automates all the details of setting up a cross-compilation
environment, building the wheel, and testing it on an emulator.
