Learning about Android threads

Source: Internet
Author: User

When the applicationProgramAt startup, the system creates a process for it, and also creates a thread named main, creating all its components, and processing system events, the system callback and other application-related tasks run in the main thread. This thread is commonly known as the main thread ). It is also known as the UI thread, because only the main thread can operate the UI-related things, so someone calls the main thread also called the UI thread. Why can't non-main threads operate the UI? Because UI operations often lead to system callbacks, if a third thread is allowed to perform operations, the system callback may be disordered, which in turn will disrupt the time sequence of the entire framework!
All components in the same process run in the same thread. Activiy, service, boradcastreceiver, and contentprovider both run in the main thread. The most common mistakes are service. Both documents and common sense think that the service is used in the background for time-consuming operations, but in fact it is not. If you do time-consuming operations in the service, it will also lead to the notorious ANR (application not responding ). Therefore, if you want to use the service as a server, you must use handlerthread or thread in the service to create a worker thread!
The same is true for the activity. After you start activity (), you start a new activity, but they all run in the same thread, so you still cannot perform time-consuming operations in the original activity! That is, after startactivity () is called to start a new activity, or time-consuming operations in onpause (), onstop (), ondestroy () will lead to ANR.
The same is true for contentprovider. If it is in the same process as other components, calling the contentresolver method is equivalent to directly calling the contentprovider method. If it is in another process, although it is through IPC, it is also synchronized, because the synchronization of ibinder, that is, when contentresolver is called, the caller's process will be suspended, wait until the contentprovider process operation is complete, and then pass the result to the caller process! Therefore, if contentprovider has time-consuming operations or locks the database synchronously, pay attention to the occurrence of ANR!
So remember: A process has only one main thread, and all components are running in the main thread.
Therefore, if there are time-consuming operations, you must create a worker thread!

 

1. Message Message message, which is understood as information exchanged between threads. When the background thread for data processing needs to update the UI, the message contains some data to the UI thread. 2. Handler Handler is the main handler of the message, responsible for sending the message and executing the message content. The background thread is referenced by the passed handler object. Sendmessage (Message) . When handler is used, the implement class Handlemessage (Message) Method, such as update UI. It is usually necessary to subclass handler to implement the handlemessage method. 3. Message Queue Message Queue is a message queue used to store messages published by handler and run first-in-first-out. Each message queue has a corresponding handler. Handler sends a message to the message queue in two ways: sendmessage or post. Both messages are inserted at the end of the message queue and executed first-in-first-out. However, messages sent using the two methods are executed in a slightly different way: a message object is sent using sendmessage, which will be processed by the handlemessage () function of handler; the post method sends a runnable object, which is executed by itself. 4. Logoff Logoff is the manager of the message queue in each line. Android does not have a global message queue, while Android automatically creates a message queue for the main thread (ui thread), but no message queue is created in the Child thread. Therefore, the logoff value of the main thread obtained by calling logoff. getmainlogoff () is not null, but the logoff value of the current thread may be null by calling logoff. mylogoff.

The API Doc provides the correct method for using logoff for sub-threads:

  1. Class looperthread extends thread {
  2. Public handler mhandler;
  3.  
  4. Public void run (){
  5. Logoff. Prepare (); // Create the Logoff of this thread and create a messagequeue
  6.  
  7. Mhandler=NewHandler (){
  8. Public void handlemessage (Message MSG ){
  9. // Process incoming messages here
  10. }
  11. };
  12. Logoff. Loop (); // Start logoff and listen to message queue
  13. }
  14. }

The general process of this message mechanism:

1. After the logoff. Loop () method starts running, the non-null message in the message queue is retrieved cyclically in the receiving order.

2. At the beginning, all messages in the message queue are null. When handler. sendmessage (Message) is sent to message queue, this function sets the target attribute of the message object to the current handler object. Then logoff retrieves the message, and calls the dispatchmessage function of the hander to which the target of the message points to process the message.

In the dispatchmessage method, the user determines how to process the message. The priority ranges from high to low:

1) callback in the message, an object that implements the runnable interface, where the run function is used for processing;

2) The mcallback in handler points to an object that implements the callback interface, which is processed by the handlemessage;

3) the classes corresponding to the handler object for processing messages inherit and implement the handlemessage function. The handlemessage function is used to process messages.

We can see that the handlemessage method we implemented has the lowest priority!

3. After handler processes the message (update UI), logoff sets the message to NULL for recycling!

There are manyArticleDescribes how the main thread interacts with other sub-threads, transmits information, and who finally processes the information, my personal understanding is the simplest method-this thread is used to determine which thread the logoff object in the handler object belongs! 1. When the constructor parameter of the handler object is null, It is the Logoff of the current thread; 2. logoff. getmainlogoff () obtains the logoff object of the main thread, and logoff. mylogoff () obtains the logoff object of the current thread.  

Android also provides a tool class: asynctask. It makes the use of the UI thread very simple. It makes it easier to create long-running tasks that need to interact with the user interface, without the need to use threads and handler.

1) subclass asynctask 2) implement the following methods defined in asynctask onpreexecute () to prepare for execution; doinbackground (Params ...) start to execute background processing. You can call publishprogress to update the real-time task progress. onprogressupdate (Progress ...) after the publishprogress method is called, the UI thread calls this method to display the progress of the task on the interface, for example, through a progress bar. Onpostexecute (result) after the operation is completed, the result is sent to the UI thread. None of the four methods can be called manually. Besides doinbackground (Params ...) the other three methods are called by the UI thread, so the requirements are as follows: 1) The asynctask instance must be created in the UI thread; 2) the asynctask.exe cute method must be called in the UI thread. Note that the task can only be executed once. Otherwise, exceptions may occur during multiple calls. In addition, you cannot manually stop it. Pay attention to this to see if it meets your needs! During usage, we found that the parameter settings of the asynctask constructor should be clear: Asynctask <Params, progress, result> Params corresponds to the doinbackground (Params...) parameter type. New asynctask(cmd.exe cute (Params... params), that is, the incoming Params data. You can execute (data) to transmit one data, or execute (data1, data2, data3) data. Progress corresponds to the parameter type of onprogressupdate (Progress...); Result corresponds to the parameter type of onpostexecute (result. If none of the preceding parameter types need to be specified, use void. Note that it is not void. For more information, see the example above or the example in the API Doc.
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.