안드로이드와 웹뷰가 통신하기 위해서는 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 폴더 만드는 법
반응형
'android' 카테고리의 다른 글
libs.versions.toml / Room 라이브러리 빌드하기 / ksp (0) | 2024.07.14 |
---|---|
[안드로이드 스튜디오] git 커밋할 때 다른 계정으로 올라간다면? 계정 변경 방법 (0) | 2024.07.13 |
Domain 계층이란? (0) | 2023.05.02 |
자바의 정석 | 객체지향 프로그래밍 1 (0) | 2023.01.01 |
[Kotlin] Geckoview tutorial (0) | 2022.12.19 |