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.
Source code: github.com/kivy/pyjnius
Document: pyjnius.readthedocs.org
There are also some other libraries, such as JPype or Py4j, which are not very good in design and availability. Using Jython is not another option, because we want to use python to develop Android projects.
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 to create a type proxy, which 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. We use Cython + JNI internally, so the minimum consumption performance is.
At the same time, the Python for android library has been completed and can be obtained from github.
OSChina. NET Translation