问题描述
我有code,它使用ScriptEngineManager,的ScriptEngine类执行使用Java的JavaScript code。但它工作正常,在Java SE,并在Android中并不奏效 - 缺课的SDK显示错误。是否有可能在Android的执行JS code?谢谢。
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.
推荐答案
您可以使用web视图继承View类。做一个XML标记,并使用 findViewById()
功能在活动中使用。但是,使用JavaScript,你可以创建包含JavaScript的code一个HTML文件。这个例子blelow可能的帮助。
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
记住,JS将运行在web视图,而不是在本地环境中,因此,你可能会遇到在模拟器上滞后或缓慢的FPS。但是用在实际的手机的时候,在code可以跑得快,这取决于有多快你的电话。
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.
这篇关于如何在Android上执行JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!