如何将变量从工作线程传递到UI线程?

时间:2018-09-22 17:07:57

标签: android multithreading http

下面是简单的get请求的代码, 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();
}

2 个答案:

答案 0 :(得分:0)

好的,我发现我没有将res变量声明为final。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Thread thread = new Thread(new Runnable(){
    @Override
    public void run(){
        try {
            final 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();

}

答案 1 :(得分:0)

您必须在OnCreate()的Main线程上创建一个处理程序。 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);