直接在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隊列