平时开发难免要加载h5页面,本人结合项目自己总结的一些小心得,希望能让我这样的新手可以少走一些弯路,文章会因为本人遇到的问题做随时更新
android api:31 ,语言:kotlin ,插件:viewbinding
1.基本设置
添加权限
<manifest>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
注册文件设置网络安全配置文件
<manifest>
<application
android:networkSecurityConfig="@xml/network_security_config">
</application>
</manifest>
network_security_config(在res->xml文件夹下创建network_security_config.xml)
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
设置控件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/loading"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:indeterminate="true"
android:indeterminateTint="#ff31b798" />
</RelativeLayout>
在活动中加载控件
val url = "https://www.baidu.com"
binding.webView.loadUrl(url)
binding.webView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
binding.loading.visibility = View.VISIBLE
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
binding.loading.visibility = View.GONE
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
return false
}
@SuppressLint("WebViewClientOnReceivedSslError")
override fun onReceivedSslError(
view: WebView?,
handler: SslErrorHandler?,
error: SslError?
) {
handler?.proceed()
}
}
websettings设置
binding.webView.settings.apply {
javaScriptEnabled = true
useWideViewPort = true
loadWithOverviewMode = true
setSupportZoom(false)
builtInZoomControls = false
displayZoomControls = false
javaScriptCanOpenWindowsAutomatically = true
loadsImagesAutomatically = true
defaultTextEncodingName = "utf-8"
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
}
2.当h5地址与h5内图片加载的网络协议不一样导致图片加载不出时处理方法
binding.webView.settings.apply {
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
}
3. 实体返回按键实现网页后退
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KEYCODE_BACK && binding.webView.canGoBack()) {
binding.webView.goBack()
return true
}
return super.onKeyDown(keyCode, event)
}
4. Android通过localStorage给h5传值
binding.webView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
binding.inLoading.loading.visibility = View.VISIBLE
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
val js = "window.localStorage.setItem('token','${token}');"
val jsUrl = "javascript:localStorage.setItem('token','${token}');"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
view?.evaluateJavascript(js, null)
} else {
view?.loadUrl(jsUrl)
view?.reload()
}
binding.inLoading.loading.visibility = View.GONE
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
return false
}
@SuppressLint("WebViewClientOnReceivedSslError")
override fun onReceivedSslError(
view: WebView?,
handler: SslErrorHandler?,
error: SslError?
) {
handler?.proceed()
}
}
H5操作
window.localStorage.getItem("token")
5. android与h5的交互(webview内点击h5按钮跳转android外部浏览器)
binding.webView.addJavascriptInterface(JavaScriptInterface(this), "android")
class JavaScriptInterface internal constructor(context: Context){
@JavascriptInterface
fun openAndroidBrowser(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
}
h5操作
android.openAndroidBrowser("https://www.baidu.com")
6. 多窗口设置(webView点击target=_blank无反应)
当点击webview内按钮没反应时候你就该考虑是不是前端做了target=_blank开启浏览器新窗口的处理
binding.webView.settings.apply {
javaScriptCanOpenWindowsAutomatically = true
setSupportMultipleWindows(true)
}
binding.webView.webChromeClient = object : WebChromeClient() {
override fun onCreateWindow(
view: WebView,
isDialog: Boolean,
isUserGesture: Boolean,
resultMsg: Message
): Boolean {
val newWebView = WebView(view.context)
newWebView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
binding.webView.loadUrl(request?.url.toString())
return false
}
}
val transport = resultMsg.obj as WebView.WebViewTransport
transport.webView = newWebView
resultMsg.sendToTarget()
return true
}
}
觉得有用的点个赞👍!
|