gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:19:27 25 4
gpt4 key购买 nike

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

如何在线程范围之外传递这个字符串变量值?将字符串变量设为 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");

}

最佳答案

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

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

关于java - 将值从辅助线程传递到主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26613177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com