Android的返回方法必须在同一个线程错误被称为 [英] Android returns methods must be called on same thread error

查看:186
本文介绍了Android的返回方法必须在同一个线程错误被称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用从它是由web视图的javascript调用的方法一的WebView方法。随后的WebView应返回在方法中使用的值。

I am trying to call a WebView method from a method which is called by javascript in the webview. Webview then should return value that is used within the method.

HTML事件 - > JavaScript的 - > jSinterface - > Android的方法< - >网页视图

html event -> javascript -> jSinterface -> android method <-> webview

显然,网页视图运行在UI线程,而JS不和的WebView方法必须由同一个线程调用。此方法可以用来调用从非UI线程的方法:

Apparently Webview runs in ui thread while js doesn't and webview's methods must be called from same thread. This method can be used to call methods from non-ui thread:

webView.post(new Runnable() {
         public void run() {
            webView.loadUrl("javascript:" + s + ";");
        }
    });

但我想返回结果为好。 返回webView.getUrl()为例。我该怎么做?

推荐答案

正如你所说,当你从一个非UI线程中调用JS到JavaBridge的方法,然后到你的类,你必须使用监听器/回调。当你做你的使用loadURL ,叫你听者传递所需的字符串URL。

As you said, when you call methods from JS to the JavaBridge and then to your class from a non-ui Thread, you have to use listeners/callbacks. When you have done your loadUrl, call you listener to pass the desired String url.

在这个例子中,我定义了一个与 onGetWebViewUrl 监听内部接口。我已经通过实现在同一类的接口注册了侦听器,这样我就可以轻松地调用它。

In this Example, I've defined an an inner interface with the onGetWebViewUrl listener. I've registered the listener by implementing the interface in the same class, so I can call it easily.

例如:

public class WebViewProxy implement WebViewListener {

    private WebView mWebView;

    ...

    @JavascriptInterface
    public void onJsStuff(){
        webView.post(new Runnable() {
             public void run() {
                mWebView.loadUrl("javascript:" + s + ";");
                WebViewProxy.this.onGetWebViewUrl(mWebView.getUrl());
            }
        });
    }

    @Override
    public void onGetWebViewUrl(String url){
        // call method 2 with this url
    }

    public interface WebViewListener {

        void onGetWebViewUrl(String url);
    }
}

这篇关于Android的返回方法必须在同一个线程错误被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆