webview与kotlin相互调用
2020-07-21 本文已影响0人
JaosnZhao
调用本地HTML示范
1595306906(1).pngjs调用kotlin(assert中的html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carson</title>
</head>
<body>
<script>
var json = "js调用了android中的hello方法";
function callAndroid(){
// 由于对象映射,所以调用test对象等于调用Android映射的对象
test.showToast(json);
}
function showMessage(str){
alert(str);
}
</script>
<button type="button" id="button1" onclick="callAndroid()">点击按钮则调用callAndroid函数</button>
</body>
</html>
中间桥梁类(js调用kotlin的时候规范test)
class JavaScriptMe {
private var mContext : Context ?= null
constructor(mContext: Context?) {
this.mContext = mContext
}
@JavascriptInterface
fun showToast(json:String){
mContext?.let {
it.toast(json)
}
}
}
具体调用
class MainActivity : AppCompatActivity() {
private val mWebView:WebView by lazy {
tv
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setWebView()
}
var setWebView = {
//开启Kotlin与H5通信的开关
mWebView.settings.javaScriptEnabled = true
//设置2个WebViewClient
mWebView.webViewClient = MyWebView()
mWebView.webChromeClient = MyWebViewSec();
//H5与kotlin 通信方式
//1.h5调用kotlin
//设置通信桥梁类
mWebView.addJavascriptInterface(JavaScriptMe(this),"test")
mWebView.loadUrl("file:///android_asset/test.html");
}
private inner class MyWebView : WebViewClient(){
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
//kotlin调用js
//JS定义String变量的时候用单引号,而JAVA是使用双引号。
var json = "kotlin调用js"
mWebView.loadUrl("javascript:showMessage('$json')")
}
}
private class MyWebViewSec : WebChromeClient(){
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
}
}
}
callback机制
桥梁(js决定方法名)
class JavaScriptMe {
private var mContext : Context ?= null
private var mWebView : WebView ?= null
constructor(mContext: Context?,mWebView: WebView?) {
this.mContext = mContext
this.mWebView = mWebView
}
@JavascriptInterface
fun showToast(json:String){
mContext?.let {
it.toast(json)
}
}
//callback (js嗲用kotlin)
@JavascriptInterface
fun getHotelData(method : String){
var d = "获取酒店的数据"
println(d)
// callback 回传数据
mContext?.let {
it.runOnUiThread {
mWebView?.let {
it.loadUrl("javascript:$method('$d')")
}
}
}
}
}
HTML类
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carson</title>
</head>
<body>
<script>
var json = "js调用了android中的hello方法";
function callAndroid(){
// 由于对象映射,所以调用test对象等于调用Android映射的对象
test.showToast(json);
}
function showMessage(str){
alert(str);
}
//callback (js调用kotlin)
function callKotlin(){
//前后端分离方法传递给kotlin
var method = "showMessage"
test.getHotelData(method)
}
</script>
<button type="button" id="button1" onclick="callAndroid()">点击按钮则调用callAndroid函数</button>
<button type="button" id="button2" onclick="callKotlin()">js调用kotlin方法(callback)</button>
</body>
</html>