Handler message transmission mechanism (1)

Source: Internet
Author: User

Handler message transmission mechanism (1)

Why Handler:

For the sake of performance optimization, Android UI operations are not thread-safe, which means that if multiple threads operate the UI components concurrently, thread security problems may occur. To solve this problem, Android has developed a simple principle: only allow the UI thread (that is, the main thread) to modify the UI components in the Activity.
When a program is started for the first time, Android starts a main thread at the same time. The main thread is mainly responsible for processing UI-related events, for example, the user's key event, the user's access to the screen event, the screen drawing event, and the relevant event is distributed to the corresponding component for processing, so the main thread is often called the UI thread.

Handler concept:

1)Execute scheduled tasksYou can execute some tasks at a scheduled time and simulate the timer.
2)Inter-thread Communication. When an Android Application is started, a main thread is created, and a main thread is created.

Message Queue to process various messages.When you create a sub-thread, you can obtain the parent thread in your sub-thread.
The created Handler object can be used to send messages to the Message Queue of the parent thread.
. Because Android requires updating the interface in the UI thread, you can update the interface in other threads through this method.

The Handler class contains the following methods for sending and processing messages:

? Void handlerMessage (Message msg): the method used to process messages. This method is usually used for rewriting.
? Final boolean hasMessage (int what): Check whether the message queue contains a message with the value of what.
? SendEmptyMessage (int what): sends an empty message.
? Final boolean sendMessage (Message msg): sends the message immediately. Pay attention to the returned value. If the message is successfully placed in the Message queue, true is returned. Otherwise, false is returned. (personal suggestion: you don't have to remember this kind of problem. You can directly view the source code when using it. The Source Code contains detailed comments)

Handler:
(1) send messages in a thread.
(2) obtain and process messages in another thread.
The basic principle of Handler processing:

To enable the main thread to process messages sent by sub-threads in a timely manner, it is clear that only the callback method can be used to implement this. Developers only need to override the methods in the Handler class,When a newly started thread sends a message, the message is sent to the associated MessageQueue, And the Handler continuously obtains and processes the message from MessageQuere.----- This will cause the method for processing messages in the Handler class to be called back.
The basic steps for using Handler in a thread are as follows:
Complete the following in the called thread:
(1) Call The logoff prepare () method to create a logoff object for the current thread. When a logoff object is created, its constructor will create a matching MessageQueue.
(2) After loaning, create an instance of the Handler subclass and override the HandlerMessage () method to process messages from other threads.
(3) Call logoff's loop () method to start logoff.

Note: If the called thread is a main thread class, because the system automatically creates a logoff instance for the main thread, the first and third steps can be omitted, but only step 1 is required.
Completed in the call thread:
(1) create a message and fill in the content.
(2) Use the Handler instance created by the called class to call the sendMessage (Message msg) method.

Relationship between Handler and thread
Handler generally runs in the main thread or sub-thread, but must create a logoff object. In the main thread, Android has created a logoff object for it.

 

Handler is used in two common scenarios:
1. You can only modify the UI in the main UI. But in fact,Some UIS need to control the modification logic in the Child thread. Therefore, the sub-thread must notify the main thread through handler to modify the UI.. This is especially common in game development. For example, you need to periodically change the UI of the newly started thread. ,

The sub-thread notifies the main UI thread to modify the UI component.In this example, the new thread periodically modifies the image displayed by the ImageView:

In this example, Handler obtains, processes, and sends messages in the main thread.

 

Public class HandlerTest extends Activity {// define the IDint [] imageIds = new int [] {R. drawable. java, R. drawable. ee, R. drawable. ajax, R. drawable. xml, R. drawable. classic}; int currentImageId = 0; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); final ImageView show = (ImageView) findViewById (R. id. show); final Handler myHandler = new H Andler () // obtain, process, and update the UI component in the main thread. You can modify the UI component {@ Overridepublic void handleMessage (Message msg) {// if the message is the if (msg. what = 0x1233) {// dynamically modify the displayed Image show. setImageResource (imageIds [currentImageId ++ % imageIds. length]) ;}}; // defines a timer to periodically execute the specified task. The sub-thread notifies the main thread to modify the UI component to implement inter-process communication new Timer (). schedule (new TimerTask () {@ Overridepublic void run () {// send an empty message myHandler. sendEmptyMessage (0x1233); send messages in the thread }}, 0, 1200 );}}

2. To avoid ANR, You should execute a time-consuming operation in the Child thread. After this operation is completed, you may need to notify the main thread to modify the UI..

 

After a time-consuming task is executed in a child thread, the main thread is notified to modify the UI component.Example: use the new process to calculate the prime number and display it with Toast

In this example, a message is sent in the main thread, obtained in the subthread, and processed.

 

Public class CalPrime extends Activity {static final String UPPER_NUM = "upper"; EditText etNum; CalThread calThread; // defines a Thread class CalThread extends Thread {public Handler mHandler; public void run () {logoff. prepare (); // create a logoff object. Each thread needs to have a logoff object mHandler = new Handler () when using Handler. // obtain it using handler in the subthread, message Processing {// define the method for processing the Message @ Overridepublic void handleMessage (Message msg) {if (msg. what = 0x123) {int upper = msg. ge TData (). getInt (UPPER_NUM); List <integer> nums = new ArrayList <integer> (); // calculate the number of all prime numbers starting from 2 to upper outer: for (int I = 2; I <= upper; I ++) {// use all the numbers from where I is at the square root from 2 to where I is (int j = 2; j <= Math. sqrt (I); j ++) {// if division can be performed, this number is not a prime number if (I! = 2 & I % j = 0) {continue outer ;}} nums. add (I);} // use Toast to display all counts of Toast. makeText (CalPrime. this, nums. toString (), Toast. LENGTH_LONG ). show () ;}}; logoff. loop (); // start logoff }}@ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); etNum = (EditText) findViewById (R. id. etNum); calThread = new CalThread (); // start the new thread calThread. start () ;}// provides the event processing function public void cal (View source) {// creates a Message msg = new Message (); msg for the button click event. what = 0x123; Bundle bundle = new Bundle (); bundle. putInt (UPPER_NUM, Integer. parseInt (etNum. getText (). toString (); msg. setData (bundle); // sends the message calThread to the new Handler in the main thread. mHandler. sendMessage (msg); // send a message in the main thread }}</integer> </integer>

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.