Handler.post (R) adds r to the message queue, but does not open a new thread. It is not executed until the message is removed.
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 (); @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Handler.post (R); Setcontentview (R.layout.activity_main); BTN = (Button) Findviewbyid (R.id.hello);//used to verify that Setcontentview () is executed first. 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 (); }}}; @Overridepublic Boolean oncreateoptionsmenu (MENU menu) {getmenuinflater (). Inflate (R.menu.activity_main, menu); return true;}
}
Run Result: Logcat Print the following information first. Program Run Interface 10s display TextView text.
Explain:
The main thread extracts a message from the message pump, processes (executes the related function), and then takes one, processing. So OnCreate is the execution of a message processing, where post a message, just put the message into the queue, not yet execute new messages, when to execute? It will be executed when the message is processed again from the message pump after the previous message has been processed.
So first the system.out of main, then the System.out of the post.
By contrast, SendMessage is performed synchronously, with Handler.sendmessage, and that order is changed.
As for Setcontentview (R.layout.activity_main), it is definitely the first to execute, the program interface opens first, but the interface space is not displayed until the activity's resume (that is, the interaction phase) stage. By obtaining an interface space ID, you can verify that the space content is printed in log.
Handler.post (R) doubts about the same thread