1.去rhino官网https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino下载rhino.jar,部分高版本的jar包包含了jdk1.8的内容,如果android gradle 做了以下配置
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
建议使用rhino1.7.6版本,否则高版本编译不过。
2.将下载好的jar包添加到android工程
3.以下为一个调用js函数例子,在android asset目录下添加了一个fridge.js文件,文件里面有一个函数
function firdgeJsonToShadow(fridgeJson) {...}
public static void fridgeJsonToShadow(String fridgeJson) {
try {
InputStream inputStream = MyApplication.getAppContext().getResources().getAssets().open("fridge.js");
InputStreamReader reader = new InputStreamReader(inputStream);
org.mozilla.javascript.Context ctx = org.mozilla.javascript.Context.enter();
//添加这一行的目的是禁止优化,因为优化后可能报错
ctx.setOptimizationLevel(-1);
Scriptable scope = ctx.initStandardObjects();
// scope.put("param1", scope, "value1");
// String jsStr = "var testFunc = function(param){ return 'testFunc...'+'param='+param }; testFunc(param1);";
Object result = ctx.evaluateReader(scope, reader, null, 0, null);
Object fObj = scope.get("firdgeJsonToShadow", scope);
Function f = (Function)fObj;
//最后一个参数是传给函数的参数
String ret = (String) f.call(ctx, scope, scope, new String[]{fridgeJson});
reader.close();
Log.d("","ret:"+ret);
} catch (Exception e) {
e.printStackTrace();
}
}