打电话、发邮件(html页面)
需求:html 页面调用打电话、发邮件功能
<a href="tel:1234567890">拨打电话</a>
<a href="mailto:example@example.com">发送邮件</a>
webView.loadUrl("file:///android_asset/demo.html")
webView.settings.javaScriptEnabled = true
webView.webViewClient = object :WebViewClient(){
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
val url = request?.url.toString()
if (url.startsWith("tel:")){
val intent = Intent(Intent.ACTION_DIAL , Uri.parse(url))
startActivity(intent)
return true ;
}else if(url.startsWith("mailto:")){
val intent = Intent(
Intent.ACTION_SENDTO,
Uri.parse(url)
)
startActivity(intent)
return true ;
}
return super.shouldOverrideUrlLoading(view, request)
}
}
Js调Java方法
javascipt调用java的方法
<button onclick="AndroidInterface.showToast('Hello from JavaScript')">调用Java方法</button>
//定义javascript接口类
inner class MyJavaScriptInterface {
@JavascriptInterface
fun showToast(message: String?) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show()
}
}
//添加
webView.addJavascriptInterface(MyJavaScriptInterface(),"AndroidInterface")
Java调js方法
java层调html定义的javascript方法
<script>
function javascriptMethodName(parameter) {
// 获取<h1>元素
var h1Element = document.querySelector("h1");
// 修改<h1>元素的内容
h1Element.textContent = "新的标题: "+parameter;
return "ok from html5"
}
</script>
findViewById<Button>(R.id.btn).setOnClickListener{
val time = System.currentTimeMillis()
webView.evaluateJavascript("javascriptMethodName($time)" ,object : ValueCallback<String>{ //当html方法结束,会执行的回调函数
override fun onReceiveValue(value: String?) {
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show()
}
})
}