将值从辅助线程传递到主线程

时间:2014-10-28 16:12:04

标签: java android multithreading

我有一个带有try-catch块的线程。在try块中,我将HTML存储在一个变量中,我想将其加载到webview中。现在Android / Java不允许在主线程之外的任何其他地方调用Webview。

如何在线程范围之外传递此String变量值?将字符串变量设为final并声明外部线程并没有帮助。

public class MyCustomView extends LinearLayout {
//UI elements
private WebView mWebView;
final Activity activity = (Activity) this.getContext();

new Thread(new Runnable() {

        @Override
        public void run() {
            try {

                //Using thread because accessing network
                URL obj = new URL(adrequesturl);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                con.setRequestMethod("GET");


                if (con.getResponseCode() == 200) {

                //*****Need this variable's value in the Main Thread
                String dataToLoad="some_custom_html";


              //mWebView is a webview that I have created and below can not get executed from inside helper thread                      
              //mWebView.loadData(dataToLoad, "text/html", "utf-8");-

                } else {
                    //Some code
                }

            } catch (Exception e) {
                    //Some code
            }
        }

    }).start();


//**solution which worked for me**  
activity.runOnUiThread(new Runnable() {
                    public void run() {
                        mWebView.loadData(dataToLoad, "text/html", "utf-8");
                    }
                });


  //Now we are back to main thread

  //********Main Problem**************
  //Below mWebView.loadData is allowed but I can not get dataToLoad value here
  //mWebView.loadData(dataToLoad, "text/html", "utf-8");

}

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式在UI线程中运行部分代码:

this.getContext().runOnUiThread(new Runnable() {
    public void run() {
        mWebView.loadData(dataToLoad, "text/html", "utf-8");
    }
});

答案 1 :(得分:0)

您应该了解如何使用以及使用它们时线程的作用。 致电

mythread.start() 

启动它并且它的代码是并行执行的。 所以你不能说是否

 String dataToLoad="some_custom_html" 

之前或之后执行
 mWebView.loadData(dataToLoad, "text/html", "utf-8");

就像mithrop已经说过的那样,把它放在dataToLoad之后的同一个线程中

 this.getContext().runOnUiThread(new Runnable() {
public void run() {
    mWebView.loadData(dataToLoad, "text/html", "utf-8");
}

});