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

后端 未结 4 945
南方客
南方客 2020-11-30 13:02

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

4条回答
  •  时光取名叫无心
    2020-11-30 13:31

    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.)

提交回复
热议问题