Application Analysis of Android Handler main thread and general thread Communication

Source: Internet
Author: User
Tags time in milliseconds

Handler definition:It mainly accepts data sent by sub-threads and uses this data with the master thread to update the UI.
Explanation: When an application is started, Android will first enable 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 a Button, Android will distribute the event to the Button to respond to your operation. If you need a time-consuming operation, such as reading data online or reading a large local file, you cannot put these operations in the main thread, if you put it in the main thread, the interface will be suspended. If it is not completed in five seconds, you will receive an error message from the Android system, "Force disable ". At this time, we need to put these time-consuming operations in a sub-thread. Because the sub-thread involves UI update, the main Android thread is thread insecure, that is, updating the UI can only be updated in the main thread. Operations in the Child thread are dangerous. At this time, Handler came up to solve this complicated problem. Since Handler runs in the main thread (UI thread), it and the sub-thread can transmit data through the Message object. At this time, handler is responsible for receiving the Message object (which is transmitted by the Sub-thread using the sedMessage () method) sent by the sub-thread, (which contains data), and putting these messages into the main thread queue, updates the UI with the main thread.

Handler features
Handler can distribute the Message object and Runnable object to the main thread. Each Handler instance is bound to the thread that creates the handler (usually located in the main thread ).
It has two functions: (1) arranging a message or Runnable to execute somewhere in a main thread; (2) arranging an action to execute in different threads.

Methods for sending messages in Handler
Post (Runnable)
PostAtTime (Runnable, long)
PostDelayed (Runnable long)
SendEmptyMessage (int)
SendMessage (Message)
SendMessageAtTime (Message, long)
SendMessageDelayed (Message, long)
The post method above allows you to arrange a Runnable object to the main thread queue,
SendMessage class method, allows you to arrange a Message object with data into the queue, waiting for updates.

To change the UI content, you can only change the UI content in the main thread. The following figure shows how to dynamically change the UI content in Android: Start a thread timer first, this thread is responsible for the specific operations of dynamic changes to the UI. In addition, another thread is defined to be responsible for the communication between the main thread and the timer thread. This thread isHandler! It is a bridge between Runnable and Activity.

Steps:

1. define the specific implementation of Operation Title in MainActivity

Private int title = 0;

Protected void updateTitle () {setTitle ("welcome to Livingstone's blog" + title); // update the Title method in MainActivity. title ++ ;}

2. Define a Handler in MainActivity to update the Title.

private Handler changeTitleHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:updateTitle();break;}}};

3. Define an internal 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 in the onCreate method of MainActivity.

Timer timer = new Timer (); timer. scheduleAtFixedRate (new Mytack (), 1, 5000); // detailed description of 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!
Execute this Activity and you will see a program that dynamically updates the Title.

Handler usage:

1. to schedule messages and runnables to be executed as some point in the future;

Schedule messages and runnables to be executed at a certain time point in the future.

2. to enqueue an action to be passed med on a different thread than your own.

Bind the action to the queue for execution in a different thread. That is, inter-thread communication can be realized. For example, when you create a sub-thread, you can get the Handler object created in the main thread in your sub-thread 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.

1) create a Handler object (this is created in the main thread to facilitate UI updates ).

2) Build a Runnable object and update the interface in Runnable.

3) post to the UI thread in the run method of the sub-thread, and update the UI and Handler. post (runnable runa) with the Runnable object ).

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.