Browse Source

1.添加第三方jsbridge webview依赖加载webview画面

王鹏鹏 2 years ago
parent
commit
785a60b1ee

+ 1 - 0
.idea/misc.xml

@@ -3,6 +3,7 @@
   <component name="DesignSurface">
     <option name="filePathToZoomLevelMap">
       <map>
+        <entry key="..\:/workspace/hcp-pad/webview/src/main/res/layout/activity_bridge_web.xml" value="0.22826086956521738" />
         <entry key="..\:/workspace/yingyangfly/app/src/main/res/layout/activity_main.xml" value="0.22826086956521738" />
         <entry key="..\:/workspace/yingyangfly/app/src/main/res/layout/activity_push.xml" value="0.22239583333333332" />
         <entry key="..\:/workspace/yingyangfly/baselib/src/main/res/drawable/bg_center_toast.xml" value="0.2265" />

+ 5 - 0
baselib/src/main/java/com/yingyangfly/baselib/router/RouterUrlCommon.kt

@@ -20,6 +20,11 @@ object RouterUrlCommon {
      */
     const val load_web_view = "/net_view/webViewInteractionJs"
 
+    /**
+     * Home组件WebView路径, 该WebView适合JS交互的H5页面,
+     */
+    const val WEB_VIEW_INTERACTION_JS = "/web/webViewInteractionJs"
+
     /**
      * 工作台
      */

+ 1 - 0
webview/build.gradle

@@ -20,4 +20,5 @@ dependencies {
     implementation( rootProject.ext.androidx.appcompat )
     implementation( rootProject.ext.androidx.material )
     implementation( rootProject.ext.androidx.constraintlayout)
+    implementation 'com.github.lzyzsd:jsbridge:1.0.4'
 }

+ 6 - 0
webview/src/main/AndroidManifest.xml

@@ -11,6 +11,12 @@
         android:supportsRtl="true"
         android:usesCleartextTraffic="true"
         tools:targetApi="n">
+        <activity
+            android:name=".BridgeWebActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:screenOrientation="landscape"
+            android:windowSoftInputMode="adjustResize|adjustPan" />
+
         <activity
             android:name=".WebviewActivity"
             android:configChanges="keyboardHidden|orientation|screenSize"

+ 9 - 9
webview/src/main/java/com/yingyangfly/webview/AndroidToJs.kt

@@ -16,15 +16,15 @@ class AndroidToJs(val context: Activity) : Any() {
     @JavascriptInterface
     fun postMessage(msg: String?) {
         "js回调给原生的参数:$msg".logi()
-        if (msg?.contains("403") == true) {
-
-        }
-        if (msg?.contains("back") == true) {
-           context.finish()
-        }
-        if (msg?.contains("list") == true) {
-
-        }
+//        if (msg?.contains("403") == true) {
+//
+//        }
+//        if (msg?.contains("back") == true) {
+//           context.finish()
+//        }
+//        if (msg?.contains("list") == true) {
+//
+//        }
 
     }
 }

+ 116 - 0
webview/src/main/java/com/yingyangfly/webview/BridgeWebActivity.kt

@@ -0,0 +1,116 @@
+package com.yingyangfly.webview
+
+import android.annotation.SuppressLint
+import android.content.pm.ActivityInfo
+import android.graphics.Bitmap
+import android.os.Build
+import android.webkit.WebResourceRequest
+import android.webkit.WebSettings
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import com.alibaba.android.arouter.facade.annotation.Route
+import com.yingyangfly.baselib.base.BaseActivity
+import com.yingyangfly.baselib.ext.toast
+import com.yingyangfly.baselib.router.RouterUrlCommon
+import com.yingyangfly.webview.databinding.ActivityBridgeWebBinding
+
+/**
+ * BridgeWebview
+ */
+@Route(path = RouterUrlCommon.WEB_VIEW_INTERACTION_JS)
+class BridgeWebActivity : BaseActivity<ActivityBridgeWebBinding>() {
+
+    private lateinit var webSettings: WebSettings
+    var url: String = ""
+
+    override fun initViews() {
+        url = "http://60.205.201.7/cocos/mobile/whacaMole/"
+        initWebView()
+    }
+
+    override fun initListener() {
+
+    }
+
+    override fun initData() {
+
+    }
+
+    @SuppressLint("JavascriptInterface")
+    private fun initWebView() {
+        webSettings = binding.webView.settings
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
+        }
+        val ua = webSettings.userAgentString
+        //必须设置
+        webSettings.userAgentString = "$ua; app/lottchina  Android"
+        webSettings.javaScriptCanOpenWindowsAutomatically = true
+        webSettings.javaScriptEnabled = true
+        webSettings.setAppCacheEnabled(true)
+        webSettings.cacheMode = WebSettings.LOAD_DEFAULT
+        /**必须的设置, 访问网页版的H5,一定要设置。该方法是设置支持DomStorage,
+         * DOM Storage 分为 sessionStorage 和 localStorage。
+         * localStorage 对象和 sessionStorage 对象使用方法基本相同,它们的区别在于作用的范围不同。
+         * sessionStorage 用来存储与页面相关的数据,它在页面关闭后无法使用。而 localStorage 则持久存在,在页面关闭后也可以使用。
+         */
+        webSettings.domStorageEnabled = true
+        // 通过addJavascriptInterface()将Java对象映射到JS对象 下面一行代码是 JS调用原生方法
+        binding.webView.addJavascriptInterface(AndroidToJs(this), "callbackHandle")
+        binding.webView.addJavascriptInterface(AndroidToJs(this), "callbackImgHandle")
+        binding.webView.addJavascriptInterface(AndroidToJs(this), "callbackBackHandle")
+
+        binding.webView.isDrawingCacheEnabled = true
+        binding.webView.buildDrawingCache()
+        binding.webView.buildLayer()
+
+        binding.webView.webViewClient = object : WebViewClient() {
+            override fun shouldOverrideUrlLoading(
+                view: WebView?,
+                request: WebResourceRequest?
+            ): Boolean {
+                url.let {
+                    view?.loadUrl(it)
+                }
+                return super.shouldOverrideUrlLoading(view, request)
+            }
+
+            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
+                super.onPageStarted(view, url, favicon)
+            }
+
+            override fun onPageFinished(view: WebView?, url: String?) {
+                super.onPageFinished(view, url)
+
+            }
+        }
+        if (url.isNullOrEmpty().not()) {
+            binding.webView.loadUrl(url)
+        } else {
+            "视频链接不能为空".toast()
+        }
+    }
+
+    override fun onDestroy() {
+        destoryWebView()
+        super.onDestroy()
+    }
+
+    fun destoryWebView() {
+        binding.webView.stopLoading() // 停止加载
+        binding.webView.removeAllViews() // 移除webview上子view
+        binding.webView.clearCache(true) // 清除缓存
+        binding.webView.clearHistory() // 清楚历史
+        binding.webView.destroy() // 销毁WebView自身。
+    }
+
+    override fun onResume() {
+        /**
+         * 设置为横屏
+         */
+        if (requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
+            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
+        }
+        super.onResume()
+    }
+}

+ 15 - 2
webview/src/main/java/com/yingyangfly/webview/WebviewActivity.kt

@@ -44,8 +44,8 @@ class WebviewActivity : BaseActivity<ActivityWebviewBinding>() {
 
         // 通过addJavascriptInterface()将Java对象映射到JS对象 下面一行代码是 JS调用原生方法
         binding.web.addJavascriptInterface(AndroidToJs(this), "callbackHandle")
-        binding.web.addJavascriptInterface(AndroidToJs(this), "callbackImgHandle")
-        binding.web.addJavascriptInterface(AndroidToJs(this), "callbackBackHandle")
+//        binding.web.addJavascriptInterface(AndroidToJs(this), "callbackImgHandle")
+//        binding.web.addJavascriptInterface(AndroidToJs(this), "callbackBackHandle")
 
         binding.web.isDrawingCacheEnabled = true
         binding.web.buildDrawingCache()
@@ -105,4 +105,17 @@ class WebviewActivity : BaseActivity<ActivityWebviewBinding>() {
         }
         super.onResume()
     }
+
+    override fun onDestroy() {
+        destoryWebView()
+        super.onDestroy()
+    }
+
+    fun destoryWebView() {
+        binding.web.stopLoading() // 停止加载
+        binding.web.removeAllViews() // 移除webview上子view
+        binding.web.clearCache(true) // 清除缓存
+        binding.web.clearHistory() // 清楚历史
+        binding.web.destroy() // 销毁WebView自身。
+    }
 }

+ 6 - 1
webview/src/main/manifest/AndroidManifest.xml

@@ -6,11 +6,16 @@
         android:requestLegacyExternalStorage="true"
         android:usesCleartextTraffic="true">
         <activity
-            android:name=".WebviewActivity"
+            android:name=".BridgeWebActivity"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:screenOrientation="landscape"
             android:windowSoftInputMode="adjustResize|adjustPan" />
 
+        <activity
+            android:name=".WebviewActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:screenOrientation="landscape"
+            android:windowSoftInputMode="adjustResize|adjustPan" />
     </application>
 
 </manifest>

+ 23 - 0
webview/src/main/res/layout/activity_bridge_web.xml

@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<layout 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"
+    tools:ignore="ResourceName">
+
+    <androidx.constraintlayout.widget.ConstraintLayout
+        android:layout_width="match_parent"
+        android:layout_height="match_parent">
+
+        <!-- webview 演示web调用Java -->
+        <com.github.lzyzsd.jsbridge.BridgeWebView
+            android:id="@+id/webView"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent"
+            app:layout_constraintBottom_toBottomOf="parent"
+            app:layout_constraintLeft_toLeftOf="parent"
+            app:layout_constraintRight_toRightOf="parent"
+            app:layout_constraintTop_toTopOf="parent" />
+
+    </androidx.constraintlayout.widget.ConstraintLayout>
+
+</layout>

+ 1 - 1
workbenches/src/main/java/com/yingyang/workbenches/WorkbenchesActivity.kt

@@ -37,7 +37,7 @@ class WorkbenchesActivity : BaseMVVMActivity<ActivityWorkbenchesBinding, Workben
             rvGame.adapter = gameAdapter
             gameAdapter.setData(gameList)
             gameAdapter.onGameImageClickListener = { bean, position ->
-                JumpUtil.jumpActivity(RouterUrlCommon.load_web_view)
+                JumpUtil.jumpActivity(RouterUrlCommon.WEB_VIEW_INTERACTION_JS)
             }
         }
     }