一 : 主类
class MainActivity : AppCompatActivity() {
/**
* 懒加载
*/
private val mWebView:WebViewby lazy{
m_WebView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//1.开启Kotlin与H5通信的开关
setWebView()
}
//lamada
// var add = {a:int,b:int -> a+b}
var setWebView ={
m_WebView.settings.javaScriptEnabled =true
//2.设置两个Client
m_WebView.webViewClient = MyWebviewClient()
m_WebView.webChromeClient = MyWebChromeClient()
//kotlin与H5通信开关
//设置桥梁类
//对象.方法名 对象的别名
//H5调用kotlin
m_WebView.addJavascriptInterface(JavaScriptMethods(this,m_WebView),"jsInterface")
m_WebView.loadUrl("file:///android_asset/javascript.html")
}
inner private class MyWebviewClient :WebViewClient(){
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
//kotlin主动调用H5
// m_WebView.loadUrl("javascript:方法名(参数)")
var json = JSONObject()
json.put("name","kotlin")
m_WebView.loadUrl("javascript:message( " + json.toString() +")")
}
}
private class MyWebChromeClient :WebChromeClient(){
//控制加载进度条
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
}
}
}
二:桥梁
class JavaScriptMethods {
private var mContent:Context? =null
private var mWebview:WebView? =null
constructor(mContent: Context?,webview:WebView?) {
this.mContent = mContent
this.mWebview = webview
}
@JavascriptInterface//17 4.2上能调
fun showTip(json:String){
Toast.makeText(mContent,json,Toast.LENGTH_LONG).show()
}
@JavascriptInterface
fun getStorDate(json:String){
var isJson = JSONObject(json)
//http://dev.yuedaowang.com/driverapp/v2/getParameterList
val callback = isJson.opt("callback")
println("获取酒店数据")
//异步操作在子线程操作
doAsync {
var url = URL("http://dev.yuedaowang.com/driverapp/v2/getParameterList")
//流变成字符串
val readText = url.readText()
println(readText)
//回传数据
// mWebview!!.
mContent?.let {
it.runOnUiThread {
mWebview?.let {
it.loadUrl("javascript:" + callback +"(" + readText +")")
}
}
}
}
}
}
三 :模拟的H5页面
<!DOCTYPE html>
<meta charset="UTF-8">
<title>first
function callAndroid(){
console.log("点击啦")
var json = {"name":"html5"}
jsInterface.showTip(JSON.stringify(json))
}
var message = function(json){
alert(JSON.stringify(json))
}
function callkotlin(){
console.log("callback")
var json = {"callback":"receiveHotelDate"}
//调用kotlin方法
jsInterface.getStorDate(JSON.stringify(json))
}
var receiveHotelDate = function(json){
alert(JSON.stringify(json))
}
<button id="btn1" onclick="callAndroid()">js调用kotlin方法
<button id="btn2" onclick="callkotlin()">js调用kotlin方法(calllback)
</html>
四 :附带图
网友评论