pythonjavachaquopy

How to call Java class method from Python?


I am making and Android app in Python using briefcase from BeeWare that must start a service. And I have this code...

This is the relevant code form MainActivity.java:

package org.beeware.android;

import com.chaquo.python.Kwarg;
import com.chaquo.python.PyException;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;

public class MainActivity extends AppCompatActivity {

    public static MainActivity singletonThis;

    protected void onCreate(Bundle savedInstanceState) {
        singletonThis = this;
        ... start Python
    }

    public void startMyService() {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }

And this is the relevant code from app.py that my intuition came up with:

from chaquopy import Java

class Application(toga.App):

      ...UI code here

  def start_tcp_service(self, widget):
    msg = 'START pressed !'
    print(msg); self.LogMessage(msg)
    self.CallJavaMethod('startMyService')

  def CallJavaMethod(self, method_name):
    MainActClass = Java.org.beeware.android.MainActivity
    MainActivity = MainActClass.singletonThis
    method = getattr(MainActivity, method_name)
    method()   

Now, when I try to run the project with briefcase run android -u on my Android phone, through the USB Debuging bridge, I get the error:

E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/org.beeware.android.MainActivity}: com.chaquo.python.PyException: ModuleNotFoundError: No module named 'chaquopy'

It seems that there is no module with name chaquopy. I tried to install it with pip but it is not found. But then, how can I access the MainActivity methods from Python ? What is the correc module to include ?

I found here some documentation that says "The java module provides facilities to use Java classes and objects from Python code.". I tried to import java bun this is not found either... It seems that on this page it tells how to access Java from Python, but I dont understant all that is there, because this is my first interaction with Java and Android...


Solution

  • I found it ! It goes like this...

    from org.beeware.android import MainActivity
    
    class Application(toga.App):
    
          ...UI code here
    
      def start_tcp_service(self, widget):
        msg = 'START pressed !'
        print(msg); self.LogMessage(msg)
        self.CallJavaMethod('startMyService')
    
      def CallJavaMethod(self, method_name):
        MainActInst = MainActivity.singletonThis
        method = getattr(MainActInst, method_name)
        method()