Rhino是什么
Rhino是一种基于Java的JavaScript引擎。它允许在Java应用程序中嵌入JavaScript脚本,从而实现动态脚本功能。Rhino是由Mozilla基金会开发的,它是开源的,并且可以在商业和非商业应用程序中免费使用。Rhino支持ECMAScript 5.1标准,并提供了许多扩展功能,例如Java和JavaScript之间的无缝交互。
Rhino在android上运行
引入rhino库
implementation 'org.mozilla:rhino:1.7.14'
java中执行script
public static void testExecuteScriptInJava() {
Context context = Context.enter();
context.setOptimizationLevel(-1);// 关闭Rhino的优化,加速加载
try {
Scriptable scope = context.initStandardObjects();
String jsStr = "var name = 'July';";
context.evaluateString(scope, jsStr, null, 1, null);
Object jsObject = scope.get("name", scope);
if (jsObject == Scriptable.NOT_FOUND) {
Log.i("test","0711 name is not defined.");
} else {
Log.i("test","0711 result: " + Context.toString(jsObject));
}
} catch (Exception e) {
} finally {
Context.exit();
}
}
测试中遇到一个坑
rhino.setOptimizationLevel(-1);这句不执行的话一直报错
java中执行js文件
public static void testLoadJSFile() {
Context context = Context.enter();
context.setOptimizationLevel(-1);
LineNumberReader reader = null;
try {
Scriptable scope = context.initStandardObjects();
String filename = "/storage/emulated/0/Android/data/com.xxx.AndroidNew/files/Documents//user/webApp/app/messageCenter/js/HelloWorld.js";
reader = new LineNumberReader(new FileReader(filename));
String temp = null;
StringBuffer sb = new StringBuffer();
while ((temp = reader.readLine()) != null) {
sb.append(temp).append("\n");
}
context.evaluateString(scope, sb.toString(), null, 1, null);
Object result = context.evaluateString(scope, "calculateSum(5, 3);", "<cmd>", 1, null);
Log.i("test","0711 result: " + Context.toString(result));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Context.exit();
}
}