Home > front end >  Webview.loadurl inside @JavascriptInterface will crashes the app
Webview.loadurl inside @JavascriptInterface will crashes the app

Time:01-19

I have a webview, which is running on main thread and i am calling webview.loadurl("https://www.google.com")

its loading fine.

webview has following setting, so javascript function call some of native function.

webView.addJavascriptInterface(this, name)

and this class has one method with @JavascriptInterface annotation

@JavascriptInterface
fun getTestData(){
**webview.loadURL("https://www.facebook.com")**
}

the bold one webview.loadURL("https://www.facebook.com") is getting crashed with following error: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 2) {95d9516} called on Looper (JavaBridge, tid 1144) {e018910}, FYI main Looper is Looper (main, tid 2) {95d9516})

I have checked for threads and webview is running on main thread, and while the control comes under the method getTestData(), the thread is javabridge.

Any help would be appreciated

CodePudding user response:

run your code in UI thread, JS interfaces are called in some other (looks like)

@JavascriptInterface
fun getTestData(){
    Handler(Looper.getMainLooper()).post {
        webview.loadURL("https://www.facebook.com")
    }
}

from stacktrace:

All WebView methods must be called on the same thread

and you are creating WebView instance always in UI thread (as this is View, should be drawn...)

also if you are in Activity then you can use runOnUiThread{}

CodePudding user response:

You need to call Android Web view related things on UI thread.

webView.post {
    webView.loadUrl("https://www.facebook.com")
}
  • Related