首页 > 解决方案 > 如何将变量从工作线程传递给 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();
}

标签: androidmultithreadinghttp

解决方案


您必须在 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);

推荐阅读