I'm glad to introduce you to a pyjnius project. This is a python library that can be used on the desktop or android to access Java classes.
AD:
I'm glad to introduce you
Pyjnius project. This is a python library that can be used on the desktop or android to access Java classes.
Source code: github.com/kivy/pyjnius
Document: pyjnius.readthedocs.org
There are also some other libraries, such
Jpype or
Py4j, which is not well designed and available. And use
Jython is not another option because we want to use
Python Android development project.
Now let me tell you how to simply 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'
In the above Code, we use
The autoclass function creates a type proxy that corresponds to all the methods and field attributes of the Java. util. Stack class in Java.
OK. Maybe you want an Android-related example. Here:
- 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()
Now, you can get more examples from the document.
We can map Java/Python types, native arrays, and support method overloading. What we use internally is
Cython +
JNI, so the consumption performance is the smallest.
At the same time,
The Python for Android library has been completed. You can obtain it from GitHub.
Original English,
Oschina. Net Translation