We’re pleased to announce the Pyjnius project. It’s a Python library to access Java classes from Python, on the desktop or on Android.
- Source code: github.com/kivy/pyjnius
- Documentation: pyjnius.readthedocs.org
We found others libraries such as JPype or Py4j, but we weren’t happy with the design and the usability. Using Jython wasn’t an option either, because we wanted to use the library within our python for android project.
Let me show you how simple it is to use Pyjnius:
>>> from jnius import autoclass >>> Stack = autoclass('java.util.Stack') >>> stack = Stack() >>> stack.push('hello') >>> stack.push('world') >>> stack.pop() 'world' >>> stack.pop() 'hello'
What we demonstrate here is the autoclass function that create kind-of proxy that reflect all the methods and fields available from the Java class
Ok, maybe you want an Android-related example? Just have a look:
from jnius import autoclass from time import sleep MediaRecorder = autoclass('android.media.MediaRecorder') AudioSource = autoclass('android.media.MediaRecorder$AudioSource') OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat') AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder') # Record the Microphone with a 3GP recorder mRecorder = MediaRecorder() mRecorder.setAudioSource(AudioSource.MIC) mRecorder.setOutputFormat(OutputFormat.THREE_GPP) mRecorder.setOutputFile('/sdcard/testrecorder.3gp') mRecorder.setAudioEncoder(AudioEncoder.ARM_NB) mRecorder.prepare() # Record 5 seconds mRecorder.start() sleep(5) mRecorder.stop() mRecorder.release()
More examples are available in the documentation. We have a mapping between Java/Python type, native arrays, support for methods with multiple signatures, and a lot more. We are using Cython + JNI internally. The performance cost is minimal.
The library is already available for Python for android.
The library have been done by Gabriel Pettier and myself, under the Kivy organization.