Reference javax.script.ScriptEngine in android or evaluate a javascript expression

Is it possible to reference the javax.script.ScriptEngine library when developing an android application? If not is there anyway possible to evaluate a javascript expression in android?


Solution 1:

For the classes javax.script.ScriptEngine, javax.script.ScriptEngineFactory and so on, you can add the jsr223.jar to your Android project: just copy the .jar file to your libs directory, and add it from Properties->Java Build Path.

These class will allow your JSR 223-compliant engines to compile. You can then do new SomeScriptEngienFactory().getScriptEngine() to get an engine. I've managed to do this with JNLua 1.0.4 and Rhino 1.7R2.

The file jsr223.jar can be downloaded from http://www.java2s.com/Code/Jar/j/Downloadjsr223jar.htm, a direct link is http://www.java2s.com/Code/JarDownload/jsr223/jsr223.jar.zip.

Solution 2:

javax.script.ScriptEngine is not a default part of android, but you could easily jar up any libraries you need(assuming the size is reasonable, I'm not sure) and include them in your project.

Solution 3:

According to this post, javax.script.ScriptEngine is not available in Android SDK. You can try the steps below to include the library, but the code may not run, even though it will compile.

Using Android Development Toolkit in Windows, I performed the following steps to get javax.script library.

  1. Right-clicked on the project, went to Properties (Project).
  2. Under the Java Build Path, I chose Libraries tab.
  3. Select Add Library located on the middle right of the Tab
  4. Select JRE System Library under Add Library and click Next...
  5. Select Workspace Default JRE (jre 7)
  6. Click Finish.
  7. Click Ok on the Java Build Path to exist project properties.

Javax.script was then loaded.

Solution 4:

If you want to evaluate some code in JS in android

1) to your gradle dependencies add (rhino):

compile 'org.mozilla:rhino:1.7R4'

2) write some code like this to get the result of JS evaluation

Context rhino = Context.enter()
// turn off optimization to work with android
rhino.optimizationLevel = -1

String evaluation = "2+2"

try {
    ScriptableProject scope = rhino.initStandardObjects()
    String result = rhino.evaluateString(scope, evaluation, "JavaScript", 1, null).toString()
} finally {
    Context.exit()
}

3) You can write more complex scripts in JS to run in the android app also (functions etc.)