我使用 J2V8 为 android 创建了代码用于在 android mobile 中执行 nodejs 脚本的库。但是当我运行应用程序时它给了我错误。
Gradle 依赖项
compile 'com.eclipsesource.j2v8:j2v8:4.6.0@aar'
代码
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_console);
runScript();
}
private void runScript() {
NodeJS nodeJS = NodeJS.createNodeJS();
try {
File script = createTempScript("console.log(\"Hello NodeJS\")");
nodeJS.exec(script);
script.delete();
} catch (Exception e) {
e.printStackTrace();
} finally {
nodeJS.release();
}
}
private File createTempScript(String script) throws IOException {
File file = File.createTempFile("temp",".js", getCacheDir());
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(script);
fileWriter.close();
return file;
}
...
错误
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.asissuthar.lion/in.asissuthar.lion.ConsoleActivity}: java.lang.UnsupportedOperationException:
StartNodeJS Not Supported.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2348)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)
请帮我解决这个错误。
普通 V8 引擎工作正常,但上面 createNodeJS
给出错误。
V8 v8 = V8.createV8Runtime()
最佳答案
根本原因
J2V8 库包含一个 JAR 和一个包含 v8 引擎的本地库。在您的情况下,JNI native 库未使用 -D NODE_COMPATIBLE=1
选项编译,因此您会收到以下错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.asissuthar.lion/in.asissuthar.lion.ConsoleActivity}: java.lang.UnsupportedOperationException: StartNodeJS Not Supported.
这可以通过查看 J2V8 代码来断言。我在下面添加了一个 fragment :
#ifndef NODE_COMPATIBLE
(env)->ThrowNew(unsupportedOperationExceptionCls, "StartNodeJS Not Supported.");
#endif
可能的解决方案:
- 您需要使用
-D NODE_COMPATIBLE=1
选项重新编译 JNI 源代码。源代码位于 https://github.com/eclipsesource/J2V8
或
- 在他们的 github 上提出一张票,以便他们可以使用更新的本地库更新 aar,并支持 Node 。
关于java - 如何使用 J2V8 在 Android 中使用 NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42574824/