一区二区三区日韩精品-日韩经典一区二区三区-五月激情综合丁香婷婷-欧美精品中文字幕专区

分享

How to execute JavaScript on Android

 quasiceo 2015-07-03
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have code which uses ScriptEngineManager, ScriptEngine class for executing JavaScript code using Java. But it works fine in Java SE, and doesn't work in Android - SDK show error of missing classes. Is it possible to execute JS code in Android? Thank you.

asked Dec 4 '11 at 7:50
user1078760
2191317

1  
FYI, if the search engine is broken I am sure google will find a couple of the duplicates in here. The "related" block to the right lists at least one of them. –  Fredrik Dec 4 '11 at 7:57
    

8 Answers

You can use Webview which inherits View class. Make an XML tag and use findViewById() function to use in the activity. But to use the JavaScript, you can make a HTML file containing the JavaScript code. The example blelow might help.

Webview browser=(Webview) findViewById(R.main.browser); //if you gave the id as browser
browser.getSettings().setJavaScriptEnabled(true); //Yes you have to do it
browser.loadUrl("file:///android_asset/JsPage.html"); //If you put the HTML file in asset folder of android

Remember that the JS will run on WebView, not in native environment, thus you might experience a lag or slow FPS in emulator. However when using on an actual phone, the code may run fast, depending on how fast is your phone.

answered Dec 4 '11 at 9:40
noob
5,40423461

http://divineprogrammer./2009/11/javascript-rhino-on-android.html will get you started. ScriptEngine is a java thing. Android doesn't have a JVM but a DalvikVM which is not identical but similar.

answered Dec 4 '11 at 8:02
Fredrik
4,45511424

Here is a little library I wrote for evaluating JavaScript:

https://github.com/evgenyneu/js-evaluator-for-android

jsEvaluator.evaluate("function hello(){ return 'Hello world!'; } hello();", new JsCallback() {
  @Override
  public void onResult(final String result) {
    // get result here (optional)
  }
});

It creates a WebView behind the scenes. Works on Android version 3 and newer.

answered Mar 15 '14 at 0:35
Evgenii
4,88933959

The javax.script package is not part of the Android SDK. You can execute JavaScript in a WebView, as described here. You perhaps can use Rhino, as described here. You might also take a look at the Scripting Layer for Android project.

answered Dec 4 '11 at 8:03
Ted Hopp
137k21189281

AndroidJSCore is an Android Java JNI wrapper around Webkit's JavaScriptCore C library. It is inspired by the Objective-C JavaScriptCore Framework included natively in iOS 7. Being able to natively use JavaScript in an app without requiring the use of JavaScript injection on a bloated, slow, security-constrained WebView is very useful for many types of apps, such as games or platforms that support plugins. However, its use is artificially limited because the framework is only supported on iOS. Most developers want to use technologies that will scale across both major mobile operating systems. AndroidJSCore was designed to support that requirement.

For example, you can share Java objects and make async calls:

public interface IAsyncObj {
    public void callMeMaybe(Integer ms, JSValue callback) throws JSException;
}
public class AsyncObj extends JSObject implements IAsyncObj {
    public AsyncObj(JSContext ctx) throws JSException { super(ctx,IAsyncObj.class); }
    @Override
    public void callMeMaybe(Integer ms, JSValue callback) throws JSException {
        new CallMeLater(ms).execute(callback.toObject());
    }

    private class CallMeLater extends AsyncTask<JSObject, Void, JSObject> {
        public CallMeLater(Integer ms) {
            this.ms = ms;
        }
        private final Integer ms;
        @Override
        protected JSObject doInBackground(JSObject... params) {
            try {
                Thread.sleep(ms);
            } catch (InterruptedException e) {
                Thread.interrupted();
        }
            return params[0];
        }

        @Override
        protected void onPostExecute(JSObject callback) {
            JSValue args [] = { new JSValue(context,
                    "This is a delayed message from Java!") };
             try {
                 callback.callAsFunction(null, args);
             } catch (JSException e) {
                 System.out.println(e);
             }
        }
    }
}

public void run() throws JSException {
    AsyncObj async = new AsyncObj(context);
    context.property("async",async);
    context.evaluateScript(
        "log('Please call me back in 5 seconds');\n" +
        "async.callMeMaybe(5000, function(msg) {\n" +
        "    alert(msg);\n" +
        "    log('Whoomp. There it is.');\n" +
        "});\n" +
        "log('async.callMeMaybe() has returned, but wait for it ...');\n"
    );
}
answered May 30 '14 at 14:39
Eric Lange
248313

Given that ScriptEngineManager and ScriptEngine are part of the JDK and Android SDK is not the same thing as the JDK I would say that you can't use these classes to work with JavaScript under Android.

You can check the Android SDK's reference documentation/package index to see what classes are included (what can you work on Android out of the box) and which of them are missing.

answered Dec 4 '11 at 8:01
Kohányi Róbert
4,02111850

I just found the App JavaScript for Android, which is the Rhino JavaScript engine for Java. It can use all Java-classes, so it has BIG potential. The problem is it might be slow, since it is not really optimized (heavy CPU load). There is another JavaScript engine named Nashorn, but that unfortunately doesn't works on Google's DalvikVM Java engine (does not support the optimizations of Oracle Java engine). I hope Google keeps up with that, I would just love it!

answered Apr 15 '14 at 13:36
lama12345
6101612

You can use Rhino library to execute JavaScript without WebView.

Download Rhino first, unzip it, put the js.jar file under libs folder. It is very small, so you don't need to worry your apk file will be ridiculously large because of this one external jar.

Here is some simple code to execute JavaScript code.

Object[] params = new Object[] { "javaScriptParam" };

// 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();

    // 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, javaScriptCode, "JavaScript", 1, null);

    // Get the functionName defined in JavaScriptCode
    Object obj = scope.get(functionNameInJavaScriptCode, scope);

    if (obj instanceof Function) {
        Function jsFunction = (Function) obj;

        // Call the function with params
        Object jsResult = jsFunction.call(rhino, scope, scope, params);
        // Parse the jsResult object to a String
        String result = Context.toString(jsResult);
    }
} finally {
    Context.exit();
}

You can see more details at my post.

    本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多

    日本精品中文字幕人妻| 亚洲午夜福利视频在线| 亚洲成人黄色一级大片| 国产成人精品在线一区二区三区| 永久福利盒子日韩日韩| 一区二区三区18禁看| 女生更色还是男生更色| 大香蕉再在线大香蕉再在线| 国产午夜精品在线免费看| 九九热精品视频在线观看| 精品人妻少妇二区三区| 欧美午夜一级艳片免费看| 国产综合欧美日韩在线精品| 亚洲一区二区三区在线免费| 国产精品一区二区高潮| 国产精品偷拍一区二区| 日本高清中文精品在线不卡| 国产成人精品资源在线观看| 日韩欧美国产精品自拍| 国产精品日韩欧美第一页| 亚洲内射人妻一区二区| 国产精品欧美一级免费| 国产亚洲午夜高清国产拍精品| 中国黄色色片色哟哟哟哟哟哟| 国产精品内射视频免费| 东北老熟妇全程露脸被内射| 日韩av生活片一区二区三区| 青青草草免费在线视频| 1024你懂的在线视频| 日韩亚洲精品国产第二页| 好骚国产99在线中文| 亚洲精品av少妇在线观看| 中文字幕日韩欧美一区| 国产丝袜极品黑色高跟鞋| 日韩黄片大全免费在线看| 国产精品视频第一第二区| 国产一区二区三区免费福利| 欧美三级大黄片免费看| 伊人欧美一区二区三区| 东北老熟妇全程露脸被内射| 日本二区三区在线播放|