Android Basics Summary: (14) handler detailed (UP)

Source: Internet
Author: User

Definition of handler:

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 opens 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 action.

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.

By this time, Handler appeared. To solve this complex problem, because handler is running in the mainline approached (UI thread), it and the child thread can pass the data through the Message object, at this time, the handler undertakes to accept the child thread passed over (the child thread uses the Sedmessage () method to pass the younger brother) The Message object, which contains data, is placed in the main thread queue and updated with the main thread.

Handler Concept Explanation:

The handler class allows you to send messages and process messages and runnable objects in the thread message queue. Handler instances are used with a thread and Message queuing for that thread, and once a new handler instance is created, the system binds the instance to a thread and Message queuing for that thread, which can send messages and runnable objects to the message queue. and processing them at the exit of the message queue.

There are two main uses of the handler class: 1. According to the time schedule, at some point in the future, a message is processed or an runnable instance is executed. 2. Avoids inter-thread collisions by placing an operation request for another thread object into the message queue.

The time class message is used in the following ways: Post (Runnable), Postattime (Runnable, Long), postdelayed (Runnable, Long), sendemptymessage (int), SendMessage (Message), Sendmessageattime (message, long), and sendmessagedelayed (message, long)

Functions such as methods.post can transfer a Runnable object to a message queue and be called after it arrives at the message queue. Functions such as SendMessage can pass a message object containing data that can be handled by the Handlemessage (message) method of the handler class.

Functions such as post and SendMessage can specify when a message is executed, whether it is executed immediately, later, or at a certain point in time. This can be used to implement timeouts, messages, or other time-related operations.

When a process starts, the main thread executes a message queue independently, which manages the top-level objects (such as: activities, broadcast receivers, and so on) and all created Windows. You can create your own thread and communicate with the main thread through handler. This can be accomplished by invoking the handler post and SendMessage operations of the main thread in the new threads.

Handlerthread/looper & MessageQueue & Message Relationship:

The handler is responsible for encapsulating the information that needs to be passed into a message, passing it to looper through the SendMessage () of the Handler object, and Looper putting it in MessageQueue. When the Looper object sees that the MessageQueue contains a message, it broadcasts it. After the handler object receives the message, it calls the corresponding handler object's Handlemessage () method to process it.

Handler some features

Handler can distribute the Message object and the Runnable object into the main thread, each handler instance is bound to create his line approached (typically in the main thread), and it has two functions:

(1): Schedule a message or runnable to execute somewhere in a main thread.

(2) Schedule an action to be executed in 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.

Use of Handler
Here are two examples to explain:
Example 1:
public class Handlertest extends activity {/** Called when the activity is first created. */private Button Startbutton;pri Vate Button Endbutton; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main);//Get Control object Startbutton = (Button) Findviewbyid (R.id.startbutton) based on ID; Endbutton = (Button ) Findviewbyid (R.id.endbutton);//Set Listener Startbutton.setonclicklistener for the control (new Startbuttonlistener ()); Endbutton.setonclicklistener (New Endbuttonlistener ());} Class Startbuttonlistener implements Onclicklistener {public void OnClick (View v) {//Call Handler's post () method, Put the thread object you want to execute into the queue handler.post (Updatethread);}} Class Endbuttonlistener implements Onclicklistener {public void OnClick (View v) {//Call handler Removecallbacks () method, Delete Thread Object Handler.removecallbacks (updatethread) not executed in queue;}} Creates a handler object handler handler = new handler ();//Create a new Thread object Runnable updatethread = new Runnable () {//The action to be performed in the run method of the Write thread object p ublic void Run () {System.out.println ("Updatethread");Call Handler's postdelayed () method//The function of this method is to put the thread object that will be executed into the queue, after the time is over, run the developed thread object//The first parameter is the runnable type: The thread object to be executed// The second parameter is a long type: The delay time, in milliseconds handler.postdelayed (Updatethread, 3000);}};}


Example 2:

An application has a progress bar and a button that, when clicked, is part of a progress bar every second.

For the application to run:


public class Progressbarhandlertest extends activity {/** Called when the activity is first created. */private ProgressBar Progressbar;private Button Startbutton; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.main);p Rogressbar = (progressBar) Findviewbyid (R.id.progressbar); Startbutton = (Button) Findviewbyid (R.id.startbutton); Startbutton.setonclicklistener (new Progressbaronclicklistener ());} Class Progressbaronclicklistener implements Onclicklistener {public void OnClick (View v) {// Set the progress bar to a visible state progressbar.setvisibility (view.visible); Updatebarhandler.post (Updatethread);}} Use the anonymous inner class to write the Handlermessage () method in Handler Handler Updatebarhandler = new Handler () {@Overridepublic void Handlemessage ( Message msg) {progressbar.setprogress (MSG.ARG1); Updatebarhandler.post (updatethread);//The thread that will be executed is put into the queue}};//the thread class, The class is declared using an anonymous inner class Runnable updatethread = new Runnable () {int i = 0;public void run () {//TODO auto-generated method Stubsys Tem. OUT.PRINTLN ("Begin Thread"); i + = 10;//Get a Message object, message class is an Android system-supplied message msg = Updatebarhandler.obtainmessage () ;//Set the value of the ARG1 parameter of the message object to IMSG.ARG1 = i; Passing messages with the two member variables arg1, ARG2, the advantage is that system performance consumes less try {thread.sleep (1000);//Let the current thread hibernate 1000 milliseconds} catch (Interruptedexception ex) { Ex.printstacktrace ();} Add Message object to Message Queue Updatebarhandler.sendmessage (msg);//If the value of I equals 100if (i = = 100) {// Remove the thread object from the queue updatebarhandler.removecallbacks (Updatethread);}};}

the relationship between handler and Threads

Handler by default, it is actually on the same thread as the activity that called it.

For example, in Example 1 of the use of handler (i), although the thread object is declared, it does not invoke the thread's start () method in the actual call, but instead calls the current thread's run () method directly.

By an example to confirm

An Android application that creates handler and thread objects in activity and outputs the ID and name of the current thread in the activity's OnCreate () method, and then prints the ID and name of the current thread under the output from the run method of the Threaded object. If the result of the activity output is the same as the result of the thread object output, then it means that they are using the same thread.

Here is the activity code:

public class Handlertwo extends activity {/** Called when the activity is first created. */handler Handler = new Handler () ; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);//Call the Post method before setting up the layout file ,//indicates that the contents of the layout file are not displayed until after the thread has been executed, and the thread is set to hibernate for 10 seconds,//So the final effect is to display the application main interface and wait 10 seconds before displaying the contents of the layout file Handler.post (r); Setcontentview (R.layout.main); SYSTEM.OUT.PRINTLN ("Activity ID--->" + thread.currentthread (). GetId ()); System.out.println ("Activity name--->+ thread.currentthread (). GetName ());} Runnable r = new Runnable () {public void run () {//outputs the ID of the current thread and name//if the thread ID, name and the thread ID that is output in the above OnCreate () method is the same as the It means that they are using the same thread System.out.println ("runnable_id--->+ thread.currentthread (). GetId ()); System.out.println ("Runnable_name--->+ thread.currentthread (). GetName ()); try {thread.sleep (10000); Let the thread hibernate for 10 seconds} catch (Interruptedexception e) {e.printstacktrace ();}}};}

As you can see from the results, the IDs and name of the two outputs are the same, and they use the same thread.

Now modify the code in the activity, create a thread thread, then call the thread's start () method, and then look at the output of the console.

Just make a little change to the above code.

1. Handler.post (R) is commented out first.

2, add the following two lines of code is OK.

Handler.post (R); Thread t = new Thread (r); T.start ();

As you can see from this output, the ID of the thread object, name is completely different from the thread ID and name in the activity, so they are not using the same thread.

This example also conceals an effect, that is, we usually put the handler post () method after the Setcontentview (R.layout.main) This method is called, will be set up after the layout and then perform other operations, and in this example, is to place the handler post () method before the SetContent () method, and the run () method of the thread object passed in the post, and the sleep thread is executed for 10 seconds, so the effect of running the implementation will be, when the program runs, First, there is nothing on the activity, and after 10 seconds, the contents of the activity are displayed.

Welcome to read the following article:

Android Basics Summary: (15) handler details (next)




Android Basics Summary: (14) handler detailed (UP)

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.