handler.post(r);是把r加到消息隊列,但並未開辟新線程。等到消息被取出時才執行。
package com.lei.handlethread; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.view.Menu; import android.widget.Button; public class MainActivity extends Activity { private Button btn = null; private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler.post(r); setContentView(R.layout.activity_main); btn = (Button)findViewById(R.id.hello);// 用來驗證setContentView()先執行的。
String s=(String) btn.getText();//
System.out.println(s); System.out.println("activity--->"+Thread.currentThread().getId()); System.out.println("Activityname--->"+Thread.currentThread().getName()); } Runnable r = new Runnable() { public void run() { System.out.println("handler--->"+Thread.currentThread().getId()); System.out.println("handlername--->"+Thread.currentThread().getName()); try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
運行結果:logCat先打印如下信息。程序運行界面過10s顯示TextView文字。
解釋:
main線程從消息泵中取出一個消息,處理(執行相關函數),然后再取一個,處理。所以onCreate是某一消息處理中的執行,其中post一個消息,只是把消息加入隊列了,還沒執行新消息,什么時候執行?要等前一個消息處理完,再次從消息泵中取消息處理時,它才被執行。
所以先是main的system.out,再是post的system.out
相比之下,sendMessage是同步執行,用handler.sendMessage,那順序就變了。
至於setContentView(R.layout.activity_main);肯定是最先執行,程序界面最先打開了,但是界面空間要等到Activity的Resume(即交互階段)階段才會顯示。通過獲取界面空間ID,在Log中打印空間內容就可驗證。