본문 바로가기
android

android webview 통신 webBridge

by liz_devel 2023. 12. 26.

안드로이드와 웹뷰가 통신하기 위해서는 webBridge가 필요하다.

안드로이드와 웹뷰 간의 직접 호출이 불가하여 브릿지를 통해 통신한다.

브릿지는 자바스크립트용 인터페이스이다.

 

브릿지 예제

MainActivity.kt

class MainActivity : AppCompatActivity(), Bridge.BridgeListener {

    private val bridge = Bridge()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val webView = findViewById<WebView>(R.id.web_view)
        webView.settings.javaScriptEnabled = true
        webView.loadUrl("file:///android_asset/webviewtest.html")
        webView.addJavascriptInterface(bridge, "Bridge")
        bridge.setListener(this)
    }

    override fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

Bridge.kt

class Bridge {

    private var callback: BridgeListener? = null

    fun setListener(listener: BridgeListener) {
        callback = listener
    }

    @JavascriptInterface
    fun showMessage() {
        callback?.showToast("메이크 토스트")
    }

    interface BridgeListener {
        fun showToast(msg: String)
    }
}

 

webviewtest.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
</head>
<body style="background-color: white;">
<button type="button" onclick="clickButton()">클릭</button>
<script>
function clickButton() {
    Bridge.showMessage();
}

</script>
</body>
</html>

 

webviewtest.html은 assets 폴더를 생성해서 그 안에 파일을 생성해 주어야 한다.

 

*assets 폴더 만드는 법

 
반응형