Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #1

Merged
merged 3 commits into from
Aug 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 81 additions & 18 deletions app/src/main/java/com/ding1ding/jsbridge/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package com.ding1ding.jsbridge.app
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import com.ding1ding.jsbridge.Callback
import com.ding1ding.jsbridge.ConsolePipe
Expand All @@ -17,8 +19,10 @@ class MainActivity :
AppCompatActivity(),
View.OnClickListener {

private var webView: WebView? = null
private var bridge: WebViewJavascriptBridge? = null
private lateinit var webView: WebView
private lateinit var bridge: WebViewJavascriptBridge

private val webViewContainer: LinearLayout by lazy { findViewById(R.id.linearLayout) }

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -28,29 +32,74 @@ class MainActivity :
setupClickListeners()
}

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && event?.repeatCount == 0) {
when {
webView.canGoBack() -> webView.goBack()
else -> supportFinishAfterTransition()
}
return true
}
return super.onKeyDown(keyCode, event)
}

override fun onResume() {
super.onResume()
webView.onResume()
webView.resumeTimers()
}

override fun onPause() {
webView.onPause()
webView.pauseTimers()
super.onPause()
}

override fun onDestroy() {
// 01
bridge.release()
// 02
releaseWebView()
Log.d(TAG, "onDestroy")
super.onDestroy()
}

@SuppressLint("SetJavaScriptEnabled")
private fun setupWebView() {
webView = findViewById<WebView>(R.id.webView).apply {
// WebView.setWebContentsDebuggingEnabled(true)
settings.javaScriptEnabled = true
settings.allowUniversalAccessFromFileURLs = true
webView = WebView(this).apply {
removeJavascriptInterface("searchBoxJavaBridge_")
removeJavascriptInterface("accessibility")
removeJavascriptInterface("accessibilityTraversal")

WebView.setWebContentsDebuggingEnabled(true)

layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
0,
1f,
)

settings.apply {
javaScriptEnabled = true
allowUniversalAccessFromFileURLs = true
}
webViewClient = createWebViewClient()
loadUrl("file:///android_asset/index.html")
}

webViewContainer.addView(webView)
}

private fun setupBridge() {
bridge = webView?.let {
WebViewJavascriptBridge(this, it).apply {
consolePipe = object : ConsolePipe {
override fun post(message: String) {
Log.d("[console.log]", message)
}
bridge = WebViewJavascriptBridge(this, webView).apply {
consolePipe = object : ConsolePipe {
override fun post(message: String) {
Log.d("[console.log]", message)
}

registerHandler("DeviceLoadJavascriptSuccess", createDeviceLoadHandler())
registerHandler("ObjTest", createObjTestHandler())
}

registerHandler("DeviceLoadJavascriptSuccess", createDeviceLoadHandler())
registerHandler("ObjTest", createObjTestHandler())
}
}

Expand All @@ -63,7 +112,7 @@ class MainActivity :
private fun createWebViewClient() = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
Log.d(TAG, "onPageStarted")
bridge?.injectJavascript()
bridge.injectJavascript()
}

override fun onPageFinished(view: WebView?, url: String?) {
Expand All @@ -90,7 +139,7 @@ class MainActivity :
when (v?.id) {
R.id.buttonSync -> callJsHandler("GetToken")
R.id.buttonAsync -> callJsHandler("AsyncCall")
R.id.objTest -> bridge?.callHandler(
R.id.objTest -> bridge.callHandler(
"TestJavascriptCallNative",
mapOf("message" to "Hello from Android"),
null,
Expand All @@ -99,7 +148,7 @@ class MainActivity :
}

private fun callJsHandler(handlerName: String) {
bridge?.callHandler(
bridge.callHandler(
handlerName,
Person("Wukong", 23),
object : Callback<Any> {
Expand All @@ -110,6 +159,20 @@ class MainActivity :
)
}

private fun releaseWebView() {
webViewContainer.removeView(webView)
webView.apply {
stopLoading()
loadUrl("about:blank")
clearHistory()
removeAllViews()
webChromeClient = null
// webViewClient = null
settings.javaScriptEnabled = false
destroy()
}
}

companion object {
private const val TAG = "MainActivity"
}
Expand Down
6 changes: 4 additions & 2 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<WebView
<!--<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
android:layout_weight="1" />-->

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="horizontal"
android:padding="16dp">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,16 @@ object MessageSerializer {
return json.toString().escapeJavascript()
}

@JvmStatic
fun deserializeResponseMessage(
jsonString: String,
responseCallbacks: Map<String, Callback<*>>,
messageHandlers: Map<String, MessageHandler<*, *>>,
): ResponseMessage {
): ResponseMessage = try {
val json = JSONObject(jsonString)
val responseId = json.optString(RESPONSE_ID)

return if (responseId.isNotEmpty()) {
if (responseId.isNotEmpty()) {
val callback = responseCallbacks[responseId]
val targetType = callback?.javaClass?.genericInterfaces?.firstOrNull()?.let {
(it as? ParameterizedType)?.actualTypeArguments?.firstOrNull()
Expand All @@ -93,6 +94,9 @@ object MessageSerializer {
data = parseData(json.optString(DATA), targetType),
)
}
} catch (e: Exception) {
Log.e("[JsBridge]", "Error deserializing message: ${e.message}")
ResponseMessage(null, null, null, null, null)
}

private fun parseData(jsonString: String, targetType: Type?): Any? {
Expand Down
Loading
Loading