Handler detail series (4) -- use Handler to send messages between the main thread and the sub-thread. handler details

Source: Internet
Author: User

Handler detail series (4) -- use Handler to send messages between the main thread and the sub-thread. handler details

MainActivity is as follows:

Package cc. c; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. OS. message; import android. widget. textView;/*** Demo Description: ** the example steps are as follows: * 1 The subthread sends a message to the subthread * 2 after receiving the Message 1, after the subthread sends a message to the main thread * 3 receives a message of 2, the main thread sends a message to the subthread ** to implement the subthread to send a message to itself, the key is the logoff passed in when Handler is constructed. * Here, The logoff of the subthread is passed in. the Code is as follows: * logoff. prepare (); * mHandlerTest1 = new H AndlerTest1 (logoff. mylogoff (); * logoff. loop (); ** so when mHandlerTest1.sendMessage (message); when a message is sent * Of course, it is sent to its own message queue. ** when the child thread receives the message sent by itself, it can continue to send the message to the main thread. in this case, you only need to note that the Handler passed in when constructing * Handler is the Handler of the main thread, that is, getMainLooper (). * Nothing else can be said. * ** sending a message to the subthread after the main thread processes the message ** in fact, there is nothing to send the message between these threads. The key is to construct the Logoff of the input during Handler. **/public class MainActivity extends Activity {private TextView mTextView; private HandlerTest1 mHandler Test1; private HandlerTest2 mHandlerTest2; private int counter = 0; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); init ();} private void init () {mTextView = (TextView) findViewById (R. id. textView); // 1 subthread sends a message to itself new Thread () {public void run () {logoff. prepare (); mHandlerTest1 = new HandlerTest1 (logoff. mylogoff (); Message message = New Message (); message. obj = "Hi ~ Hi "; mHandlerTest1.sendMessage (message); logoff. loop ();};}. start ();} private class HandlerTest1 extends Handler {private HandlerTest1 (low.logoff) {super (low. B ;}@ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); System. out. println ("subthread Received:" + msg. obj); // 2 after receiving the Message, you can resend the message to the main thread mHandlerTest2 = new HandlerTest2 (getMainLooper (); Message message = new Message (); message. obj = "O (∩ _ ∩) O"; mHan DlerTest2.sendMessage (message) ;}} private class HandlerTest2 extends Handler {private HandlerTest2 (Looper looper) {super (lods) ;}@ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); mTextView. setText ("in the main thread, receive a message from the Child thread:" + msg. obj); // 3 after receiving the Message, send the message to the subthread if (counter = 0) {Message message = new Message (); message. obj = "Xi ~ Xi "; mHandlerTest1.sendMessage (message); counter ++ ;}}}}

Main. xml is as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    >    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world"        android:layout_centerInParent="true"        android:layout_marginTop="70dip" />    </RelativeLayout>




Why can I use the following code to process multi-threaded messages of Android Handler and Message? Look,

1. If the thread does not have a termination condition, it will always send messages to the main thread. The main thread continuously calls the handleMessage code, which is easy to ANR (the application does not respond)
2. handler. obtainMessage () Get the message object more efficiently than new Message ();

How to Use the Android Handler mechanism?

The Handler object is in the same thread as its caller. If a delayed operation is set in Handler, the calling thread will also be blocked. Each Handler object is bound to a logoff object, and each logoff object corresponds to a Message Queue (MessageQueue ). If the logoff object bound to the Handler is not specified when the Handler is created, The logoff object of the current thread is bound to the Handler by default.
In the main thread, you can directly use new Handler () to create a Handler object, which will be automatically bound to the logoff object of the main thread. If Handler is directly created in a non-main thread, an error will be reported, the Android system does not enable logoff in the main thread by default, and the Handler object must be bound to the logoff object. In this case, you must manually enable logoff in this thread. prepare () --> logoff. loop (), and then bind it to the Handler object; or use logoff. getMainLooper () to obtain the Looper of the main thread and bind it to this Handler object.
All the messages sent by Handler are added to the logoff MessageQueue. Handler contains two queues: thread queue and message queue. post () can add the thread object to the thread queue; Use Handler. sendMessage () can be used to add a message object to a message queue. The source code analysis shows that Handler has only one message queue, namely, MessageQueue. The thread object passed through post () will be encapsulated into a message object and passed into MessageQueue.
After a thread object is put into a Message Queue using post (), when logoff polls the thread for execution, it does not actually start a new thread separately, but it is still executed in the thread bound to the current logoff. Handler only calls the run () of the thread object. For example, the UI update command is defined in the Child thread. If the thread is directly enabled for execution, an error is reported () add it to the Logoff of the main thread and execute it to update the UI.
After you use sendMessage () to add a message object to a message queue, when logoff polls the message, handleMessage () of Handler is called to process it. Taking UI update as an example, if this method is used, the Logoff of the main thread is first bound to the Handler object, and handleMessage () is overloaded to process UI updates, then you can send a message to it.

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.