当我们需要在子线程处理耗时的操作(例如访问网络,数据库的操作),而当耗时的操作完成后,需要更新UI,这就需要使用Handler来处理,因为子线程不能做更新UI的操作。Handler能帮我们很容易的把任务(在子线程处理)切换回它所在的线程。简单理解,Handler就是解决线程和线程之间的通信的。
package com.example.xxh.myhandle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView txt_view; private Button btn; MyHandle myHandle; private void log(String msg) { Log.i("MYHANDLE", msg); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); log("主线程 启动"); txt_view = (TextView)findViewById(R.id.txt_view); btn = (Button)findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myHandle = new MyHandle(); MyThread myThread = new MyThread(); new Thread(myThread).start(); txt_view.append("完成\n"); } }); log("主线程 完成 taskid:" + getTaskId()); } private class MyHandle extends Handler { private MyHandle() { } public MyHandle(Looper L) { super(L); } @Override public void handleMessage(Message msg) { log("handleMessage 收到消息 taskid: " + getTaskId()); super.handleMessage(msg); Bundle bundle = msg.getData(); String color = bundle.getString("color"); MainActivity.this.txt_view.append(color); } } class MyThread implements Runnable { @Override public void run() { log("新子线程启动"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } log("new thread; taskid:" + getTaskId()); Message message = new Message(); Bundle bundle = new Bundle(); bundle.putString("color", "我是新的消息"); message.setData(bundle); log("子线程发送消息"); MainActivity.this.myHandle.sendMessage(message); log("子线程消息发送完成"); } } }