### Install PyJNIus Source: https://github.com/kivy/pyjnius/blob/master/README.md Install the pyjnius package using pip. This is the recommended way to get started. ```bash pip install pyjnius ``` -------------------------------- ### Running the Pyjnius Example Source: https://github.com/kivy/pyjnius/blob/master/docs/source/quickstart.md Shows how to execute the Python script containing the Pyjnius example and the expected output. ```bash $ python test.py world hello ``` -------------------------------- ### Example Output of Packaged Application Source: https://github.com/kivy/pyjnius/blob/master/docs/source/packaging.md This is an example of the expected output when the packaged application runs successfully, indicating the path to the Java runtime environment. ```text C:\\Program Files\\Java\\jdk1.7.0_79\\jre ``` -------------------------------- ### Using javap to get Java method signatures Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Command-line example using 'javap -s' to inspect the signature of a Java method. ```bash $ javap -s java.util.Iterator ``` -------------------------------- ### Windows Environment Setup Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/README.md Set the JAVA_HOME environment variable for Windows to your JDK installation directory. ```bash # Set JAVA_HOME to your JDK installation set JAVA_HOME=C:\Program Files\Java\jdk-11 python script.py ``` -------------------------------- ### Example: Getting Method Signatures Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMethod.md Demonstrates how to retrieve and print the signatures for a Java String method using Pyjnius. ```python from jnius import autoclass String = autoclass('java.lang.String') signatures = String.split.signatures() print(signatures) # [(['java/lang/String', 'I'], '[Ljava/lang/String;'), ...] ``` -------------------------------- ### Start Activity with Intent.ACTION_VIEW Source: https://github.com/kivy/pyjnius/blob/master/docs/source/android.md Open a web URL using Intent.ACTION_VIEW and Uri.parse. Requires casting PythonActivity.mActivity to an Android Activity to start the activity. ```python from jnius import cast from jnius import autoclass # import the needed Java class PythonActivity = autoclass('org.kivy.android.PythonActivity') Intent = autoclass('android.content.Intent') Uri = autoclass('android.net.Uri') # create the intent intent = Intent() intent.setAction(Intent.ACTION_VIEW) intent.setData(Uri.parse('http://kivy.org')) # PythonActivity.mActivity is the instance of the current Activity # BUT, startActivity is a method from the Activity class, not from our # PythonActivity. # We need to cast our class into an activity and use it currentActivity = cast('android.app.Activity', PythonActivity.mActivity) currentActivity.startActivity(intent) # The website will open. ``` -------------------------------- ### Install PyJNIus from Source Source: https://github.com/kivy/pyjnius/blob/master/docs/source/building.md Use this command to build and install PyJNIus after checking out the source code. It ensures Cython is installed in the build environment. ```default pip install . ``` -------------------------------- ### Linux/Mac Environment Setup Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/README.md Set the JAVA_HOME environment variable for Linux or macOS. Alternatively, PyJNIus can auto-detect the Java installation. ```bash # Ensure JAVA_HOME is set export JAVA_HOME=/usr/lib/jvm/java-11-openjdk # Or let PyJNIus auto-detect (via which java) python3 script.py ``` -------------------------------- ### Source Location Example Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/README.md An example indicating the source code location within the PyJNIus project, including file path and line numbers. ```text Source Location jnius/reflect.py:199-356 ``` -------------------------------- ### Example: Inspecting Method Signatures Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMultipleMethod.md Demonstrates how to use the signatures() method to view the available overloads for a Java method like String.split(). ```python from jnius import autoclass String = autoclass('java.lang.String') print(String.split.signatures()) ``` -------------------------------- ### Usage Examples Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaField.md Examples demonstrating how to declare and use JavaField and JavaStaticField for instance, static, object, and array type fields. ```APIDOC ## Usage Examples ### Declaring fields in a manual JavaClass ```python from jnius import JavaClass, MetaJavaClass, JavaField, JavaStaticField class Point(JavaClass): __metaclass__ = MetaJavaClass __javaclass__ = 'java/awt/Point' x = JavaField('I') # Instance field: int y = JavaField('I') # Instance field: int p = Point() p.x = 50 p.y = 75 print(p.x, p.y) # 50 75 ``` ### Static fields ```python from jnius import autoclass System = autoclass('java.lang.System') out = System.out # Static field: PrintStream err = System.err # Static field: PrintStream ``` ### Object fields ```python from jnius import autoclass File = autoclass('java.io.File') f = File('/tmp/test.txt') parent = f.getParent() # Method returning String # To access a field instead (if it existed): # some_obj_field = f.someObjectField ``` ### Field with array type ```python from jnius import JavaClass, MetaJavaClass, JavaField class IntArrayHolder(JavaClass): __metaclass__ = MetaJavaClass __javaclass__ = 'com/example/IntArrayHolder' data = JavaField('[I') # int array field holder = IntArrayHolder() holder.data = [1, 2, 3] # Set array field arr = holder.data # Get as list print(arr) # [1, 2, 3] ``` ### Field mutation with pass_by_reference When setting an array field, changes can be synchronized back: ```python from jnius import autoclass list_obj = autoclass('java.util.ArrayList')() list_obj.add('a') list_obj.add('b') # If we retrieve an array field and update it: items = list_obj.toArray() # Get array items[0] = 'c' # Modify in Python ``` ``` -------------------------------- ### JNI Signature Format Examples Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMethod.md Illustrates the JNI type descriptors used for defining method signatures, showing various argument and return types. ```text Examples: - `'()V'` — No arguments, returns void - `'(I)Z'` — Takes int, returns boolean - `'(Ljava/lang/String;)Ljava/lang/String;'` — Takes String, returns String - `'([I)V'` — Takes int array, returns void - `'(I[Ljava/lang/Object;)V'` — Takes int and Object array, returns void ``` -------------------------------- ### Get Pyjnius Version Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/MODULE_INVENTORY.md Prints the currently installed version of the Pyjnius library. ```python import jnius print(jnius.__version__) # Current version ``` -------------------------------- ### Basic class instantiation Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/autoclass.md Example of how to use autoclass to create a Python wrapper for the Java String class and instantiate it. ```APIDOC ## Basic class instantiation ### Description Instantiate a Java class wrapper created by `autoclass`. ### Code ```python from jnius import autoclass String = autoclass('java.lang.String') s = String('Hello') print(s) # prints: Hello ``` ``` -------------------------------- ### Usage Example: Checking method overloads Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMethod.md Shows how to use the `signatures()` method to inspect and understand the different overloads available for a Java method. ```APIDOC ### Checking method overloads ```python from jnius import autoclass String = autoclass('java.lang.String') print(String.valueOf.signatures()) # Shows all overloads of valueOf ``` ``` -------------------------------- ### Autoclass Example Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/utility_functions.md Demonstrates how to use autoclass to create Python subclasses for Java classes and check their inheritance. ```python from jnius import autoclass Collection = autoclass('java.util.Collection') ArrayList = autoclass('java.util.ArrayList') print(issubclass(ArrayList, Collection)) # True ``` -------------------------------- ### Signature Generation Examples Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/signatures.md Examples demonstrating the use of the signature() function to generate JNI method signatures for primitive, JavaClass, and array types. ```python from jnius.signatures import jint, jvoid, jfloat, signature from jnius import autoclass # Primitive types sig1 = signature(jint, ()) # Result: '()I' sig2 = signature(jvoid, [jint, jfloat]) # Result: '(IF)V' # JavaClass types String = autoclass('java.lang.String') sig3 = signature(String, []) # Result: '()Ljava/lang/String;' sig4 = signature(String, [String, jint]) # Result: '(Ljava/lang/String;I)Ljava/lang/String;' # Array types from jnius.signatures import JArray sig5 = signature(JArray(jint), []) # Result: '()[I' ``` -------------------------------- ### Android Environment Setup Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/README.md PyJNIus is automatically included when using python-for-android. Set ANDROID_ARGUMENT to enable Android-specific features. ```bash # PyJNIus is automatically included # Set ANDROID_ARGUMENT to enable Android-specific features export ANDROID_ARGUMENT=1 ``` -------------------------------- ### Example: Debugging Signature Selection Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMultipleMethod.md Demonstrates enabling debug output for signature selection in JavaMultipleMethod by passing `debug=True` as a keyword argument. ```python from jnius import autoclass String = autoclass('java.lang.String') s = String('test') # With debug=True, prints which signature was selected result = s.split('e', debug=True) ``` -------------------------------- ### Example: Inspecting ArrayList Add Signatures Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMultipleMethod.md Illustrates inspecting the signatures of the 'add' method on a Java ArrayList to understand its overloads. ```python from jnius import autoclass ArrayList = autoclass('java.util.ArrayList') obj = ArrayList() print(obj.add.signatures()) ``` -------------------------------- ### Interact with Hardware using PyJNIus Source: https://github.com/kivy/pyjnius/blob/master/README.md Demonstrates how to get device DPI, enable the accelerometer, and read its readings over time. Ensure necessary hardware support is available. ```python from kivy.utils import Hardware from time import sleep # use that new class! print('DPI is', Hardware.getDPI()) Hardware.accelerometerEnable() for x in range(20): print(Hardware.accelerometerReading()) sleep(0.1) ``` -------------------------------- ### Instance methods and fields Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/autoclass.md Example of using instance methods and accessing fields of a Java object through its Python wrapper. ```APIDOC ## Instance methods and fields ### Description Interact with instance methods and fields of a Java object via its Python wrapper. ### Code ```python from jnius import autoclass ArrayList = autoclass('java.util.ArrayList') list_obj = ArrayList() list_obj.add('first') list_obj.add('second') print(list_obj.size()) # 2 ``` ``` -------------------------------- ### Get Javaclass Example Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/utility_functions.md Shows how to retrieve a cached JavaClass using MetaJavaClass.get_javaclass. This is useful for checking if a Java class has already been loaded. ```python from jnius import MetaJavaClass # Check if class is cached cls = MetaJavaClass.get_javaclass('java/util/ArrayList') if cls: print("Already loaded") ``` -------------------------------- ### Call a Static Method Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/README.md Instantiate a Java class and call its static methods directly. This example shows how to print a string to the console using System.out.println. ```python from jnius import autoclass System = autoclass('java.lang.System') System.out.println('Hello') ``` -------------------------------- ### Calling Java Static Methods Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/autoclass.md Shows how to call a static method on a Java class. This example calls the println method on java.lang.System.out. ```python from jnius import autoclass System = autoclass('java.lang.System') System.out.println('Hello from Java') # calls static method ``` -------------------------------- ### Usage Example: Handling return values Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMethod.md Provides examples of how pyjnius handles different Java return types (e.g., int, list) and converts them into their corresponding Python types. ```APIDOC ### Handling return values ```python from jnius import autoclass String = autoclass('java.lang.String') s = String('Hello') length = s.length() # Returns int print(type(length)) # parts = s.split('l') # Returns array print(type(parts)) # ``` ``` -------------------------------- ### Install PyJNIus using Conda Source: https://github.com/kivy/pyjnius/blob/master/docs/source/installation.md Install PyJNIus from the conda-forge channel using the conda package manager. ```bash conda install -c conda-forge pyjnius ``` -------------------------------- ### Example Debug Output with ArrayList Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/configuration.md Demonstrates the debug output when initializing an ArrayList with the debug flag enabled. This shows constructor resolution and method dispatch details. ```python from jnius import autoclass ArrayList = autoclass('java.util.ArrayList') l = ArrayList(10, debug=True) # Output: # [(..., 'ArrayList(int)', ..., [10], ...)] # Selected (...)(I)V for invocation ``` -------------------------------- ### Minimal Pyjnius Example Source: https://github.com/kivy/pyjnius/blob/master/docs/source/quickstart.md Demonstrates basic usage of autoclass to instantiate and use a Java class. Ensure your script is not named jnius.py to avoid conflicts. ```python from jnius import autoclass Stack = autoclass('java.util.Stack') stack = Stack() stack.push('hello') stack.push('world') print(stack.pop()) # --> 'world' print(stack.pop()) # --> 'hello' ``` -------------------------------- ### Install PyJNIus with python-for-android Source: https://github.com/kivy/pyjnius/blob/master/docs/source/installation.md When using python-for-android directly, include 'pyjnius' in the requirements argument when creating a distribution or APK. ```bash p4a apk --requirements=pyjnius ``` -------------------------------- ### Set JDK_HOME Environment Variable Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/configuration.md An alternative to JAVA_HOME, specifically for JDK installations. It has higher priority than JAVA_HOME and auto-detection. ```bash export JDK_HOME=/opt/jdk-11 python3 script.py ``` -------------------------------- ### PythonJavaClass Usage Example Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/utility_functions.md Provides a practical example of creating a Python class that implements a Java interface using PythonJavaClass and the java_method decorator, then instantiating it and passing it to Java code. ```python from jnius import PythonJavaClass, java_method class MyListener(PythonJavaClass): __javaclass__ = 'com/example/MyListener' __javainterfaces__ = ['java/util/EventListener'] @java_method('(Ljava/util/EventObject;)V') def onEvent(self, event): print(f"Event: {event}") # Instantiate and pass to Java listener = MyListener() button.setOnClickListener(listener) ``` -------------------------------- ### Java Signature Format Example: Method with Byte array argument, returning boolean Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Example of a Java signature for a method that takes a byte array and returns a boolean. ```text ([B)Z ``` -------------------------------- ### Instantiate a Java Class Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/README.md Use autoclass to create a Python wrapper for a Java class and then instantiate it. The example demonstrates creating an ArrayList and adding an element. ```python from jnius import autoclass ArrayList = autoclass('java.util.ArrayList') list_obj = ArrayList() list_obj.add('hello') print(list_obj.size()) # 1 ``` -------------------------------- ### With selective visibility Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/autoclass.md Example of using autoclass with flags to control the inclusion of protected and private members. ```APIDOC ## With selective visibility ### Description Control the visibility of members included in the generated Python class wrapper. ### Code ```python from jnius import autoclass MyClass = autoclass('com.example.MyClass', include_private=False) # Only public and protected members are included ``` ``` -------------------------------- ### Example: Automatic Overloaded Method Calling Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMultipleMethod.md Shows how JavaMultipleMethod automatically selects the correct overload for methods like String.split() based on the arguments provided. ```python from jnius import autoclass String = autoclass('java.lang.String') s = String('Hello,World') # split() has multiple overloads: # split(String) → String[] # split(String, int) → String[] parts1 = s.split(',') # Auto-selects split(String) parts2 = s.split(',', -1) # Auto-selects split(String, int) ``` -------------------------------- ### Example PyJNIus Debug Log Output Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/configuration.md Illustrates typical debug log messages from PyJNIus, showing Java discovery and libjvm.so location on a Linux system. ```text DEBUG:kivy.jnius:Identified Java at /usr/lib/jvm/java-11-openjdk-amd64 DEBUG:kivy.jnius:looking for libjvm to initiate pyjnius, platform is linux DEBUG:kivy.jnius:found libjvm.so at /usr/lib/jvm/java-11-openjdk-amd64/lib/server/libjvm.so ``` -------------------------------- ### Instance Methods and Fields on Java Objects Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/autoclass.md Illustrates calling instance methods and accessing fields of a Java object. This example uses java.util.ArrayList to add elements and retrieve its size. ```python from jnius import autoclass ArrayList = autoclass('java.util.ArrayList') list_obj = ArrayList() list_obj.add('first') list_obj.add('second') print(list_obj.size()) # 2 ``` -------------------------------- ### Handling Configuration Errors Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/errors.md Catch `RuntimeError` during Pyjnius initialization if Java environment is not configured correctly. This example shows how to handle errors when `JAVA_HOME` is invalid. ```python import os os.environ['JAVA_HOME'] = '/nonexistent/path' from jnius import autoclass try: String = autoclass('java.lang.String') except RuntimeError as e: print(f"Config error: {e}") # Output: RuntimeError: Could not find your Java installed ``` -------------------------------- ### Java Signature Format Example: Method with Integer and List arguments, no return Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Illustrates the Java signature format for a method that accepts an integer and a java.util.List object, returning void. ```text (ILjava/util/List;)V ``` -------------------------------- ### JavaClass __repr__ Example Output Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaClass.md Illustrates the expected string representation of a JavaClass instance, showing its Python object ID, Java class name, and internal Java object reference. ```text > ``` -------------------------------- ### Usage Example: Declaring methods in a manual JavaClass Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMethod.md Demonstrates how to declare and use Java methods (instance and static) within a custom Python class that extends JavaClass. ```APIDOC ## Usage Examples ### Declaring methods in a manual JavaClass ```python from jnius import JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod class ArrayList(JavaClass): __metaclass__ = MetaJavaClass __javaclass__ = 'java/util/ArrayList' add = JavaMethod('(Ljava/lang/Object;)Z') get = JavaMethod('(I)Ljava/lang/Object;') size = JavaMethod('()I') clear = JavaStaticMethod('()V') # if it were static obj = ArrayList() obj.add('hello') obj.add('world') print(obj.size()) # 2 ``` ``` -------------------------------- ### Example: Custom JavaMultipleMethod Definition Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMultipleMethod.md Defines a custom Java class 'Processor' with a 'process' method that has multiple overloaded signatures, demonstrating manual definition using JavaMultipleMethod. ```python from jnius import JavaClass, MetaJavaClass, JavaMultipleMethod class Processor(JavaClass): __metaclass__ = MetaJavaClass __javaclass__ = 'com.example.Processor' process = JavaMultipleMethod([ ('(I)V', False, False), # process(int) ('(Ljava/lang/String;)V', False, False), # process(String) ('(Ljava/util/List;)V', False, False), # process(List) ]) p = Processor() p.process(42) # Calls process(int) p.process('hello') # Calls process(String) p.process([1, 2, 3]) # Calls process(List) ``` -------------------------------- ### JavaMethod Reflection Example Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Shows how to reflect Java methods within a JavaClass subclass using JavaMethod. The signature is specified in JNI format. ```python class Stack(JavaClass): __javaclass__ = 'java/util/Stack' __metaclass__ = MetaJavaClass peek = JavaMethod('()Ljava/lang/Object;') empty = JavaMethod('()Z') ``` -------------------------------- ### Run PyJNIus Tests Source: https://github.com/kivy/pyjnius/blob/master/docs/source/building.md Execute this command to run the test suite and verify that PyJNIus is functioning correctly. Requires Cython and pytest to be installed. ```default make tests ``` -------------------------------- ### JavaField __get__ Example Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaField.md Demonstrates retrieving a Java instance field's value. The value is automatically converted to its Python equivalent. For object types, a JavaClass wrapper is returned. ```python from jnius import autoclass Point = autoclass('java.awt.Point') p = Point() p.x = 10 value = p.x # Calls __get__, returns 10 ``` -------------------------------- ### JavaMultipleMethod Reflection Example Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Illustrates how to reflect a Java method with multiple possible signatures using JavaMultipleMethod. PyJNIus automatically selects the best matching signature based on argument types. ```python class String(JavaClass): __javaclass__ = 'java/lang/String' __metaclass__ = MetaJavaClass getBytes = JavaMultipleMethod([ '(Ljava/lang/String;)[B', '(Ljava/nio/charset/Charset;)[B', '()[B']) ``` -------------------------------- ### JavaField __set__ Example Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaField.md Illustrates setting a Java instance field's value. The provided Python value is converted to the appropriate JNI type before being set on the Java object. ```python from jnius import autoclass Point = autoclass('java.awt.Point') p = Point() p.x = 100 # Calls __set__ p.y = 200 ``` -------------------------------- ### Java Signature Format Example: Method with Collection and Object array arguments, no return Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Shows the Java signature format for a method accepting a Collection and an array of Objects, with no return value. ```text (Ljava/util/Collection;[Ljava/lang/Object;)V ``` -------------------------------- ### Usage Example: Calling overloaded methods explicitly Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMethod.md Illustrates how pyjnius automatically selects the best overload when calling an overloaded Java method with Python arguments. ```APIDOC ### Calling overloaded methods explicitly ```python from jnius import autoclass String = autoclass('java.lang.String') # If valueOf has overloads for different types: result = String.valueOf(42) # Auto-selects best overload ``` ``` -------------------------------- ### JavaField Reflection Example Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Demonstrates reflecting a static Java field using JavaField. The signature is in JNI format, and the static parameter must be set to True. ```python class System(JavaClass): __javaclass__ = 'java/lang/System' __metaclass__ = MetaJavaClass out = JavaField('()Ljava/io/InputStream;', static=True) ``` -------------------------------- ### Run Packaged Application Source: https://github.com/kivy/pyjnius/blob/master/docs/source/packaging.md Execute the main application file after ensuring all dependencies, including Java, are correctly configured. The output should show the Java home directory. ```bash main.exe ``` -------------------------------- ### Get PyJNIus Version Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/README.md Import the jnius library and print its __version__ attribute to check the installed version. ```python import jnius print(jnius.__version__) ``` -------------------------------- ### Get Class and Hash Code of Java Object Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/reflect_module.md Demonstrates retrieving the Class object and hash code for a Java object instance using its wrapper methods. ```python from jnius import autoclass String = autoclass('java.lang.String') s = String('hello') # Get the class cls = s.getClass() print(cls.getName()) # Get hash code hc = s.hashCode() print(type(hc)) ``` -------------------------------- ### Python Object to Java Conversion Examples Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/types.md Shows how various Python values are converted when passed to Java methods. Covers `None` to Java `null`, Python `str` to Java `String` or `CharSequence`, `int` to boxed `Integer`, `float` to boxed `Float`, and Python `list`/`tuple` to Java object arrays. ```python from jnius import autoclass # Passing Python string to Java method expecting String String = autoclass('java.lang.String') s = String('hello') result = s.startsWith('he') # Python str → Java String # Passing None for nullable argument ArrayList = autoclass('java.util.ArrayList') l = ArrayList() l.add(None) # None → Java null # Passing Python list for array argument Arrays = autoclass('java.util.Arrays') sorted_arr = Arrays.asList([3, 1, 2]) # list → Java Object[] ``` -------------------------------- ### Basic Java Class Instantiation Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/autoclass.md Demonstrates how to load a Java class and instantiate it with a string argument. Ensure 'java.lang.String' is accessible in your Java environment. ```python from jnius import autoclass String = autoclass('java.lang.String') s = String('Hello') print(s) # prints: Hello ``` -------------------------------- ### Instantiating Java Class with Constructor Arguments Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaClass.md Shows how to create a Java object by providing arguments to its constructor. Ensure the Python types match a valid Java constructor signature. ```python from jnius import autoclass String = autoclass('java.lang.String') s = String('Hello World') print(s.length()) # 11 ``` -------------------------------- ### Install PyJNIus with Conda and specific label Source: https://github.com/kivy/pyjnius/blob/master/docs/source/installation.md Install PyJNIus using Conda, specifying a particular package label such as 'gcc7'. ```bash conda install -c conda-forge/label/gcc7 pyjnius ``` -------------------------------- ### Set JAVA_HOME Environment Variable Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/configuration.md Specifies the Java Development Kit or Java Runtime Environment installation path. PyJNIus uses this to locate the JVM library. If not set, automatic detection is attempted. ```bash export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 python3 script.py ``` -------------------------------- ### Using javap for Android class method signatures Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Steps to use 'javap -s' with an Android SDK's 'android.jar' to find method signatures for Android classes. ```bash $ cd path/to/android/sdk/ $ cd platforms/android-xx/ # Replace xx with your android version $ javap -s -classpath android.jar android.app.Activity # Replace android.app.Activity with any android class whose methods' signature you want to see ``` -------------------------------- ### jnius_config Module: env Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/MODULE_INVENTORY.md Classes and functions within `jnius_config.env` for detecting and managing Java installation locations. ```APIDOC ## JavaLocation Classes ### Description Base and platform-specific classes for locating Java installations. ### Classes - `JavaLocation`: Base class. - `WindowsJavaLocation`: For Windows. - `UnixJavaLocation`: For Unix/Linux. - `MacOsXJavaLocation`: For macOS. - `BSDJavaLocation`: For BSD systems. - `AndroidJavaLocation`: For Android environments. ``` ```APIDOC ## jnius_config.env Functions ### Description Utility functions for detecting Java installation paths. ### Functions - `get_java_setup(platform)`: Detects Java setup for a given platform. - `get_jdk_home(platform)`: Locates the JDK home directory for a platform. - `get_jre_home(platform)`: Locates the JRE home directory for a platform. - `get_osx_framework()`: Retrieves the Java path from macOS frameworks. ``` -------------------------------- ### Accessing a Java Class Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Use autoclass to get a JavaClass representation. The name must be in 'a.b.c' format. ```pycon >>> from jnius import autoclass >>> autoclass('java.lang.System') ``` -------------------------------- ### Using Arrays with Signatures Module Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/signatures.md Demonstrates how to define Java methods that accept or return arrays using the signatures module, specifically JArray and signature functions. ```python from jnius.signatures import signature, JArray, jint, jvoid from jnius import JavaClass, MetaJavaClass, JavaMethod class ArrayProcessor(JavaClass): __metaclass__ = MetaJavaClass __javaclass__ = 'com/example/ArrayProcessor' sum = JavaMethod(signature(jint, [JArray(jint)])) sort = JavaStaticMethod(signature(jvoid, [JArray(jint)])) processor = ArrayProcessor() result = processor.sum([1, 2, 3, 4, 5]) # 15 ``` -------------------------------- ### String Representation of Java Class Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/reflect_module.md Demonstrates how to get the string representation of a Java class using the custom __str__ method. ```python from jnius import find_javaclass String = find_javaclass('java.lang.String') print(str(String)) List = find_javaclass('java.util.List') print(str(List)) ``` -------------------------------- ### Get Device DPI with DisplayMetrics Source: https://github.com/kivy/pyjnius/blob/master/docs/source/android.md Retrieve the screen's DPI using the DisplayMetrics class. Ensure PyJNIus is imported. ```python from jnius import autoclass DisplayMetrics = autoclass('android.util.DisplayMetrics') metrics = DisplayMetrics() print('DPI', metrics.getDeviceDensity()) ``` -------------------------------- ### Selecting a Specific Java Constructor Signature Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaClass.md Illustrates how to explicitly choose a constructor when a Java class has multiple overloads. Use the `signature` keyword argument with the JNI signature string. ```python from jnius import autoclass ArrayList = autoclass('java.util.ArrayList') # Use constructor with initial capacity: ArrayList(int) l = ArrayList(10, signature='(I)V') ``` -------------------------------- ### Object Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/reflect_module.md Wrapper for `java.lang.Object`, the base class for all Java objects. Provides methods to get the Class object for an instance and its hash code. ```APIDOC ## Object ### Description Wrapper for `java.lang.Object`, the base class for all Java objects. Provides methods to get the Class object for an instance and its hash code. ### Methods | Method | Returns | Description | |---|---|---| | getClass() | Class | Get the Class object for this instance | | hashCode() | int | Hash code of this object | ### Usage Examples ```python from jnius import autoclass String = autoclass('java.lang.String') s = String('hello') # Get the class cls = s.getClass() print(cls.getName()) # 'java.lang.String' # Get hash code hc = s.hashCode() print(type(hc)) # ``` ``` -------------------------------- ### Implement Java Iterator with next() Method Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md Example of implementing the java.util.Iterator interface in Python using PythonJavaClass and the @java_method decorator for the next() method. ```python class PythonListIterator(PythonJavaClass): __javainterfaces__ = ['java/util/ListIterator'] @java_method('()Ljava/lang/Object;') def next(self): obj = self.collection.data[self.index] self.index += 1 return obj ``` -------------------------------- ### Checking Method Overloads with valueOf Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaMethod.md Demonstrates how to use the signatures() method to inspect all available overloads for a Java method, specifically String.valueOf. ```python from jnius import autoclass String = autoclass('java.lang.String') print(String.valueOf.signatures()) ``` -------------------------------- ### JavaMethod Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/MANIFEST.md Descriptors for instance and static methods. Includes constructor parameters, JNI signature format, methods like __call__() and signatures(), return value conversion rules, and differences from JavaStaticMethod. ```APIDOC ## JavaMethod ### Description Descriptors for handling Java instance and static methods, including their signatures, invocation, and return value conversions. ### Constructor Parameters Parameters accepted by the JavaMethod constructor. ### JNI Signature Format Details the format for JNI signatures used by methods. ### Methods - **__call__(*args, **kwargs)**: Invokes the Java method. - **signatures()**: Returns the available signatures for the method. ### Return Value Conversion Rules Specifies how Java return types are converted to Python types. ### JavaStaticMethod Differences Highlights the distinctions between JavaMethod and JavaStaticMethod. ### JNI Signature Format Table A table detailing various JNI signature formats. ### Usage Examples Examples demonstrating the use of JavaMethod. ### Source Location Indicates the source file location for JavaMethod. ``` -------------------------------- ### Loading Nested Java Classes Source: https://github.com/kivy/pyjnius/blob/master/docs/source/quickstart.md Illustrates how to load nested Java classes using the '$' separator for class names. ```python version = autoclass("android.os.Build$VERSION") base_os = version.BASE_OS ``` -------------------------------- ### JavaField Definition Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/MODULE_INVENTORY.md Defines the structure for representing a Java field. Supports static fields and provides methods for getting and setting field values. ```python class JavaField(object): def __init__(self, definition: str, static: bool = False) → None def __get__(self, obj, objtype) → value def __set__(self, obj, value) → None ``` -------------------------------- ### Get Internal JNI JavaVM Pointer Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/MODULE_INVENTORY.md Use get_jni_java_vm() to retrieve the internal JNI JavaVM* pointer. This is an advanced function for low-level interaction. ```python from jnius import get_jni_java_vm # Get the JNI JavaVM pointer java_vm_ptr = get_jni_java_vm() ``` -------------------------------- ### Comparing Raw Signatures vs. Signatures Module Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/signatures.md Illustrates the difference in readability and clarity between defining a Java method signature using raw JNI type descriptors and using the Pyjnius signatures module. The signatures module offers a more Pythonic and understandable approach. ```python # Raw signature (hard to read) process = JavaMethod('([Ljava/lang/String;Ljava/util/List;)V') ``` ```python # With signatures module (clear intent) from jnius.signatures import signature, JArray String = autoclass('java.lang.String') List = autoclass('java.util.List') process = JavaMethod(signature(jvoid, [JArray(String), List])) ``` -------------------------------- ### JavaException Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/MANIFEST.md The exception wrapper class. Covers constructor parameters, properties, the __str__() method for stack traces, and usage examples for catching and checking exceptions. ```APIDOC ## JavaException ### Description Wrapper class for handling Java exceptions within Python. ### Constructor Parameters Parameters and properties accepted by the JavaException constructor. ### Methods - **__str__()**: Returns a string representation of the exception, including the stack trace. ### Usage Examples Examples for catching and checking Java exceptions. ### Exception Type Mapping Table A table mapping Java exception types to Python exceptions. ### Exception Catching Flow Describes the process of catching and handling Java exceptions. ### Source Location Indicates the source file location for JavaException. ``` -------------------------------- ### Manual JavaClass Declaration with Signatures Module Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/signatures.md Illustrates defining Java methods and static methods within a JavaClass using both raw JNI signatures and the more readable signatures module. ```python from jnius.signatures import signature, with_signature, jint, jvoid, jboolean from jnius import JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod class Calculator(JavaClass): __metaclass__ = MetaJavaClass __javaclass__ = 'com/example/Calculator' # Using raw signatures (traditional way) add = JavaMethod('(II)I') subtract = JavaStaticMethod('(II)I') # Using signatures module (more readable) multiply = JavaMethod(signature(jint, [jint, jint])) divide = JavaStaticMethod(signature(jint, [jint, jint])) calc = Calculator() result = calc.add(10, 5) # 15 result = calc.multiply(10, 5) # 50 result = Calculator.divide(10, 5) # 2 ``` -------------------------------- ### Basic Java Class Access Source: https://github.com/kivy/pyjnius/blob/master/README.md Demonstrates accessing Java's System.out.println and java.util.Stack using autoclass. This is useful for simple Java interactions. ```python >>> from jnius import autoclass >>> autoclass('java.lang.System').out.println('Hello world') Hello world >>> Stack = autoclass('java.util.Stack') >>> stack = Stack() >>> stack.push('hello') >>> stack.push('world') >>> print(stack.pop()) world >>> print(stack.pop()) hello ``` -------------------------------- ### JavaField Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaField.md JavaField is a descriptor for accessing Java instance fields from Python. It allows you to get and set values of Java instance fields as if they were Python attributes. ```APIDOC ## JavaField Instance field descriptor for accessing Java instance fields from Python. ### Constructor ```python def __init__(self, definition, **kwargs) ``` #### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | definition | str | Yes | — | JNI field type descriptor. E.g., `'I'` for int, `'Ljava/lang/String;'` for String, `'[I'` for int array. | | static | bool | No | False | Set to True for static fields (use `JavaStaticField` instead). | ### Field Type Descriptors | Type | Descriptor | Python Type | |------|-----------|-------------| | boolean | Z | bool | | byte | B | int | | char | C | str | | short | S | int | | int | I | int | | long | J | int | | float | F | float | | double | D | float | | Object | L*class_name*; | JavaClass | | Array | [*element_type* | list | ### __get__ Retrieve the field value. ```python def __get__(self, obj, objtype) ``` **Parameters:** - `obj` — Instance of JavaClass (None for static access) - `objtype` — The class itself **Returns:** - Field value converted to Python type - For object types, returns a JavaClass wrapper - For arrays, returns a Python list **Example:** ```python from jnius import autoclass Point = autoclass('java.awt.Point') p = Point() p.x = 10 value = p.x # Calls __get__, returns 10 ``` ### __set__ Set the field value. ```python def __set__(self, obj, value) ``` **Parameters:** - `obj` — Instance of JavaClass - `value` — New value (converted from Python to JNI type) **Example:** ```python from jnius import autoclass Point = autoclass('java.awt.Point') p = Point() p.x = 100 # Calls __set__ p.y = 200 ``` ``` -------------------------------- ### ART Runtime Detachment Error Example Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md This log output shows the error message on ART runtime when a native thread exits without calling `DetachCurrentThread`. ```log W/art (21168): Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?): Thread[16,tid=21293,Native,Thread*=0x4c25c040,peer=0x677eaa70,"Thread-16219"] F/art (21168): art/runtime/thread.cc:903] Native thread exited without calling DetachCurrentThread: Thread[16,tid=21293,Native,Thread*=0x4c25c040,peer=0x677eaa70,"Thread-16219"] F/art (21168): art/runtime/runtime.cc:203] Runtime aborting... F/art (21168): art/runtime/runtime.cc:203] (Aborting thread was not attached to runtime!) F/art (21168): art/runtime/runtime.cc:203] Dumping all threads without appropriate locks held: thread list lock mutator lock F/art (21168): art/runtime/runtime.cc:203] All threads: F/art (21168): art/runtime/runtime.cc:203] DALVIK THREADS (16): ... ``` -------------------------------- ### Dalvik VM Detachment Error Example Source: https://github.com/kivy/pyjnius/blob/master/docs/source/api.md This log output illustrates the error message seen on Dalvik VM when a native thread exits without being detached. ```log D/dalvikvm(16696): threadid=12: thread exiting, not yet detached (count=0) D/dalvikvm(16696): threadid=12: thread exiting, not yet detached (count=1) E/dalvikvm(16696): threadid=12: native thread exited without detaching E/dalvikvm(16696): VM aborting ``` -------------------------------- ### Build Executable with PyInstaller Source: https://github.com/kivy/pyjnius/blob/master/docs/source/packaging.md Execute this command to build the application using the modified .spec file. PyInstaller will create a folder containing the executable and all necessary dependencies. ```bash pyinstaller main.spec ``` -------------------------------- ### Inspect Java Method Signatures with PyJNIus Source: https://github.com/kivy/pyjnius/blob/master/README.md Shows how to use the `signatures` method to inspect the discovered signatures of a Java method. This is useful for understanding method overloading and types. ```python from jnius import autoclass String = autoclass('java.lang.String') print(dir(String)) print(String.format.signatures()) ``` -------------------------------- ### Enabling Debug Output for Constructor Resolution Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaClass.md Shows how to enable detailed logging during constructor selection by setting the `debug=True` keyword argument. This is useful for diagnosing issues with constructor matching. ```python from jnius import autoclass MyClass = autoclass('com.example.MyClass') obj = MyClass(5, 'hello', debug=True) # Prints which constructor signature was selected ``` -------------------------------- ### JavaMultipleMethod Signature and Call Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/MODULE_INVENTORY.md Handles overloaded Java methods. The __init__ takes multiple definitions, and __call__ dispatches to the appropriate method based on arguments. signatures() returns available signatures. ```python # Signature for JavaMultipleMethod # def __init__(self, definitions) # def __call__(*args, **kwargs) → return_value # def signatures() → list # Example usage (conceptual): # Assuming 'my_java_object' has overloaded methods and 'overloaded_method' is a JavaMultipleMethod descriptor # result = my_java_object.overloaded_method(arg1, arg2) ``` -------------------------------- ### Access a Java Field Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/README.md Access and modify Java object fields directly from Python. This example demonstrates creating a Point object and setting its x and y coordinates. ```python from jnius import autoclass Point = autoclass('java.awt.Point') p = Point() p.x = 100 print(p.y) ``` -------------------------------- ### Accessing Object Fields Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaField.md Illustrates accessing an object field, specifically the 'parent' field of a `java.io.File` object. The example notes that this is for field access, not method calls. ```python from jnius import autoclass File = autoclass('java.io.File') f = File('/tmp/test.txt') parent = f.getParent() # Method returning String # To access a field instead (if it existed): # some_obj_field = f.someObjectField ``` -------------------------------- ### JavaField Signature and Access Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/MODULE_INVENTORY.md Defines the signature for a Java field, including its constructor, get, and set methods. Use __get__ to retrieve and __set__ to assign values. ```python # Signature for JavaField # def __init__(self, definition, static=False) # def __get__(obj, objtype) → value # def __set__(obj, value) → None # Example usage (conceptual): # Assuming 'my_java_object' is an instance of a JavaClass and 'my_field' is a JavaField descriptor # field_value = my_java_object.my_field # my_java_object.my_field = new_value ``` -------------------------------- ### Create Main Python Script Source: https://github.com/kivy/pyjnius/blob/master/docs/source/packaging.md This script imports the autoclass function from jnius and prints the Java home directory. It serves as the entry point for the packaged application. ```python from jnius import autoclass if __name__ == '__main__': print(autoclass('java.lang.System').getProperty('java.home')) ``` -------------------------------- ### Record Audio File with MediaRecorder Source: https://github.com/kivy/pyjnius/blob/master/docs/source/android.md Record audio for 5 seconds to '/sdcard/testrecorder.3gp' using Android's MediaRecorder. Imports for MediaRecorder and time are required. ```python from jnius import autoclass from time import sleep # get the needed Java classes MediaRecorder = autoclass('android.media.MediaRecorder') AudioSource = autoclass('android.media.MediaRecorder$AudioSource') OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat') AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder') # create out recorder mRecorder = MediaRecorder() mRecorder.setAudioSource(AudioSource.MIC) mRecorder.setOutputFormat(OutputFormat.THREE_GPP) mRecorder.setOutputFile('/sdcard/testrecorder.3gp') mRecorder.setAudioEncoder(AudioEncoder.AMR_NB) mRecorder.prepare() # record 5 seconds mRecorder.start() sleep(5) mRecorder.stop() mRecorder.release() ``` -------------------------------- ### Calling Static Java Methods Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/api-reference/JavaClass.md Demonstrates how to invoke static methods on a Java class without needing to instantiate the class first. Use this for utility methods or class-level operations. ```python from jnius import autoclass System = autoclass('java.lang.System') System.out.println('No instance needed') # Static method ``` -------------------------------- ### Automatic Android Thread Detach Hook Source: https://github.com/kivy/pyjnius/blob/master/_autodocs/configuration.md When ANDROID_ARGUMENT is set, PyJNIus installs a threading hook to automatically call jnius.detach() on thread exit, preventing resource leaks. ```python import os if "ANDROID_ARGUMENT" in os.environ: import threading import jnius orig_thread_run = threading.Thread.run def jnius_thread_hook(*args, **kwargs): try: return orig_thread_run(*args, **kwargs) finally: jnius.detach() threading.Thread.run = jnius_thread_hook ```