Click here to Skip to main content
Click here to Skip to main content

Calling Python from Java for Android using CLE and SL4A

, 28 Feb 2012
Rate this:
Please Sign up or sign in to vote.
Calling Python from Java for Android using CLE and SL4A

Java is major language to develop applications on Android platform. But, in some cases, programmers want to call Python code from Java to perform some functions.

By now, there is no direct method to write programs with Python.

SL4A is an open project, which supports script languages including python, lua, etc. But calling python from Java has not been supported directly. Programmers have to use JNI method, and native code to write interface for python. This is more difficult, you have to manage relationship between Java objects and python objects, kinds of references, interface parameters conversion, and callback functions from python to Java.

CLE(Common Language Extension) is a middleware which presents functions to aid multi-language calls between scripts, including Java and python. Using CLE, the above problems can be solved easily. Architecture of CLE is as follows:

Java calls python functions:

Python function

Obj=Service._New("TestClass");
def Obj_PythonAdd(self,x,y) :
    return x+y;
Obj.PythonAdd = Obj_PythonAdd;

Java code

StarObjectClass a = Service._GetObject("TestClass")._New();
a._Call("PythonAdd",12,34));
Callback of python to java:

Java callback function

StarObjectClass a = Service._GetObject("TestClass")._New()._Assign(new StarObjectClass(){
   public int JavaAdd(StarObjectClass self,int x,int y){
       return x+y;
   }
});

Python code

Obj.JavaAdd(x,y)

Java gets object’s attributes defined in python.

Python: Obj.PythonValue = 200;

Java: a._Get("PythonValue")
Python gets object’s attributes defined in Java.

Java: a._Set("JavaValue",100);
Python: self.JavaValue

Method1 source code (integrate CLE with your project)

  1. Install SL4A from http://code.google.com/p/android-scripting/downloads/list
  2. Download devfiles from http://code.google.com/p/cle-for-android, and then Open Eclipse
  3. Create project for Android.
  4. Add CLE libraries to project as follows:

  5. Python code:
    SrvGroup = libstarpy._GetSrvGroup()
    
    Service = SrvGroup._GetService("","")
    
    #Create objects
    Obj=Service._New("TestClass");
    
    #Define functions
    def Obj_PythonAdd(self,x,y) :
        print("Call python function...");
        return x+y;
    Obj.PythonAdd = Obj_PythonAdd;
    
    #Call java functions
    def Obj_PythonPrint(self,x,y) :
        print( "Value defined in java is ",self.JavaValue );
        print( "Function result from java ",self.JavaAdd(x,y) );
    Obj.PythonPrint = Obj_PythonPrint;
    
    #define Attributes
    Obj.PythonValue = 200;
  6. Java code:
    package com.cle.pythonfromjava;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.content.res.AssetManager;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    import com.srplab.www.starcore.*;
    
    public class PytonfromjavaActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            //--init CLE
            StarCoreFactoryPath.InitDefault(Runtime.getRuntime(),
    			"/data/data/com.cle.pythonfromjava");
            
    StarCoreFactory starcore= StarCoreFactory.GetFactory();
    StarServiceClass Service=starcore._InitSimple("test","123",0,0);
    Service._CheckPassword(false);
    
    AssetManager assetManager = getAssets();     
    
            try{
                String pythonbuf;
                
                   InputStream dataSource = assetManager.open("code.py");
                   int size=dataSource.available();
                   byte[] buffer=new byte[size]; 
                   dataSource.read(buffer); 
                   dataSource.close();        
                   pythonbuf=new String(buffer);
                   
                Service._RunScript("python",pythonbuf,"cmd","");
            }
            catch(IOException e ){
            }   
            
    StarObjectClass a = Service._GetObject("TestClass")._New()._Assign(new StarObjectClass(){
       public int JavaAdd(StarObjectClass self,int x,int y){
           System.out.println("Call java function...");
           return x+y;
       }
    });
            a._Set("JavaValue",100);
            System.out.println(a._Get("PythonValue")); 
            System.out.println(a._Call("PythonAdd",12,34));           
            a._Call("PythonPrint",56,78);
        }
    
    }

Method2 source code (install cle from http://code.google.com/p/cle-for-android independently):

  1. Install SL4A from http://code.google.com/p/android-scripting/downloads/list
  2. Install CLE from http://code.google.com/p/cle-for-android/downloads/list
  3. Download devfiles from http://code.google.com/p/cle-for-android, and then Open Eclipse
  4. Create project for Android
  5. Python code:
    Same as method 1
  6. Java code:
    Delete the following code line. Others are the same as method1.
    StarCoreFactoryPath.InitDefault(Runtime.getRuntime(),
    			"/data/data/com.cle.pythonfromjava");

Examples may be downloaded from http://www.srplab.com/android/calling_python_from_java.rar.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

li9705

China China
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 28 Feb 2012
Article Copyright 2012 by li9705
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid