Android's messaging mechanism

Source: Internet
Author: User

First, Introduction

①, we cannot access the UI null control in a sub-thread, it is time to put the update UI operation into the main thread only by handler

②, Handler's composition: MessageQueue and Looper support

③, MessageQueue: function: Stores a set of messages that provide insertions and deletions in the form of queues. The fact is that a single-linked list of data structures is used to store message lists.

④, Looper role: Because Mesagequeue can not process the message, Looper fill this function, Looper will be an infinite loop to find out if there is a new message, if there is a message processing, no words have been waiting

⑤, Looper's special concept threadlocal: It's not a thread, but it can store data in threads.

Example: When handler is created, it uses the current thread's looper to construct its circulatory system by default. So how do you get the current thread's looper, or specify the thread's Looper?

This will use the threadlocal,threadlocal to store and extract data in different threads. So the looper of each thread can be easily obtained by threadlocal.

Note : The thread is not looper by default and requires handler to be created for the thread first handler

 class  looperthread extends   thread{ public   Handler Mhandler;  public  void   run () {looper.prepare ();                      Mhandler  = new   Handler () {  public  void   Handlemessage (Message msg) { // process incoming messages here  
create Looper in thread

Why is the main thread not needed?

Since the activitythread was created, it has been initialized Looper

Ii. Overview of the message mechanism

Android message mechanism: mainly refers to the operating mechanism of handler and handler with MessageQueue and Looper work process.

The main function of handler : To tell a task to switch to a specified thread to execute,

Q: Why does Android have this feature?

Android Specifies that the access UI can only be executed in the main thread:

UI validation was judged in Viewrootimpl (P373①).

If there is no handler, we do some data processing in the sub-thread, then we have to modify the UI based on the data, and if there is no handler we will not be able to switch the work of the access UI to the main thread.

Q: Why do I specify that the UI can only be executed in the main thread?

Because if multiple threads in a concurrent interview may cause the UI control to be in an unexpected state.

Operating mechanism of handler

1. When the handler is created, the Looper and MessageQueue within it can work together with handler.

2. Use the Handler.post () method to post a runnable to the looper inside the handler, or using the Send () method. Because the post () method is ultimately done by the Send method.

3.send () method workflow: When Handler's send () method is called, it calls MessageQueue's Enqueuemessage () method to put the message in the message queue. Looper then discovers that a new message will be processed when it arrives, and the runnable () or handler handler Handlemessage () method in the final message will be called.

Call Graph:

Third, the Android message mechanism analysis threadlocal working principle

Usage Scenario: When some data is scoped to a thread and different threads have different copies of the data.

Example:

Private Static FinalString TAG = "Mainactivity";PrivateThreadlocal<boolean> mbooleanthreadlocal =NewThreadlocal<boolean>();//put a true type of data in MainthreadMbooleanthreadlocal.set (true); LOG.D (TAG,"Mainactivity" +mbooleanthreadlocal.get ());NewThread ("Thread#1"){   Public voidrun () {Mbooleanthreadlocal.set (false); LOG.D (TAG,"Thread#1" +mbooleanthreadlocal (. get ()); }}NewThread ("Thread#2") {Publcivoidrun () {LOG.D (TAG,"Thread#1" +mbooleanthreadlocal (. get ()); }}
mainactivity

return Result:

Mainactivity:true Thread#1:false Thread#2:null

Description: Although different threads are accessing the same threadlocal but depending on the thread, the returned data is based on the data set in the corresponding thread. (as if there was a copy)

Working principle:

1. View Threadlocal's Set () method (P377①)

①, gets the current thread first

②, calls the value () method based on the current thread to return the value object of the current thread, which stores the data for that thread.

Value class: The thread internally stores threadlocal data (indicating that the threadlocal data is stored in the current thread, rather than storing the data in the threadlocal)

③, put the data into the value.table structure.

Table data structure: The value of the array private object[] table,threadlocal is stored in it.

2. View the Get () method for threadlocal (P379①)

Also takes out the current thread's value.table () and then gets the data based on the index

How Message Queuing works (MessageQueue)

Operation of ① and MessageQueue

Insert (Enqueuemessage ()) and read (Next ()) (the read operation is accompanied by a delete operation)

②, Enqueuemessage () operation: Simple single-linked list insert operation next (): Search for an unlocked message and return it to the caller

How the Looper works

function : Different calls to the next () method of MessageQueue to see if there is a new message, if there is a new message will be processed immediately, if not have been blocked there.

Construction Method (P383①)

1. Save the current thread object. 2. Create a MessageQueue

Android's messaging mechanism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.