The relationship among message, handler, message queue, and logoff in the single-thread model.

Source: Internet
Author: User

1. Android Process
When a program is started for the first time, Android starts a Linux Process and a main thread. By default, all components of the program will run in the process and thread.

At the same time, Android assigns a separate linux user to each application. Android will try to keep a running process. When the memory resources are insufficient, Android will try to stop some processes and release enough resources for other new processes to use, it can also ensure that the current process being accessed by the user has enough resources to respond to the user's events in a timely manner. Android judges the importance of a process based on the component category and component Status in the process. Android first stops unimportant processes.

FollowImportanceThere are five levels from high to low:

Foreground Process
The foreground process is the process currently in use by the user. Only some foreground processes can exist at any time. They are the last one ended, when the memory is low to the root of them can not run. In general, in this case, the device will perform memory scheduling and stop some foreground processes to maintain a response to user interaction.
Visible Process
The visible process does not contain foreground components, but displays a visible process on the screen. It is very important, unless the foreground process needs to obtain its resources, it will not be aborted.
Service Process
Run a service that is started using the startservice () method. This service is not of the two higher importance mentioned above. Although the process where the service is located is not directly visible to users, they execute tasks that users are very concerned about (such as playing MP3 and downloading data from the network ). As long as the foreground and visible processes have enough memory, the system will not recycle them.
Background Process
Run an activity that is invisible to the user (the onstop () method has been called ). these processes have no direct impact on the user experience. They can be recycled when the service process, visible process, and frontend process require memory. Generally, many invisible processes are running in the system. They are stored in the LRU (least recently used) list so that they can be recycled immediately when the memory is insufficient. If an activity executes its lifecycle, closing the process has no significant impact on user experience.
Empty Process
No program components are running. The only reason for running these processes is to use them as a cache to shorten the restart time required by the next program. The system often terminates these processes, which can adjust the balance between program cache and system slow storage.
When Android rates the importance of processes, it selects the highest level. In addition, when another process is dependent, the level of a process may increase. A process serving other processes will never be more important than the service process. Because the service process is more important than the background activity process, it is best to start a service for a time-consuming activity, instead of starting a sub-process, this operation takes longer time than the activity. For example, playing music in the background and uploading images captured by cameras to the Internet. Using the service, processes can obtain at least the important level of the service process, you do not need to consider the current status of the activity. Broadcast
When receivers is time-consuming, it should also enable a service rather than opening a thread.
2. Single-threaded Model
When a program is started for the first time, Android starts a corresponding main thread at the same time. The main thread is mainly responsible for processing UI-related events, such as user key events, the user contacts screen events and Screen Drawing events, and distributes related events to corresponding components for processing. Therefore, the main thread is often called the UI thread. When developing Android applications, you must follow the single-thread model principle: Android UI operations are not thread-safe and must be executed in the UI thread.
2.1 The Sub-thread updates the UI
The android UI is single-threaded. To avoid dragging the GUI, some time-consuming objects should be handed over to independent threads for execution. If the background thread executes the UI object, Android will send an error message.
Calledfromwrongthreadexception. When such an exception is thrown in the future, you must know how to handle it!
2.2 Message Queue
In the single-thread model, Android designs a message queue to solve similar problems. The message queue can be used between threads to exchange information with handler and logoff components. They are described as follows:
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 uses the passed handler object reference to sendmessage ). When handler is used, handlemessage (Message) of implement class is required)
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:

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 many articles on the Internet about how the main thread interacts with other sub-threads, how information is transmitted, and who finally processes 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.

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.