|
@@ -6,11 +6,17 @@ import android.webkit.JavascriptInterface
|
|
|
import android.webkit.WebView
|
|
|
import com.google.gson.Gson
|
|
|
import com.google.gson.JsonElement
|
|
|
-import com.hzliuzhi.applet.core.SharedFlowHub
|
|
|
+import com.hzliuzhi.applet.core.shared.Event
|
|
|
+import com.hzliuzhi.applet.core.shared.SharedFlowHub
|
|
|
+import com.hzliuzhi.applet.core.shared.SharedFlowHub.cast
|
|
|
import kotlinx.coroutines.CoroutineScope
|
|
|
import kotlinx.coroutines.Dispatchers
|
|
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
|
|
+import kotlinx.coroutines.flow.filter
|
|
|
+import kotlinx.coroutines.flow.launchIn
|
|
|
+import kotlinx.coroutines.flow.onEach
|
|
|
import kotlinx.coroutines.withContext
|
|
|
+import org.json.JSONObject
|
|
|
import java.io.InputStreamReader
|
|
|
|
|
|
class WebViewBridge(private val coroutineScope: CoroutineScope) {
|
|
@@ -45,6 +51,14 @@ class WebViewBridge(private val coroutineScope: CoroutineScope) {
|
|
|
}.also { lastScriptText = it }
|
|
|
}.getOrNull()
|
|
|
script?.also { webview.evaluateJavascript(it, null) }
|
|
|
+
|
|
|
+ SharedFlowHub.events.filter { it.type == "${SharedFlowHub.WEBVIEW_BRIDGE_EVENT}:js" }.onEach { event ->
|
|
|
+ Log.d("log:bridge", "发送消息事件: $event")
|
|
|
+ event.cast<Message, String>()?.also {
|
|
|
+ val payload = Gson().toJson(it.payload)
|
|
|
+ webview.evaluateJavascript("Bridge.getInstance().dispatch(${JSONObject.quote(payload)})", it.callback)
|
|
|
+ }
|
|
|
+ }.launchIn(coroutineScope)
|
|
|
}
|
|
|
|
|
|
|
|
@@ -53,22 +67,29 @@ class WebViewBridge(private val coroutineScope: CoroutineScope) {
|
|
|
@SuppressLint("JavascriptInterface")
|
|
|
internal suspend fun WebView.handleBridge(): Nothing = withContext(Dispatchers.Main) {
|
|
|
addJavascriptInterface(this@WebViewBridge, "AndroidBridge")
|
|
|
- messages.collect {
|
|
|
- Log.d("log:bridge", "接收到的事件: ${it.type}")
|
|
|
- SharedFlowHub.emit(
|
|
|
- SharedFlowHub.Event(
|
|
|
- type = it.type,
|
|
|
- payload = it.payload,
|
|
|
- callback = {}
|
|
|
- ))
|
|
|
- }
|
|
|
+ messages.collect { SharedFlowHub.webViewEmit(it) }
|
|
|
}
|
|
|
|
|
|
+ private fun SharedFlowHub.webViewEmit(message: Message) {
|
|
|
+ Log.d("log:bridge", "接收消息: $message")
|
|
|
+ Event<JsonElement, JsonElement>(
|
|
|
+ type = "$WEBVIEW_BRIDGE_EVENT:${message.type}",
|
|
|
+ payload = message.payload,
|
|
|
+ callback = { payload ->
|
|
|
+ Event<Message, String>(
|
|
|
+ type = "$WEBVIEW_BRIDGE_EVENT:js",
|
|
|
+ payload = message.copy(payload = payload)
|
|
|
+ ).also { emit(it) }
|
|
|
+ }
|
|
|
+ ).also { emit(it) }
|
|
|
+ }
|
|
|
|
|
|
+ /* 注入到 JavaScript 中的方法 */
|
|
|
@JavascriptInterface
|
|
|
fun postMessage(string: String) {
|
|
|
Message.fromJson(string)?.also {
|
|
|
messages.tryEmit(it)
|
|
|
}
|
|
|
}
|
|
|
-}
|
|
|
+}
|
|
|
+
|