Android 端运行 JavaScript 代码 (1)
需要搭建一个 JavaScript 运行环境, 好处一些写在 JavaScript 项目中代码我们可以在 Android 项目中复用, 例如校验, 解析和一些业务逻辑. 具体在产品中如何使用还是根据实际情况而定.
1. 安装 JavaScript 运行环境
有两种方式可以将 JS-evaluator-for-Android 引入到项目中
第一方式
在项目的 build.gradle 文件中添加依赖仓图allprojects{
repositories{
jcenter()
maven{url"https://jitpack.io"}
}
}
在模块的 build.gradle 文件中添加依赖dependencies{
implementation fileTree(dir:'libs',include:['*.jar'])
// Keep you existing dependencies here
implementation'com.github.evgenyneu:js-evaluator-for-android:v5.0.0'
}
在本地直接引入 jsevaluator-1.0.aar 文件
下载 jsevaluator-1.0.aar 文件
编译文件, 在项目的 build.gradle 文件里dependencies{
implementation(name:'jsevaluator-1.0',ext:'aar')
}
2. 如何使用使用jsEvaluator.evaluate("2 * 17",newJsCallback(){
@Override
publicvoidonResult(Stringresult){
// Process result here.
// This method is called in the UI thread.
}
@Override
publicvoidonError(StringerrorMessage){
// Process JavaScript error here.
// This method is called in the UI thread.
}
});
JavaScript 被执行的是异步的
对 JavaScript 进行执行不会影响到 UI 线程因为这一切都是异步的. 执行结果会返回到 UI 线程. It is required to call evaluate and callFunction in UI thread.
来源: http://www.jianshu.com/p/730c4adda3a2