Download Rhino Https://developer.mozilla.org/en-US/docs/Rhino
Copy Js.jar to Project engineering
Implementation of Java in the implementation of the functions in JS, from the JS call Java method, code:
Copy Code code as follows:
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 to execute JS method * *
private static final String java_call_js_function = "FUNCTION Test () {return ' farmer Uncle JAVA call JS Rhino ';}";
/** JS calls methods in JAVA */
private static final String js_call_java_function =//< br> "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 ();}";
/**
* Execute JS
*
* @param js JS code
* @param functionname js method name
* @param fun Ctionparams js Method Parameters
* @return
*/
Public String RunScript (String js, string functionname, object[] functionparams) {
& nbsp; 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 "Farmer Uncle JS call Java Rhino";
}
}
Note that Js.jar may not be confusing when confused, please refer to Article 4.1 's method.