DuktapeJava - Android平台的JavaScript引擎


MIT
跨平台
Java

软件简介

DuktapeJava 是针对 Android 平台封装的 Duktape JavaScript 引擎;实现Javascript 和 Java的无缝调用。

初始化DuktapeEngnine

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);
    duktapeEngine = new DuktapeEngine();
    duktapeEngine.put("activity",this);
    duktapeEngine.execute(AssetScript.toScript(getBaseContext(), "duk.js"));
    duktapeEngine.call("activityListener", "onCreate", savedInstanceState);
}

@Override 
protected void onDestroy() { 
    if (duktapeEngine != null) {
        duktapeEngine.destory();
        duktapeEngine = null;
    } super.onDestroy();
}

duk.js javascript 代码示例

importClass("com.furture.react.R")
importClass("android.view.View.OnClickListener")
importClass("android.widget.Toast")
importClass("java.lang.Runnable")

var activityListener = {};
activityListener.onCreate = function(){
        print("activity onCreate onJavaScript");
        activity.setContentView(R.layout.activity_duk)
        button1 = activity.findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener(function(){
            Toast.makeText(activity, "Button1 Clicked", Toast.LENGTH_SHORT).show(); 
            var intent = new Intent(activity, "com.furture.react.activity.DetailActivity");
            activity.startActivity(intent);
        }));

    button2 = activity.findViewById(R.id.button2);
    button2.setOnClickListener(new OnClickListener({
        onClick:function(){ 
           Toast.makeText(activity, "Button2 Clicked", Toast.LENGTH_SHORT).show();
        }
    }));
}

activityListener.onStart = function(){
    print("activity onStart");
}

activityListener.onResume = function(){ 
   print("activity onResume");
}


activityListener.onPause = function(){ 
    print("activity onPause");
}

activityListener.onStop = function(){ 
    print("activity onStop");
}

activityListener.finish = function(){ 
    print("activity finish" + num);
}

Java 和 Javascript 的无缝调用

javascript 调用java方法示例:

importClass("android.widget.Toast")

Toast.makeText(activity, "Javascript toast", Toast.LENGTH_SHORT).show();

Java 还可以在 JavaScript 的对象方法示例:

importClass("com.efurture.react.DataUtils")

var data = {}; 
data.count =  10; 
data.getItem = function(var index){ 
      return "Javascript Data " + index;
}

DataUtils.showData(data);

DataUtils.Java 代码示例:

public class DataUtils{ 
public static void showData(JSRef data){
         DuktapeEngine  engine =  data.getEngine();
         int count = (Integer)engine.call(data, "count");
          for(int i=0; i



**项目github地址:**[ **https://github.com/gubaojian/DuktapeJava**](https://github.com/gubaojian/DuktapeJava)