Android multithreading --View.post () source code analysis

 

Lift View.post () or View.postDelay (), I believe a lot of shoes that is not strange, it has two functions most used

1) update the UI in the sub-thread;

2) Higher Wide View of the acquired attribute.

 

First, update the UI in the sub-thread

   Generally, we update the UI exemplary child thread achieved by using View.post () is as follows:

 1 private Button mStartBtn;
 2 @Override
 3 protected void onCreate(Bundle savedInstanceState) {
 4     super.onCreate(savedInstanceState);
 5     setContentView(R.layout.activity_intent_service);
 6     mStartBtn = findViewById(R.id.start);
 7     new Thread(new Runnable() {
 8         @Override
 9         public void run() {
10             mStartBtn.post(new Runnable() {
11                 @Override
12                 public void RUN () {
 13 is                      // address some consuming operations 
14                      mStartBtn.setText ( "End" );
 15                  }
 16              });
 . 17          }
 18 is      .}) Start ();
 . 19 }

Line 7 is turned on a thread, line 10 by calling the post method, so that line 14 modifies itself implements the interface UI is displayed. Well, this is how to achieve it? We take a look at the source code into the post.

 

//============================View.java=============================
1
/** 2 * <p>Causes the Runnable to be added to the message queue. 3 * The runnable will be run on the user interface thread.</p> 4 * ...... 5 */ 6 public boolean post(Runnable action) { 7 final AttachInfo attachInfo = mAttachInfo; 8 if (attachInfo != null) { 9 return attachInfo.mHandler.post(action); //① 10 } 11 // Postpone the runnable until we know on which thread it needs to run. 12 // Assume that the runnable will be successfully placed after attach. 13 getRunQueue().post(action); //② 14 return true; 15 }

Notes 1 to 5, said line, the method Runnable added to the message queue, the UI thread will run in the Runnable. This is the role of this method, add successful returns true.

The implementation of the above-mentioned source logic, the key point in mAttachInfo whether null, which would lead to two logic:

1) mAttachInfo not null, the code ① go logic.

2) mAttachInfo is null, take the logic of the code ②.

       Yet to attach to the current View Window, View the whole system has not finished loading, mAttachInfo will be null, the performance of an Activity is onResume () method has not run to completion. On the contrary, mAttachInfo will not be null. This section will explain in detail later, here to know the conclusion.

 

Guess you like

Origin www.cnblogs.com/andy-songwei/p/11990430.html