(Android/안드로이드) WebView method must be called on the same thread

✨ 개요

WebView는 생성된 스레드(대부분 main/UI thread)에서만 접근해야 하는데, 다른 스레드에서 WebView 메서드를 호출했기 때문에 발생합니다.


1. 요약


2. 에러 메시지의 의미

WebView method must be called on the same thread는 다음을 의미합니다.


3. 해결 방법

3-1 post 사용

webView.post {
    webView.loadUrl("https://example.com")
}

3.2 Handler(Looper.getMainLooper()).post { }

val mainHandler = Handler(Looper.getMainLooper())
mainHandler.post {
    webView.evaluateJavascript("alert('hi')", null)
}

3.3 Coroutine에서 Main으로 전환

// 백그라운드 scope 라면
lifecycleScope.launch(Dispatchers.IO) {
    val data = repo.load()
    withContext(Dispatchers.Main) {
        webView.loadUrl("javascript:render(${data})")
    }
}

// main으로 실행
lifecycleScope.launch(Dispatchers.Main) {
    webView.reload()
}


Related Posts