直接在UI线程中开启子线程来更新TextView显示的内容,运行程序咱们会发现,以下错 误:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.翻译过来就是:只有建立这个控件的线程才能去更新该控件的内容。java
全部的UI线程要去负责View的建立而且维护它,例如更新冒个TextView的显示,都必须在主线程中去作,咱们不能直接在UI线程中去建立子线程,要利用消息机制:handler,以下就是handler的简单工做原理图:android
public class HandlerTestActivity extends Activity { private TextView tv; private static final int UPDATE = 0; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO 接收消息而且去更新UI线程上的控件内容 if (msg.what == UPDATE) { // Bundle b = msg.getData(); // tv.setText(b.getString("num")); tv.setText(String.valueOf(msg.obj)); } super.handleMessage(msg); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.tv); new Thread() { @Override public void run() { // TODO 子线程中经过handler发送消息给handler接收,由handler去更新TextView的值 try { for (int i = 0; i < 100; i++) { Thread.sleep(500); Message msg = new Message(); msg.what = UPDATE; // Bundle b = new Bundle(); // b.putString("num", "更新后的值:" + i); // msg.setData(b); msg.obj = "更新后的值:" + i; handler.sendMessage(msg); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } }
为何要使用Handlers?ide
由于,咱们当咱们的主线程队列,若是处理一个消息超过5秒,android 就会抛出一个 ANP(无响应)的消息,因此,咱们须要把一些要处理比较长的消息,放在一个单独线程里面处理,把处理之后的结果,返回给主线程运行,就须要用的Handler来进行线程建的通讯,spa
public int what 线程
public int arg1 翻译
public int arg2 code
public Object obj队列