應用Rhino讓java履行javascript的辦法實例。本站提示廣大學習愛好者:(應用Rhino讓java履行javascript的辦法實例)文章只能為提供參考,不一定能成為您想要的結果。以下是應用Rhino讓java履行javascript的辦法實例正文
下載Rhino https://developer.mozilla.org/en-US/docs/Rhino
把js.jar拷貝到項目工程
完成從Java中履行js中的函數、從js中挪用Java中的辦法,代碼:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text1 = (TextView) findViewById(android.R.id.text1);
TextView text2 = (TextView) findViewById(android.R.id.text2);
text1.setText(runScript(JAVA_CALL_JS_FUNCTION, "Test", new String[] {}));
text2.setText(runScript(JS_CALL_JAVA_FUNCTION, "Test", new String[] {}));
}
/** Java履行js的辦法 */
private static final String JAVA_CALL_JS_FUNCTION = "function Test(){ return '農人伯伯 java call js Rhino'; }";
/** js挪用Java中的辦法 */
private static final String JS_CALL_JAVA_FUNCTION = //
"var ScriptAPI = java.lang.Class.forName(\"" + MainActivity.class.getName() + "\", true, javaLoader);" + //
"var methodRead = ScriptAPI.getMethod(\"jsCallJava\", [java.lang.String]);" + //
"function jsCallJava(url) {return methodRead.invoke(null, url);}" + //
"function Test(){ return jsCallJava(); }";
/**
* 履行JS
*
* @param js js代碼
* @param functionName js辦法稱號
* @param functionParams js辦法參數
* @return
*/
public String runScript(String js, String functionName, Object[] functionParams) {
Context rhino = Context.enter();
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(MainActivity.this, scope));
ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(MainActivity.class.getClassLoader(), scope));
rhino.evaluateString(scope, js, "MainActivity", 1, null);
Function function = (Function) scope.get(functionName, scope);
Object result = function.call(rhino, scope, scope, functionParams);
if (result instanceof String) {
return (String) result;
} else if (result instanceof NativeJavaObject) {
return (String) ((NativeJavaObject) result).getDefaultValue(String.class);
} else if (result instanceof NativeObject) {
return (String) ((NativeObject) result).getDefaultValue(String.class);
}
return result.toString();//(String) function.call(rhino, scope, scope, functionParams);
} finally {
Context.exit();
}
}
public static String jsCallJava(String url) {
return "農人伯伯 js call Java Rhino";
}
}
留意,混雜的時刻js.jar能夠混雜不外去,請參照文章4.1的辦法。