H5示例代码
android代码(基类)
abstract class BaseWebViewActivity : BaseAppActivity() {
lateinit var activityWebView : WebView
lateinit var commonbase_activity_appbar_left:ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.commonbase_activity_web_view)
activityWebView = findViewById(R.id.activityBaseWebView)
commonbase_activity_appbar_left=activityWebViewTitleInclude.findViewById(R.id.commonbase_activity_appbar_left)
setWebWs()
}
@SuppressLint("JavascriptInterface")
private fun setWebWs() {
val ws: WebSettings? = activityWebView?.settings
//这写注释先不要删掉
//ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕 //导致4.4以下摇钱树只显示背景和标题
// ws.setLoadWithOverviewMode(true);//自适应屏幕,使用后字体变小,
// ws.setAllowFileAccess(false);// 设置允许访问文件数据
// ws.setJavaScriptCanOpenWindowsAutomatically(false);//自动打开窗口
// ws.setAppCacheEnabled(false);
// ws.setSupportZoom(true);// 设置支持缩放
// ws.setBuiltInZoomControls(true);// 设置支持缩放
// ws.setDisplayZoomControls(false);//显示缩放按
ws?.setAllowFileAccess(true);// -> 是否允许访问文件
ws?.setDomStorageEnabled(false); //-> 是否节点缓存
ws?.setDatabaseEnabled(false);// -> 是否数据缓存
ws?.setAppCacheEnabled(false);// -> 是否应用缓存
ws?.loadWithOverviewMode = true
ws?.builtInZoomControls = true
ws?.displayZoomControls = false
//? ws.setAllowFileAccessFromFileURLs(false);
//? ws.setAllowFileAccessFromFileURLs(false);
ws?.useWideViewPort = true //图片被缩放后显示不全的问题
ws?.javaScriptEnabled = true
ws?.savePassword = false
ws?.blockNetworkImage = false
ws?.loadsImagesAutomatically = true
var oldUA = ws?.userAgentString
//UA都是跟h5约定好提供什么参数
val addAgent =
" AppName/(${ChicvUserAgentDataManager.getAppName()}) LanguageId/($language_id) Language/($language_code) Currency/($currency_code) CurrencyId/($country_id) WappBrowser/1.2.6 ChannelId/(1) PlatformId/(1) LastLoginTime/ Version/(${
getVersionName(MyApplication.getInstance())
}) SystemVersion/(${ChicvUserAgentDataManager.getOsVersion()})"
ws?.userAgentString = oldUA + addAgent
val timecurrentTimeMillis = System.currentTimeMillis()
val sign = MD5Util.getMD5("SECRET")
val language_id = language_id
val language_code = language_code
val currency_code = currency_code
val country_id = currencyCountry_id.toString()
activityWebView?.addJavascriptInterface(this, "local_android");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0以上默认不允许http和https混合模式, 需手动开启
ws?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
}
// activityWebView.webChromeClient = BaseWebChromeClient()
// activityWebView.webViewClient = BaseWebViewClient(activityWebViewProgressbar)
//设置cookie
syncCookie()
val token = if (GlobalFunc.hasLogin()) GlobalFunc.getAccountToken() else ""
var cookies = if (token.isNullOrEmpty()) "currency=$currency_code;language=$language_id;language-code=$language_code" else "access_token=$token;currency=$currency_code;language=$language_id;language-code=$language_code"
//设置header,给后端使用
val headerMap = mapOf(
"x-origin-client" to "Android",
)
if (getLoadUrl() != null) activityWebView?.loadUrl(getLoadUrl(), headerMap)
}
protected abstract fun getLoadUrl(): String
open fun syncCookie(): Boolean {
var url = getLoadUrl()
val cookieManager = CookieManager.getInstance()
cookieManager.setAcceptCookie(true)
cookieManager.removeSessionCookies(null)
cookieManager.removeAllCookies(null)
val token = if (GlobalFunc.hasLogin()) GlobalFunc.getAccountToken() else ""
val currency = currency_code
val language = language_id
var cookies = if (token.isNullOrEmpty()) "currency=$currency;language=$language;language-code=$language_code" else "access_token=$token;currency=$currency;language=$language;language-code=$language_code"
url.logW("currency_code2")
cookies.logW("currency_code2")
cookieManager.setCookie(url, cookies)
val newCookie = cookieManager.getCookie(url)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
val cookieSyncManager = CookieSyncManager.createInstance(mContext)
cookieSyncManager.sync()
} else {
cookieManager.flush()
}
return if (!newCookie.isNullOrEmpty()) false else true
}
}
子类
class SpecialWebViewActivity : BaseWebViewActivity() {
override val pageTag: String
get() = TraceDpType.WebView.value
var isShowCartBtn = 0//0 hidden 1 show
var isShowTopBtn = 0//0 hidden 1 show
var goodsDetailsReturRl : RelativeLayout? = null
var merchandiseCustomerRl : RelativeLayout? = null
var commonbase_num_bg : RelativeLayout? = null
var commonbase_num : TextView? = null
override fun getLoadUrl(): String {
var dataMap = intent.getSerializableExtra("param") as Map?
if (!dataMap.isNullOrEmpty() && dataMap!!.containsKey(GlobalVariable.WEB_URL)) {
return dataMap!!.get(GlobalVariable.WEB_URL) as String
} else return ""
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setWebViewClient()
setUI()
EventBusUtil.register(this)
}
override fun onDestroy() {
super.onDestroy()
EventBusUtil.unregister(this)
}
fun setUI() {
goodsDetailsReturRl = findViewById(R.id.goodsDetailsReturWebViewRl)
merchandiseCustomerRl = findViewById(R.id.merchandiseCustomerRl)
commonbase_num_bg = findViewById(R.id.commonbase_num_bg)
commonbase_num = findViewById(R.id.commonbase_num)
merchandiseCustomerRl?.setOnClickListener {
if (LocalAppSettings.localProviderSettingsData.value!!.cart_need_login == "0") {
DeepPathLinkUtil.deepPathHome(
this,
DeepPath.cart,
"cart",
"",
null,
""
)
} else {
GlobalFunc.isLoginAndGo(mContext) {
if (it) {
DeepPathLinkUtil.deepPathHome(
this,
DeepPath.cart,
"cart",
"",
null,
""
)
}
}
}
}
goodsDetailsReturRl?.setOnClickListener {
scrollToTop(true)
}
//判断sku有没有更新 以及存储sku信息
val cartNum = UserSPUtils.getInstance().getString(GlobalVariable.CARTNUM)
cartNum.logW("cartNum")
if (!TextUtils.isEmpty(cartNum) && "0" != cartNum) {
commonbase_num_bg?.visibility = View.VISIBLE
commonbase_num?.text = Tools.change99(cartNum)
} else {
commonbase_num_bg?.visibility = View.INVISIBLE
}
}
fun setWebViewClient() {
val webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
super.onProgressChanged(view, newProgress)
}
override fun onReceivedTitle(view: WebView, title: String) {
super.onReceivedTitle(view, title)
//这里面可以赋值给到title
title.logW("qqqqqqqq")
setWebViewTitle(title,view)
}
override fun onJsAlert(
view: WebView?,
url: String?,
message: String?,
result: JsResult?
): Boolean {
ToastUtils.showShort("123")
return super.onJsAlert(view, url, message, result)
}
override fun onJsPrompt(
view: WebView?,
url: String?,
message: String?,
defaultValue: String?,
result: JsPromptResult?
): Boolean {
ToastUtils.showShort("1234")
return super.onJsPrompt(view, url, message, defaultValue, result)
}
}
val webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
}
override fun onPageFinished(view: WebView?, url: String?) {
val cookieManager = CookieManager.getInstance()
cookieManager.getCookie(url).logW("currency_code3")
super.onPageFinished(view, url)
}
override fun onReceivedSslError(
view: WebView?,
handler: SslErrorHandler?,
error: SslError?
) {
super.onReceivedSslError(view, handler, error)
handler?.proceed()
}
}
activityWebView?.webChromeClient = webChromeClient
activityWebView?.webViewClient = webViewClient
}
@JavascriptInterface
fun setMessage(msg: String) {
/*
*add_cart_function_native > GlobalVariable.SpecialPath.addCart.value 快速加购
*user_token_function_native 获取登录态
* webView.loadUrl("observeToken('')"); */
LogUtils.e("qqqqqqqq", msg)
val specialModel = JsonUtils.StringToObject(msg, SpecialModelDTO::class.java)
specialModel.toString().logW()
if (!specialModel.path.isNullOrEmpty() && specialModel.path == GlobalVariable.SpecialPath.addCart.value) {//加入购物车
specialModel.params.let {
it.handle.let { it1 ->
goodsListDetails(it1, it.selectSku)
}
}
} else if (!specialModel.path.isNullOrEmpty() && specialModel.path == GlobalVariable.SpecialPath.token.value) {//获取token
val tokenStr = if (GlobalFunc.hasLogin()) GlobalFunc.getAccountToken() else "123"
var tokenMap: Map? = null
tokenStr?.let { tokenMap = mapOf("access_token" to it) }
var json = JSONObject()
json.put("code", 200)
json.put("message", "成功")
val param = tokenMap?.let {
json.put("params", tokenMap)
// mapOf("code" to 200, "message" to "成功", "params" to it.toString())
}
// activityWebView?.loadUrl("javascript:observeToken('${param.toString()}')");
var result = "服务器返回的数据"
//调用js方法必须在主线程
callBackFunction(specialModel.params.callback, json.toString())
} else if (!specialModel.path.isNullOrEmpty() && specialModel.path == GlobalVariable.SpecialPath.cartGoodsNum.value) {//购物车数量
val cartNum = UserSPUtils.getInstance().getString(GlobalVariable.CARTNUM)
var tokenMap: Map? = null
var json = JSONObject()
json.put("code", 200)
json.put("message", "成功")
json.put("params", mapOf("carGoodsNum" to cartNum.toInt()).toString())
callBackFunction(specialModel.params.callback, json.toString())
} else if (!specialModel.path.isNullOrEmpty() && specialModel.path == GlobalVariable.SpecialPath.traceLog.value) {//埋点
var tranceLogParams: TranceLogParams? = specialModel?.params?.tranceLogParams
} else if (!specialModel.path.isNullOrEmpty() && specialModel.path == GlobalVariable.SpecialPath.openView.value) {//打开新界面
specialModel.params.deepLink?.apply {
var retMap = UriParams.getUriParams(this)
DeepPathLinkUtil.deepPathHome(mContext, this, null, null, retMap, null)
}
}
else if (!specialModel.path.isNullOrEmpty() && specialModel.path == GlobalVariable.SpecialPath.floatCart.value) {//展示购物车浮窗/置顶按钮
isShowTopBtn =
if (specialModel.params.alertType == 2 && specialModel.params.isShow == 1) 1 else 0
isShowCartBtn =
if (specialModel.params.alertType == 1 && specialModel.params.isShow == 1) 1 else 0
merchandiseCustomerRl?.visibility = if (isShowCartBtn == 1) View.VISIBLE else View.INVISIBLE
goodsDetailsReturRl?.visibility = if (isShowTopBtn == 1) View.VISIBLE else View.GONE
commonbase_num_bg?.visibility = if (isShowCartBtn == 1) View.VISIBLE else View.INVISIBLE
}else if (!specialModel.path.isNullOrEmpty() && specialModel.path == GlobalVariable.SpecialPath.jsFunction.value) {//强制跑脚本(转ar模式)
MyCoroutineScope().runWithMain {
activityWebView.loadUrl("javascript:$('html').addClass('rtl-wrapper')")
}
callBackFunction(specialModel.params.jsString, "")
}
}
private fun callBackFunction(methodName: String, message: String?) {
MyCoroutineScope().runWithMain {
var method = methodName.replace("params", "'$message'")
activityWebView.loadUrl("javascript:$method")
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onCartNumEvent(event: CartNumEvent?) {
if (event == null) return
commonbase_num_bg?.visibility = if (event.cartNum == 0) View.INVISIBLE else View.VISIBLE
commonbase_num?.text = Tools.change99(event.cartNum)// event.cartNum.toString() + ""
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && activityWebView.canGoBack()) {
activityWebView.goBack()// 返回前一个页面
return true
}
return super.onKeyDown(keyCode, event)
}
}