android - 如何将变量从工作线程传递给 UI 线程?
问题描述
下面是简单获取请求的代码,并且res变量在 Ui 线程中不可用。这如何在android中实现?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable(){
@Override
public void run(){
try {
String res = Utils.GetRequest("http://www.google.com");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, res, Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
解决方案
您必须在 OnCreate() 的主线程上创建一个处理程序
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message inputMessage) {
// handle the passed value here
// for ex. update the UI by getting the data from the inputMessage
}
}
在你的线程内..调用
Message myMessage = mHandler.obtainMessage();
myMessage.obj = "the value to update the ui";
mHandler.sendMessage(myMessage);
推荐阅读
- javascript - 我们如何在 FullCalendar 5.3.2 中更改现有事件的 ID
- python - scikit-learn机器学习中进行回归时切换损失函数的方法
- typescript - 在 Typescript 中验证正则表达式匹配的字符串类型的类型?
- python - Windows exe 上的 Setuptools 脚本丢失
- ios - ios - 使用新版本更新时,AppStore 中的 App url 链接是否可能更改?请标记任何描述此内容的文章或文档
- powerbi - Power Bi Soap 请求
- javascript - 使用 jsPDF 和 html2canvas 创建 PDF 的问题
- c# - 从 RTF 字节数组中获取超链接
- zephir - Zephir 函数返回的值只能赋值给变体变量
- spring-session - Spring Session 重写 cookie 值并在成功的 HTTP 请求上失败