### Install Python Package in Recipe Source: https://python-for-android.readthedocs.io/en/latest/recipes.html This method automates the installation of a Python package using `setup.py install`. Ensure the hostpython path is correctly set for installations. ```python def build_arch(self, arch): super().build_arch(arch) self.install_python_package() def install_python_package(self): '''Automate the installation of a Python package (or a cython package where the cython components are pre-built).''' arch = self.filtered_archs[0] env = self.get_recipe_env(arch) info('Installing {} into site-packages'.format(self.name)) with current_directory(self.get_build_dir(arch.arch)): hostpython = sh.Command(self.ctx.hostpython) shprint(hostpython, 'setup.py', 'install', '-O2', _env=env) ``` -------------------------------- ### Install python-for-android from GitHub Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Install the master branch of python-for-android directly from its GitHub repository. ```bash pip install git+https://github.com/kivy/python-for-android.git ``` -------------------------------- ### Install p4a Prerequisites on Ubuntu Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Installs essential system dependencies for python-for-android on Ubuntu-based Linux distributions using apt-get. ```bash sudo apt-get update sudo apt-get install -y \ ant \ autoconf \ automake \ autopoint \ ccache \ cmake \ g++ \ gcc \ git \ lbzip2 \ libffi-dev \ libltdl-dev \ libtool \ libssl-dev \ make \ openjdk-17-jdk \ patch \ pkg-config \ python3 \ python3-dev \ python3-pip \ python3-venv \ sudo \ unzip \ wget \ zip ``` -------------------------------- ### Starting a Custom Service Source: https://python-for-android.readthedocs.io/en/latest/services.html Use this code to start a custom service from your application. Ensure 'your.package.domain.package.name' is replaced with your actual package identifier and 'ServiceMyservice' with your service class name. ```python from jnius import autoclass service = autoclass('your.package.name.ServiceMyservice') mActivity = autoclass('org.kivy.android.PythonActivity').mActivity argument = '' service.start(mActivity, argument) ``` -------------------------------- ### Configuration File Options Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Example of options that can be placed in a `.p4a` configuration file in the current directory. These options are automatically applied to the command line. ```bash --dist_name my_example --android_api 27 --requirements kivy,openssl ``` -------------------------------- ### Starting a Service with Notification Customization Source: https://python-for-android.readthedocs.io/en/latest/services.html This snippet demonstrates how to start a service and customize the notification that appears for it. Replace 'small_icon', 'title', and 'content' with your desired resource name and strings. ```python service.start(mActivity, 'small_icon', 'title', 'content' , argument) ``` -------------------------------- ### Install python-for-android using pip Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Install the latest stable version of python-for-android from PyPI. ```bash pip install python-for-android ``` -------------------------------- ### Install Android SDK Build Tools Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Installs a specific version of the Android SDK build-tools. Version 28.0.2 is recommended. ```bash $SDK_DIR/tools/bin/sdkmanager "build-tools;28.0.2" ``` -------------------------------- ### Install Android SDK Platform Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Installs the specified Android API platform using the sdkmanager. The recommended target API level is 27. ```bash $SDK_DIR/tools/bin/sdkmanager "platforms;android-27" ``` -------------------------------- ### Include package data in APK via setup.py Source: https://python-for-android.readthedocs.io/en/latest/distutils.html Specify files to be included in the APK using the `package_data` argument in `setup.py`. This example includes all .py and .png files in the `testapp` folder. ```python from distutils.core import setup from setuptools import find_packages setup( name='testapp_setup', version='1.1', description='p4a setup.py example', author='Your Name', author_email='youremail@address.com', packages=find_packages(), options=options, package_data={'testapp': ['*.py', '*.png']} ) ``` -------------------------------- ### Run setup.py inside p4a APK build Source: https://python-for-android.readthedocs.io/en/latest/distutils.html Enable this functionality with the `--use-setup-py` flag. Note that only your `main.py` from the app's `--private` data is copied into the APK; other files must be installed by `setup.py`. ```bash p4a apk --use-setup-py ``` -------------------------------- ### Add p4a arguments in setup.py using 'options' Source: https://python-for-android.readthedocs.io/en/latest/distutils.html Pass p4a arguments to the `setup` function via the `options` parameter. This allows arguments like `debug`, `requirements`, `android-api`, `ndk-dir`, and `dist-name` to be configured within `setup.py`. ```python from distutils.core import setup from setuptools import find_packages options = {'apk': {'debug': None, # use None for arguments that don't pass a value 'requirements': 'sdl2,pyjnius,kivy,python3', 'android-api': 19, 'ndk-dir': '/path/to/ndk', 'dist-name': 'bdisttest', }} packages = find_packages() print('packages are', packages) setup( name='testapp_setup', version='1.1', description='p4a setup.py example', author='Your Name', author_email='youremail@address.com', packages=find_packages(), options=options, package_data={'testapp': ['*.py', '*.png']} ) ``` -------------------------------- ### Install Python-for-Android from Local Clone Source: https://python-for-android.readthedocs.io/en/latest/testing_pull_requests.html Installs the python-for-android package using pip from a local repository clone. This allows testing changes directly from the pull request source. ```bash cd p4a-feature-fix-numpy pip3 install . --upgrade --user ``` -------------------------------- ### Start an Android Service Source: https://python-for-android.readthedocs.io/en/latest/services.html Use this function to start a background service. Ensure the 'android' module is included in your app requirements. The `title`, `description`, and `arg` parameters are used to configure the service. ```python import android android.start_service(title='service name', description='service description', arg='argument to service') ``` -------------------------------- ### Extract Python Installation Tarball Source: https://python-for-android.readthedocs.io/en/latest/troubleshooting.html The Python installation, which is ABI-specific, is packaged as 'libpybundle.so'. Extract this file to access the core Python bundle. ```bash tar xf libpybundle.so cd _python_bundle ls ``` -------------------------------- ### Working within the Build Directory Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Example of using the `current_directory` context manager to perform operations within the isolated build directory. This ensures files are written to the correct location. ```python from pythonforandroid.toolchain import current_directory def build_arch(self, arch): super().build_arch(arch) with current_directory(self.get_build_dir(arch.arch)): with open('example_file.txt', 'w') as fileh: fileh.write('This is written to a file within the build dir') ``` -------------------------------- ### Create a Vispy PythonRecipe Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Use PythonRecipe to install Python modules without compiled components. Specify version, URL, dependencies, and site_packages_name if it differs from the recipe name. ```python from pythonforandroid.recipe import PythonRecipe class VispyRecipe(PythonRecipe): version = 'master' url = 'https://github.com/vispy/vispy/archive/{version}.zip' depends = ['python3', 'numpy'] site_packages_name = 'vispy' recipe = VispyRecipe() ``` -------------------------------- ### Conditional Build Logic with should_build Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Implement the `should_build` method to control whether a recipe is built for a specific architecture. This example checks if the package already exists in site-packages. ```python def should_build(self, arch): name = self.site_packages_name if name is None: name = self.name if self.ctx.has_package(name): info('Python package already exists in site-packages') return False info('{} apparently isn\'t already in site-packages'.format(name)) return True ``` -------------------------------- ### CythonRecipe Build Methods Source: https://python-for-android.readthedocs.io/en/latest/recipes.html This code illustrates the build process for a CythonRecipe, including building Cython components and installing the Python package. It handles potential build failures and manual Cythonization. ```python def build_arch(self, arch): Recipe.build_arch(self, arch) # a hack to avoid calling # PythonRecipe.build_arch self.build_cython_components(arch) self.install_python_package() # this is the same as in a PythonRecipe def build_cython_components(self, arch): env = self.get_recipe_env(arch) with current_directory(self.get_build_dir(arch.arch)): hostpython = sh.Command(self.ctx.hostpython) # This first attempt *will* fail, because cython isn't # installed in the hostpython try: shprint(hostpython, 'setup.py', 'build_ext', _env=env) except sh.ErrorReturnCode_1: pass # ...so we manually run cython from the user's system shprint(sh.find, self.get_build_dir('armeabi'), '-iname', '*.pyx', '-exec', self.ctx.cython, '{}', ';', _env=env) # now cython has already been run so the build works shprint(hostpython, 'setup.py', 'build_ext', '-v', _env=env) # stripping debug symbols lowers the file size a lot build_lib = glob.glob('./build/lib*') shprint(sh.find, build_lib[0], '-name', '*.o', '-exec', env['STRIP'], '{}', ';', _env=env) ``` -------------------------------- ### Run FFmpeg Command Source: https://python-for-android.readthedocs.io/en/latest/apis.html Execute FFmpeg commands for tasks like video processing. This example performs a minimal sanity check to verify FFmpeg availability and executability. Ensure FFmpeg is included in your requirements. ```python import subprocess subprocess.run( ["ffmpeg", "-f", "lavfi", "-i", "testsrc", "-t", "1", "-f", "null", "-"], check=True ) ``` -------------------------------- ### Build APK with Python-for-Android from Pull Request Source: https://python-for-android.readthedocs.io/en/latest/testing_pull_requests.html Run the build of the apk via a freshly installed copy of python-for-android. Ensure you set the correct --ndk-dir and --sdk-dir paths. ```bash python3 setup.py apk \ --ndk-dir=/media/DEVEL/Android/android-ndk-r20 \ --sdk-dir=/media/DEVEL/Android/android-sdk-linux \ --android-api=36 \ --arch=arm64-v8a \ --debug ``` -------------------------------- ### Basic Recipe Declaration Source: https://python-for-android.readthedocs.io/en/latest/recipes.html This is a fundamental example of how to declare a recipe in python-for-android. It includes essential parameters like URL, version, md5sum, patches, dependencies, and conflicts. Ensure `recipe = YourRecipe()` is included for the recipe to be accessible. ```python class YourRecipe(Recipe): url = 'http://example.com/example-{version}.tar.gz' version = '2.0.3' md5sum = '4f3dc9a9d857734a488bcbefd9cd64ed' patches = ['some_fix.patch'] # Paths relative to the recipe dir depends = ['kivy', 'sdl2'] # These are just examples conflicts = ['generickndkbuild'] recipe = YourRecipe() ``` -------------------------------- ### Download Headers for Private GitHub Repository Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Specify additional headers for downloading archives, such as authentication tokens for private repositories. This example shows the format for the `download_headers` property in a recipe. ```python [('Authorization', 'token '), ('Accept', 'application/vnd.github+json')] ``` -------------------------------- ### Define a PyProjectRecipe Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Use PyProjectRecipe for Python packages with pyproject.toml. It builds and installs packages as wheels. Specify version, URL, and dependencies. ```python from pythonforandroid.recipe import PyProjectRecipe class ExampleRecipe(PyProjectRecipe): version = '1.2.3' url = 'https://example.com/example-{version}.tar.gz' depends = ['pycparser', 'libffi'] recipe = ExampleRecipe() ``` -------------------------------- ### Example CythonRecipe for Kivy Source: https://python-for-android.readthedocs.io/en/latest/recipes.html This snippet shows how to define a CythonRecipe for the Kivy module. It specifies the version, URL, name, and dependencies. ```python class KivyRecipe(CythonRecipe): version = 'stable' url = 'https://github.com/kivy/kivy/archive/{version}.zip' name = 'kivy' depends = ['sdl2', 'pyjnius'] recipe = KivyRecipe() ``` -------------------------------- ### NDKRecipe Example for SDL2_ttf Source: https://python-for-android.readthedocs.io/en/latest/recipes.html This recipe demonstrates how to use NDKRecipe to integrate a C/C++ library like SDL2_ttf into an Android project's JNI directory. It specifies the version and download URL for the library. ```python class LibSDL2TTF(NDKRecipe): version = '2.0.12' url = 'https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-{version}.tar.gz' dir_name = 'SDL2_ttf' recipe = LibSDL2TTF() ``` -------------------------------- ### Get Storage Paths Source: https://python-for-android.readthedocs.io/en/latest/apis.html Use these functions to query common storage paths on Android devices. Ensure the 'android' module is added to your project's requirements. ```python from android.storage import app_storage_path settings_path = app_storage_path() from android.storage import primary_external_storage_path primary_ext_storage = primary_external_storage_path() from android.storage import secondary_external_storage_path secondary_ext_storage = secondary_external_storage_path() ``` -------------------------------- ### Overriding get_recipe_env for Custom Variables Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Override `get_recipe_env` to add custom environment variables. This example sets `USE_SDL2` and `KIVY_SDL2_PATH` for Kivy compilation. ```python def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env['USE_SDL2'] = '1' env['KIVY_SDL2_PATH'] = ':'.join([ join(self.ctx.bootstrap.build_dir, 'jni', 'SDL', 'include'), join(self.ctx.bootstrap.build_dir, 'jni', 'SDL2_image'), join(self.ctx.bootstrap.build_dir, 'jni', 'SDL2_mixer'), join(self.ctx.bootstrap.build_dir, 'jni', 'SDL2_ttf'), ]) return env ``` -------------------------------- ### Configure Buildozer for Custom Python-for-Android Source Source: https://python-for-android.readthedocs.io/en/latest/testing_pull_requests.html Edit your buildozer.spec file to point to the custom python-for-android source directory. This allows testing pull requests without installing python-for-android directly. ```ini p4a.source_dir = /home/user/p4a_pull_requests/p4a-feature-fix-numpy ``` -------------------------------- ### Handle Back Button Input Source: https://python-for-android.readthedocs.io/en/latest/apis.html Override the default back button behavior in Kivy applications. This example binds the on_keyboard event to intercept the back button press (keycode 27) and return True to prevent app shutdown. ```python from kivy.core.window import Window class YourApp(App): def build(self): Window.bind(on_keyboard=self.key_input) return Widget() # your root widget here as normal def key_input(self, window, key, scancode, codepoint, modifier): if key == 27: return True # override the default behaviour else: # the key now does nothing return False ``` -------------------------------- ### Add p4a arguments in setup.cfg Source: https://python-for-android.readthedocs.io/en/latest/distutils.html Configure p4a arguments within the `setup.cfg` file using the standard distutils INI format. Arguments are placed under the `[apk]` section. ```ini [apk] argument=value requirements=sdl2,kivy ``` -------------------------------- ### Call p4a from setup.py Source: https://python-for-android.readthedocs.io/en/latest/distutils.html Invoke p4a commands directly from your setup.py script. This method integrates p4a with distutils and setup.py. ```bash python setup.py apk ``` -------------------------------- ### List Available Recipes Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html View all available recipes for python-for-android. This command helps in understanding the build components. ```bash p4a recipes ``` -------------------------------- ### Build a WebView Application APK Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Build an APK for a WebView application. Specify the webview bootstrap and include all required dependencies. The --port argument specifies the app's serving port. ```bash p4a apk --private $HOME/code/myapp --package=org.example.myapp --name "My WebView Application" --version 0.1 --bootstrap=webview --requirements=flask --port=5000 ``` -------------------------------- ### Build a Kivy or SDL2 APK Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Use this command to build an APK for Kivy or SDL2 applications. Ensure all necessary libraries and dependencies are listed in the --requirements argument. ```bash p4a apk --private $HOME/code/myapp --package=org.example.myapp --name "My application" --version 0.1 --bootstrap=sdl2 --requirements=python3,kivy ``` -------------------------------- ### Build Docker Image Source: https://python-for-android.readthedocs.io/en/latest/docker.html Build the Docker image named 'p4a' using the Dockerfile in the repository. Ensure you are in the root directory of the cloned repository. ```bash docker build --tag p4a . ``` -------------------------------- ### List APK Files Source: https://python-for-android.readthedocs.io/en/latest/docker.html List the files in the 'testapps' directory to find the generated APK file after the build process. ```bash ls -lah testapps ``` -------------------------------- ### Run Buildozer with Custom App Source: https://python-for-android.readthedocs.io/en/latest/testing_pull_requests.html Execute your buildozer command as usual after configuring the custom p4a.source_dir. This method allows testing pull requests with Buildozer. ```bash buildozer android debug p4a --dist-name=dist-test-feature-fix-numpy ``` -------------------------------- ### Clean Builds and Distributions Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Run this command to clean only the build artifacts, avoiding the need to re-download dependencies. This is a faster way to clean than 'clean_all'. ```bash p4a clean_builds && p4a clean_dists ``` -------------------------------- ### List Top-Level APK Files Source: https://python-for-android.readthedocs.io/en/latest/troubleshooting.html After unzipping an APK, this command lists the standard top-level files contained within it. ```bash $ ls AndroidManifest.xml classes.dex META-INF res assets lib YourApk.apk resources.arsc ``` -------------------------------- ### List Available Distributions Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Display all currently available distributions managed by python-for-android. This helps in managing build environments. ```bash p4a distributions ``` -------------------------------- ### Core Recipe Build Methods Source: https://python-for-android.readthedocs.io/en/latest/recipes.html The three core methods for the build process: `prebuild_arch`, `build_arch`, and `postbuild_arch`. These methods are executed in sequence during the build. ```python def prebuild_arch(self, arch): super().prebuild_arch(arch) # Do any pre-initialisation def build_arch(self, arch): super().build_arch(arch) # Do the main recipe build def postbuild_arch(self, arch): super().build_arch(arch) # Do any clearing up ``` -------------------------------- ### Create Private Recipe Directory Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Set up a directory structure for a custom 'private' recipe. This allows for application-specific recipe modifications. ```bash mkdir -p p4a-recipes/myrecipe touch p4a-recipes/myrecipe/__init__.py ``` -------------------------------- ### Clean All Downloads and Builds Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Use this command to completely reset the build environment by cleaning all downloaded dependencies and build artifacts. This is useful for troubleshooting. ```bash p4a clean_all ``` -------------------------------- ### Clean and Rebuild Recipe Build Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Clean the build for a specific recipe or all distributions, then rebuild. Useful for developers contributing to recipes. ```bash p4a clean_recipe_build RECIPENAME p4a clean_dists # then rebuild your distribution ``` -------------------------------- ### Unpack APK Contents Source: https://python-for-android.readthedocs.io/en/latest/troubleshooting.html APKs are zip files. Use the unzip command to extract the contents of an APK to inspect its structure and files. ```bash unzip YourApk.apk ``` -------------------------------- ### Build a Service Library Archive (AAR) Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Create an Android Archive (.aar) containing an Android service. This requires specifying the service_library bootstrap, service entry point, requirements, and target architectures. ```bash p4a aar --private $HOME/code/myapp --package=org.example.myapp --name "My library" --version 0.1 --bootstrap=service_library --requirements=python3 --release --service=myservice:service.py --arch=arm64-v8a --arch=armeabi-v7a ``` -------------------------------- ### Run Docker Container for App Build Source: https://python-for-android.readthedocs.io/en/latest/docker.html Execute a Docker container from the 'p4a' image to build an Android application. This command mounts the local 'testapps' directory and activates a virtual environment within the container to run the build script. ```bash docker run \ --interactive \ --tty \ --volume ".../testapps":/home/user/testapps \ p4a sh -c \ '. venv/bin/activate \ && cd testapps \ && python setup_testapp_python3.py apk \ --sdk-dir $ANDROID_SDK_HOME \ --ndk-dir $ANDROID_NDK_HOME' ``` -------------------------------- ### Build APK Using Python-for-Android Commands Source: https://python-for-android.readthedocs.io/en/latest/testing_pull_requests.html Builds an APK using the python-for-android toolchain directly from the cloned pull request files. Ensure you provide correct paths for NDK and SDK directories. ```bash cd p4a-feature-fix-numpy PYTHONPATH=. python3 -m pythonforandroid.toolchain apk \ --private=testapps/on_device_unit_tests/test_app \ --dist-name=dist_unit_tests_app_pycryptodome \ --package=org.kivy \ --name=unit_tests_app_pycryptodome \ --version=0.1 \ --requirements=sdl2,pyjnius,kivy,python3,pycryptodome \ --ndk-dir=/media/DEVEL/Android/android-ndk-r20 \ --sdk-dir=/media/DEVEL/Android/android-sdk-linux \ --android-api=36 \ --arch=arm64-v8a \ --permission=VIBRATE \ --debug ``` -------------------------------- ### Setting Build Environment Variables Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Retrieve and set appropriate environment variables for compilation using `get_recipe_env`. This ensures correct linking and target architecture. ```python def build_arch(self, arch): super().build_arch(arch) env = self.get_recipe_env(arch) sh.echo('$PATH', _env=env) # Will print the PATH entry from the # env dict ``` -------------------------------- ### General Python for Android Recipe Template Source: https://python-for-android.readthedocs.io/en/latest/recipes.html A comprehensive template for creating custom recipes. It includes placeholders for version, URL, dependencies, conflicts, and overrides for various build stages like prebuild, build, and postbuild. ```python from pythonforandroid.toolchain import Recipe, shprint, current_directory from os.path import exists, join import sh import glob class YourRecipe(Recipe): # This could also inherit from PythonRecipe etc. if you want to # use their pre-written build processes version = 'some_version_string' url = 'http://example.com/example-{version}.tar.gz' # {version} will be replaced with self.version when downloading depends = ['python3', 'numpy'] # A list of any other recipe names # that must be built before this # one conflicts = [] # A list of any recipe names that cannot be built # alongside this one def get_recipe_env(self, arch): env = super().get_recipe_env(arch) # Manipulate the env here if you want return env def should_build(self, arch): # Add a check for whether the recipe is already built if you # want, and return False if it is. return True def prebuild_arch(self, arch): super().prebuild_arch(arch) # Do any extra prebuilding you want, e.g.: self.apply_patch('path/to/patch.patch') def build_arch(self, arch): super().build_arch(arch) # Build the code. Make sure to use the right build dir, e.g. with current_directory(self.get_build_dir(arch.arch)): sh.ls('-lathr') # Or run some commands that actually do # something def postbuild_arch(self, arch): super().prebuild_arch(arch) # Do anything you want after the build, e.g. deleting # unnecessary files such as documentation recipe = YourRecipe() ``` -------------------------------- ### List Connected Devices with adb Source: https://python-for-android.readthedocs.io/en/latest/troubleshooting.html Uses the adb command to list connected Android devices. This is useful for verifying device connectivity before performing other debugging tasks. ```bash python-for-android adb devices ``` -------------------------------- ### Applying Patches to Recipes Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Declare patches to be applied to recipes. Paths are relative to the recipe file and patches are applied only once. ```python patches = ['some_fix.patch', 'another_fix.patch'] ``` -------------------------------- ### Blacklist Requirements for APK Size Optimization Source: https://python-for-android.readthedocs.io/en/latest/buildoptions.html Use the `--blacklist-requirements` option with the p4a command to exclude specific Python modules and reduce the final APK size. This is useful when certain standard library components are not needed in your application. ```bash p4a apk ... --blacklist-requirements=sqlite3 ``` -------------------------------- ### Specify Distribution Name Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Force the reuse of an existing distribution by specifying its name. This ensures consistent build directories and avoids redundant disk space usage. ```bash p4a apk --dist_name=myproject ... ``` -------------------------------- ### Clone Python for Android Repository Source: https://python-for-android.readthedocs.io/en/latest/docker.html Clone the official Python for Android repository to your local machine. This is the first step before building the Docker image. ```bash git clone https://github.com/kivy/python-for-android ``` -------------------------------- ### Configure Android Environment Variables Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Sets essential environment variables for the Android SDK, NDK, and API versions in your shell configuration. ```bash # Adjust the paths! export ANDROIDSDK="$HOME/Documents/android-sdk-27" export ANDROIDNDK="$HOME/Documents/android-ndk-r23b" export ANDROIDAPI="36" # Target API version of your application export NDKAPI="21" # Minimum supported API version of your application export ANDROIDNDKVER="r10e" # Version of the NDK you installed ``` -------------------------------- ### Add User Remote and Fetch Source: https://python-for-android.readthedocs.io/en/latest/testing_pull_requests.html Adds a user's fork as a remote repository and fetches their pull request branch. This is useful for frequently testing contributions from a specific user. ```bash git remote add obiwankenobi https://github.com/obiwankenobi/python-for-android.git git fetch obiwankenobi git checkout obiwankenobi/feature-fix-numpy ``` -------------------------------- ### List Contents of Python Bundle Source: https://python-for-android.readthedocs.io/en/latest/troubleshooting.html Shows the contents of the extracted Python bundle, including modules, site-packages, and stdlib.zip, which constitute the Python environment shipped with the APK. ```bash modules site-packages stdlib.zip ``` -------------------------------- ### Export Android App Bundle (AAB) Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Generate an Android App Bundle (.aab) for distribution on Google Play. This command handles the necessary work for Google Play's requirements, including specifying architectures. ```bash p4a aab --private $HOME/code/myapp --package=org.example.myapp --name="My App" --version 0.1 --bootstrap=sdl2 --requirements=python3,kivy --arch=arm64-v8a --arch=armeabi-v7a --release ``` -------------------------------- ### Request Runtime Permissions Source: https://python-for-android.readthedocs.io/en/latest/apis.html Use this snippet to request necessary runtime permissions for accessing device features like the SD card or camera. Ensure the android module is not blacklisted. ```python from android.permissions import request_permissions, Permission request_permissions([Permission.WRITE_EXTERNAL_STORAGE]) ``` -------------------------------- ### Copying Generated Libraries Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Manually copy generated .so files to the correct lib cache directory for inclusion in the Android project. ```python def build_arch(self, arch): do_the_build() # e.g. running ./configure and make import shutil shutil.copyfile('a_generated_binary.so', self.ctx.get_libs_dir(arch.arch)) ``` -------------------------------- ### Override default p4a arguments via command line Source: https://python-for-android.readthedocs.io/en/latest/distutils.html Manually override automatic arguments like app name and version when running `python setup.py apk`. The Android package name defaults to `org.test.lowercaseappname` if not explicitly set. ```bash python setup.py apk --name="Testapp Setup" --version=2.5 ``` -------------------------------- ### Using shprint for Process Information Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Utilize the `shprint` helper function to display process information and status during compilation. ```python from pythonforandroid.toolchain import shprint shprint(sh.echo, '$PATH', _env=env) ``` -------------------------------- ### List Extracted User App Data Source: https://python-for-android.readthedocs.io/en/latest/troubleshooting.html Displays the contents of the extracted 'private.tar' file, showing the user application's data, including Python code, assets, and configuration files. ```bash $ ls README.txt android.txt icon.png main.pyc p4a_env_vars.txt particle.png private.tar touchtracer.kv ``` -------------------------------- ### SDL2 Bootstrap Class Definition Source: https://python-for-android.readthedocs.io/en/latest/bootstraps.html Defines a new bootstrap class for SDL2 integration. It specifies the bootstrap name and its recipe dependencies. The `run_distribute` method is responsible for the core logic of creating the Android project build directory. ```python from pythonforandroid.toolchain import Bootstrap, shprint, current_directory, info, warning, ArchAndroid, logger, info_main, which from os.path import join, exists from os import walk import glob import sh class SDL2Bootstrap(Bootstrap): name = 'sdl2' recipe_depends = ['sdl2'] def run_distribute(self): # much work is done here... ``` -------------------------------- ### Download Headers Environment Variable Format Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Format for the `DOWNLOAD_HEADERS_my-package-name` environment variable, which should be a JSON-formatted set of values for download headers. ```bash > [[“Authorization”,”token ”],[“Accept”, “application/vnd.github+json”]] ``` -------------------------------- ### Clean All Distributions Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Remove all distributions created by python-for-android. Use with caution as this action is irreversible. ```bash p4a clean_dists ``` -------------------------------- ### Override Recipe Source Directory Source: https://python-for-android.readthedocs.io/en/latest/quickstart.html Set an environment variable to point to a local directory for a specific recipe's source. This is useful for testing custom branches or local modifications. ```bash export P4A_kivy_DIR=/home/username/kivy ``` -------------------------------- ### Set Dark Mode Change Listener Source: https://python-for-android.readthedocs.io/en/latest/apis.html Register a callback function to be notified when the system's dark mode setting changes. The callback receives a boolean indicating the current dark mode state. ```python from android.darkmode import set_dark_mode_listener def on_dark_mode_changed(is_dark_mode): if is_dark_mode: print('Dark mode is now enabled') # Update your app's theme to dark mode else: print('Dark mode is now disabled') # Update your app's theme to light mode # Register the listener set_dark_mode_listener(on_dark_mode_changed) ``` -------------------------------- ### Registering Activity Lifecycle Callbacks Source: https://python-for-android.readthedocs.io/en/latest/apis.html Allows binding callbacks to Android's Activity lifecycle state changes. Callbacks correspond to `ActivityLifecycleCallbacks` method names. ```APIDOC ## android.activity.register_activity_lifecycle_callbacks ### Description Registers callbacks for Android Activity lifecycle state changes. ### Method `register_activity_lifecycle_callbacks(_callbackname=callback_ , _..._)` ### Parameters * `_callbackname` (string) - The name of the lifecycle callback (e.g., 'onActivityStarted', 'onActivityStopped'). * `callback` - The function or method to be called for the specified lifecycle event. ### Note Some callbacks like `onActivityCreated` are not useful in the Python app as they run before the Python app is active. ### Example: ```python from android.activity import register_activity_lifecycle_callbacks def on_activity_stopped(activity): print('Activity is stopping') register_activity_lifecycle_callbacks( onActivityStopped=on_activity_stopped, ) ``` ``` -------------------------------- ### Set Immersive Mode Source: https://python-for-android.readthedocs.io/en/latest/apis.html Enable or disable immersive mode to hide system bars for a full-screen experience. Optionally remove system-enforced contrast behind peeked bars. ```python from android.display_cutout import set_immersive_mode set_immersive_mode( False, # hide_status: True explicitly targets hiding the top status bar, False leaves it visible False, # hide_nav: True explicitly targets hiding the bottom navigation bar/gestural pill, False leaves it visible True, # remove_contrast: True disables the default system-enforced background scrim/contrast behind the bars, ensuring complete transparency when they peek ) ``` -------------------------------- ### Extract User App Data from APK Source: https://python-for-android.readthedocs.io/en/latest/troubleshooting.html The user app data is packaged in 'private.tar' within the assets folder of the APK. Extract this tarball to access your application's code and assets. ```bash cd assets ls private.tar ``` ```bash tar xf private.tar ``` -------------------------------- ### Conditional Patch Application Source: https://python-for-android.readthedocs.io/en/latest/recipes.html Use helper functions like `is_arch` and `will_build` to apply patches based on specific conditions. Custom conditions can be provided as functions. ```python from pythonforandroid.patching import will_build, is_arch ... class YourRecipe(Recipe): patches = [('x86_patch.patch', is_arch('x86')), ('sdl2_compatibility.patch', will_build('sdl2'))] ... ``` -------------------------------- ### Observing Activity Results and New Intents Source: https://python-for-android.readthedocs.io/en/latest/apis.html Allows binding callbacks to Android's `onActivityResult` and `onNewIntent` events. This is useful for handling results from activities or new intents delivered to the current activity. Note that `bind` is not thread-safe and should be called from the main thread. ```APIDOC ## android.activity.bind ### Description Binds a callback function to an Android event like `on_new_intent` or `on_activity_result`. ### Method `bind(_eventname=callback_ , _..._)` ### Parameters * `_eventname` (string) - The name of the Android event to bind to (e.g., 'on_new_intent', 'on_activity_result'). * `callback` - The function or method to be called when the event occurs. ### Warning This method is not thread-safe. Call it in the main thread of your app. ### Example: ```python from android import activity def on_new_intent(self, intent): # Handle new intent logic here pass def nfc_enable(self): activity.bind(on_new_intent=self.on_new_intent) def nfc_disable(self): activity.unbind(on_new_intent=self.on_new_intent) ``` ``` -------------------------------- ### Vibrate using Plyer Source: https://python-for-android.readthedocs.io/en/latest/apis.html Use Plyer for a concise way to trigger device vibration. The argument specifies the duration in seconds. ```python from plyer.vibrator import vibrate vibrate(10) # in Plyer, the argument is in seconds ``` -------------------------------- ### Update System UI Elements Source: https://python-for-android.readthedocs.io/en/latest/apis.html Control the status bar and navigation bar colors, icon styles, and padding for Android 15+. Use this to customize the overall system UI appearance. ```python from android.display_cutout import update_system_ui update_system_ui( "#0f62fe", # status_bar_color: hex color code or rgba (tuple or list) values [0.059, 0.384, 0.996, 1.000], # navigation_bar_color: hex color code or rgba (tuple or list) values "Light", # icon_style: "Dark" means dark icons will be drawn, "Light" means light icons will be drawn, Literal["Dark", or "Light"] True, # pad_status: Adds a padding to top of content_view, Will take effect on Android 15+ True, # pad_nav: Adds a padding to bottom of content_view, Will take effect on Android 15+ ) ``` -------------------------------- ### Implement App Pause Handling Source: https://python-for-android.readthedocs.io/en/latest/apis.html Define an `on_pause` method in your Kivy App class to handle the Android application pausing event. Returning True indicates that the app can be paused. ```python def on_pause(self): return True ``` -------------------------------- ### Accessing Service Argument Source: https://python-for-android.readthedocs.io/en/latest/services.html Retrieve the argument passed to the service via the 'PYTHON_SERVICE_ARGUMENT' environment variable. This is useful for passing configuration or data to your service. ```python from os import environ argument = environ.get('PYTHON_SERVICE_ARGUMENT', '') ``` -------------------------------- ### Hide Loading Screen Source: https://python-for-android.readthedocs.io/en/latest/apis.html Explicitly dismiss the application's loading screen. This can be scheduled to run in the first active frame or called during the app build process. ```python from android import loadingscreen loadingscreen.hide_loading_screen() ``` -------------------------------- ### Vibrate using Pyjnius Source: https://python-for-android.readthedocs.io/en/latest/apis.html Access the Android vibrator service directly using Pyjnius. This method requires obtaining the current activity and system service, offering more control but with increased verbosity. ```python 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 # This one works with SDL2 PythonActivity = autoclass('org.kivy.android.PythonActivity') activity = PythonActivity.mActivity Context = autoclass('android.content.Context') vibrator = activity.getSystemService(Context.VIBRATOR_SERVICE) vibrator.vibrate(10000) # the argument is in milliseconds ``` -------------------------------- ### Fetch Pull Request by Number Source: https://python-for-android.readthedocs.io/en/latest/testing_pull_requests.html Fetches a specific pull request from the upstream repository to a local branch. Ensure 'upstream' is correctly configured as the remote for the original project. ```bash git fetch upstream pull/1901/head:feature-fix-numpy ```