Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- / class ScriptAPI
- // These lines set the log method in the JavaScript
- // Any Java classes or methods can be accessed with **Packages** prefix
- private static final String RHINO_LOG = "var log = Packages.io.vec.ScriptAPI.log;";
- public static void log(String msg) {
- android.util.Log.i("RHINO_LOG", msg);
- }
- public void runScript() {
- // Get the JavaScript in previous section
- String source = getScriptFromServer();
- String functionName = "hello";
- Object[] functionParams = new Object[] { "Android" };
- // Every Rhino VM begins with the enter()
- // This Context is not Android's Context
- Context rhino = Context.enter();
- // Turn off optimization to make Rhino Android compatible
- rhino.setOptimizationLevel(-1);
- try {
- Scriptable scope = rhino.initStandardObjects();
- // This line set the javaContext variable in JavaScript
- ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(androidContextObject, scope));
- // Note the forth argument is 1, which means the JavaScript source has
- // been compressed to only one line using something like YUI
- rhino.evaluateString(scope, RHINO_LOG + source, "ScriptAPI", 1, null);
- // We get the hello function defined in JavaScript
- Function function = (Function) scope.get(functionName, scope);
- // Call the hello function with params
- NativeObject result = (NativeObject) function.call(rhino, scope, scope, functionParams));
- // After the hello function is invoked, you will see logcat output
- // Finally we want to print the result of hello function
- String foo = (String) Context.jsToJava(result.get("foo", result), String.class);
- log(foo);
- } finally {
- // We must exit the Rhino VM
- Context.exit();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement