本地的HTML
<!DOCTYPE html>
< html>
< head>
< meta charset = " utf-8" >
< title> 测试</ title>
< script>
function callAndroid ( ) {
AndroidApi. hello ( "JS调用了android中的hello方法" ) ;
}
function onBackPressed ( ) {
var con= confirm ( "Android调用JS,确定要关闭页面?" ) ;
if ( con== true ) AndroidApi. finishActivity ( ) ;
return "JS的返回值,Android可以接收到"
}
</ script>
</ head>
< body>
< button type = " button" id = " button1" onclick = " callAndroid()" > 点击调用Android代码</ button>
</ body>
</ html>
MainActivity
class MainActivity : AppCompatActivity ( ) {
override fun onCreate ( savedInstanceState: Bundle? ) {
super . onCreate ( savedInstanceState)
setContentView ( R. layout. activity_main)
initData ( )
}
private fun initData ( ) {
val test = "file:///android_asset/javascript.html"
CommonWebViewActivity. start ( this , test)
}
}
CommonWebViewActivity
private const val TAG = "CommonWebViewActivity"
class CommonWebViewActivity : AppCompatActivity ( ) {
companion object {
private const val EXTRA_URL = "extra_url"
fun start ( context: Context, url: String) {
val starter = Intent ( context, CommonWebViewActivity:: class . java)
starter. putExtra ( EXTRA_URL, url)
context. startActivity ( starter)
}
}
private lateinit var binding: ActivityWebviewBinding
private lateinit var webViewJSInterface: WebViewJSInterface
@SuppressLint ( "SetJavaScriptEnabled" , "JavascriptInterface" )
override fun onCreate ( savedInstanceState: Bundle? ) {
super . onCreate ( savedInstanceState)
binding = DataBindingUtil. setContentView ( this , R. layout. activity_webview)
binding. lifecycleOwner = this
webViewJSInterface = WebViewJSInterface ( this @CommonWebViewActivity , binding. webView)
binding. webView. apply {
settings. javaScriptEnabled = true
addJavascriptInterface ( webViewJSInterface, "AndroidApi" )
}
binding. webView. webChromeClient = WebChromeClient ( )
initData ( )
}
private fun initData ( ) {
val url = intent. getStringExtra ( EXTRA_URL) !!
Log. d ( TAG, "loadUrl: $url " )
binding. webView. loadUrl ( url)
}
override fun onBackPressed ( ) {
webViewJSInterface. onBackPressed ( )
}
}
WebViewJSInterface
class WebViewJSInterface ( private val activity: Activity, private val webView: WebView) {
@JavascriptInterface
fun hello ( msg: String) {
Log. d ( TAG, "hello: $msg " )
Toast. makeText ( activity, "msg=$msg " , Toast. LENGTH_SHORT) . show ( )
}
@JavascriptInterface
fun finishActivity ( ) {
activity. finish ( )
}
fun onBackPressed ( ) {
webView. evaluateJavascript ( "javascript:onBackPressed()" ) {
Log. d ( TAG, "onBackPressed: $it " )
}
}
}
参考资料