Application analysis of Android handler main thread and general threading communication

Source: Internet
Author: User

handler definition: mainly accepts the data sent by the child thread, and updates the UI with this data in conjunction with the main thread .
Explanation: When the application starts,Android first turns on a main thread (that is, the UI thread), the main thread is the UI control in the management interface , for event distribution, for example, if you click on a button, Android will distribute the event to the button, To respond to your actions. If you need a time-consuming operation at this time, for example: network read data, or read a large local file, you can not put these operations in the main thread, if you put in the main thread, the interface will appear suspended animation, if 5 seconds has not been completed, you will receive an Android system error message Force Close. This time we need to put these time-consuming operations on a sub-thread, because the child threads involve UI updates, the Android main thread is not secure, that is, the update UI can only be updated in the main thread, and the operations in the child threads are dangerous. At this time, handler appeared to solve this complex problem. Since handler runs in the mainline approached (UI thread), it and the child thread can pass the data through the message object, and at this time, the handler is assumed to be transmitted by the receiving sub-thread (the child thread is passed with the Sedmessage () method) Message object, ( Contains data), put these messages into the main thread queue, with the main thread to update the UI.

Handler some features
Handler can distribute the Message object and the Runnable object into the main thread, and each handler instance is bound to create his line approached (typically on the main thread).
It has two functions: (1), arranges messages or runnable to be executed somewhere in a main thread, and (2) arranges an action to execute on a different thread.

Some ways to distribute messages in handler
Post (Runnable)
Postattime (Runnable,long)
Postdelayed (Runnable Long)
Sendemptymessage (int)
SendMessage (Message)
Sendmessageattime (Message,long)
Sendmessagedelayed (Message,long)
The Post class method above allows you to arrange a runnable object into the main thread queue,
The SendMessage class method allows you to schedule a message object with data to queue and wait for updates.

To change the UI content only within the main thread, here is an implementation on Android that dynamically changes the content of the UI interface: Start a thread timer, which is responsible for the specific action of dynamic changes to the UI, and then define a thread that is responsible for the communication between the main thread and the timer thread. This thread is Handler! It is the bridge between the runnable and the activity interaction.

Steps:

1, in the Mainactivity definition Operation title Concrete implementation

private int title = 0;

protected void Updatetitle () {Settitle ("Welcome to Livingstone ' s blog" + title);//mainactivity update title method title++;}

2. Define a handler in mainactivity to update the title

Private Handler Changetitlehandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {switch (msg.what) {CA Se 1:updatetitle (); break;}};

3. Define an inner class of timertask type in mainactivity, this task inherits from runnable!

Private class Mytack extends TimerTask {//Public abstract class TimerTask implements runnable{} @Overridepublic void Run () {Message msg = new Message (); msg.what = 1;changetitlehandler.sendmessage (msg);}}

4. Add a timer to the OnCreate method in Mainactivity

Timer timer = new timer (), Timer.scheduleatfixedrate (New Mytack (), 1, 5000);//Method detailed Timer.scheduleatfixedrate (timertask Task, long delay, long period)

* @param Task | The task to schedule.
* @param delay | Amount of time in milliseconds before first execution.
* @param period | Amount of time in milliseconds between subsequent executions.

Ok!
To perform this activity, you will see a program with the title dynamically updated.

Handler Use occasions:

1, to schedule messages and runnables to being executed as some point in the future;

Schedule messages and runnables to be executed at a later point in time.

2, to enqueue an action to being performed on a different thread than your own.

The action is queued for execution in a different thread. That is, you can implement inter-thread communication. For example, when you create a sub-thread, you can get the handler object created in the main thread in your child thread, and you can send a message to the parent's message queue through that object. Because Android requires the interface to be updated in the UI thread, you can update the interface in other threads with this method.

1), create the handler object (created here in the main thread for easy updating of the UI).

2), constructs the Runnable object, updates the interface in the runnable.

3), post,runnable the object to the UI thread in the Run method of the child thread to update ui,handler.post (Runnable Runa).

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.