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

初始化DuktapeEngNine

 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);
    duktapeEngine = new DuktapeEngine();
    duktapeEngine.init();
    duktapeEngine.register("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


Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务