Python for Android Tutorial #7 - PyJNIus - Using Android native classes

Welcome!!

This is the seventh post about mobile development with Python.

In this  post, I’ll show you how to work with PyJNIus, a Python module to access Java classes as Python classes using JNI.

To show how it works, we’ll create a simple share button to open an intent and share a link with an external application :)

I - About the Tutorials

I’ll show you how to use each mobile API, like compass, camera, sensors, sound, and others. After the API, we will start to test some Python libs, as PyGame and OpenCV. I’m using Android with buildozer, but major part are compatible with iOS as well.

Must read:

Source code

Get updates Follow @aron-bordin
Star it: Star
Contribute: Fork
Download: Download

II - Index

Available tutorials:

III - About this tutorial

This is a short post, just to show you how to start an Android Intent with Kivy.

In this post I’ll be using Pyjnius, a Python module to access Java classes as Python classes using JNI.

This post is explaining more about the game created at Tutorial #5 – Android and iOS game with Python

IV - Creating our project

Let’s start to work on it.

Create a new folder, and create two files, main.py, for the source code, and main.kv, the UI. Now, start a new buildozer project with the command:

buildozer init

As we are using an external library, Pyjnius, you need to add it to your buildozer.spec file. Open your buildozer.spec and add pyjnius to the following line:

requirements = kivy, pyjnius

Now to make sure that you are able to run this project, run the following command:

  
buildozer --verbose android debug deploy run

This command will prepare your environment, check requirements and run the app on Android. If you get some error, please comment here so I can try to help you.

Now, let’s create a simple UI to test the Android Intent.

V - A simple UI with KV Lang

In this post we’ll have just a simple BoxLayout with a Button, nothing beautiful ;/

Just add the following code to your main.kv:

<RootWidget>:
  Button:
    text: 'Share simple text'
    on_press: root.share()

With this code, the parent widget will be a RootWidget, a Python class that we’ll create later.

The RootWidget has a simple Button, with a text and on_press event.

When the user clicks on the button, it will can the method share() on RootWidget class.

VI - Python Code

Let’s add just the necessary to run our app. Use the following code in main.py:

__version__ = '1.0'

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class RootWidget(BoxLayout):

  def share(self):
    print(&amp;quot;sharing&amp;quot;)

class MainApp(App):
  def build(self):
    return RootWidget()

  def on_pause(self):
    return True

if __name__ == '__main__':
  MainApp().run()

It’s simple! We just added a RootWidget that expends a BoxLayout, and created the method share().

VII - Working with PyJNIus

Now, let’s learn more about PyJNIus and use it.

PyJNI can wrap Java classes to use it with Python! Take a look in this simple example provided by PyJNIus documentation:

System = autoclass('java.lang.System')
System.out.println('Hello World')

With these commands you will be able to call Java System.out.println!

VIII - Starting an Android Intent with Kivy and PyJNIus

Now, let’s integrate PyJNIus with our Android Kivy application.

You can read the Android documentation here: http://developer.android.com/training/sharing/send.html

Add these lines to the top of your file:

from kivy.utils import platform

if platform() == "android":
  from jnius import cast
  from jnius import autoclass

As long as we can share only with Android, first we need to check the running platform and then import the required libraries.

Now, just update the share():

def share(self):
    if platform() == 'android': #check if the app is on Android
        # read more here: http://developer.android.com/training/sharing/send.html

        PythonActivity = autoclass('org.renpy.android.PythonActivity') #request the Kivy activity instance
        Intent = autoclass('android.content.Intent') # get the Android Intend class

        String = autoclass('java.lang.String') # get the Java object

        intent = Intent() # create a new Android Intent
        intent.setAction(Intent.ACTION_SEND) #set the action

        # to send a message, it need to be a Java char array. So we use the cast to convert and Java String to a Java Char array
        intent.putExtra(Intent.EXTRA_SUBJECT, cast('java.lang.CharSequence', String('Byte::Debugger() Tutorial #7')))
        intent.putExtra(Intent.EXTRA_TEXT, cast('java.lang.CharSequence', String("Testing Byte::Debugger() Tutorial #7, with Python for Android")))

        intent.setType('text/plain') #text message

        currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
        currentActivity.startActivity(intent) # show the intent in the game activity
Android Intent with Python

And here we can the the Android Intent working:

That’s it. I’ll be writing more tutorials soon.

Thanks for reading!

Aron Bordin

Aron Bordin

Aron Bordin
Computer Science Student and AI researcher. Always coding something fun :)

[Tutorial] Developing Android Background Services

### Welcome!In this post, I'll show you how to develop background services on Android Studio. We'll see two type of services: `Service` a...… Continue reading