0

我正在从 webview 调用 JavascriptInterface 方法来调用 javascript 方法。问题是方法在获取结果值之前返回值。那么如何让 return 语句等到从 ui 线程执行 javascript 方法。

Javascript接口

public class CordovaJSInterface {
        Context cxt;
        String returnValueFromJS="";

        CordovaJSInterface(Context cxt){
            this.cxt = cxt;
        }
        public void setReturnValueFromJS(String valueFromJS){
            this.returnValueFromJS = valueFromJS;
        }
        @JavascriptInterface
        public String performClick()
          {

            /*MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mainView.loadUrl("javascript:" + "getLocation()" + ";");
                }

            });*/
            mainView.post(new Runnable() {
                @Override
                public void run() {
                    mainView.loadUrl("javascript:" + "getLocation()" + ";");
                }
            });
            /**PROBLEM : Method returns variable returnValueFromJS 
             * before it is updated by  getLocation() javascript method..
             **/

            return returnValueFromJS;
    }

所以我想让 performClick() 让 ui 线程先完成然后返回值。

4

2 回答 2

0

您也许可以使用Thread.join方法来实现此目的,但是您必须依赖底层操作系统的调度方法,并期望它非常公平,大多数情况下都是如此。

但是,这似乎不是正确的方法(我的意思是等待 UI 线程)。UI 线程是贪婪的。我不知道您是否可以提高当前 js 线程的优先级,以便获得更多 CPU 片。

于 2016-11-07T18:45:20.210 回答
0

首先创建一个接口:

interface CallBack {
    void click(String returnValueFromJS);
}

假设这是活动,实现您在此处创建的接口:

public class FirstClass extends Activity implements CallBack {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView();
    //calling cordovainterface
    new CordovaJSInterface(this).performClick(); // now control goes to perform click of cordovaJSInterface
    //cut remaining code from here and paste it in click method
}

@Override
public void click(String returnValueFromJS) {
    //code after calling cordavajsinterface should be here
    }
}

这是 cordovaJSinterface :

public class CordovaJSInterface {
Context cxt;
String returnValueFromJS = "";

CordovaJSInterface(Context cxt) {
    this.cxt = cxt;
}

public void setReturnValueFromJS(String valueFromJS) {
    this.returnValueFromJS = valueFromJS;
}

@JavascriptInterface
public void performClick() {

        /*MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mainView.loadUrl("javascript:" + "getLocation()" + ";");
            }

        });*/
    mainView.post(new Runnable() {
        @Override
        public void run() {
            mainView.loadUrl("javascript:" + "getLocation()" + ";");
            ctx.click(returnValueFromJS);
        }
    });
    /**PROBLEM : Method returns variable returnValueFromJS
     * before it is updated by  getLocation() javascript method..
     **/

    }
}

因此,当您调用时ctx.click(returnValueFromJS);,控件将转到您活动的 click 方法。剩下的随你怎么做。

于 2015-11-25T09:00:28.770 回答