Handler in Android

Source: Internet
Author: User

When we are dealing with downloads or other tasks that need to be performed for a long time, if you place the handler function directly in the activity's OnCreate or onstart, it will cause the entire activity to be unresponsive during execution, and if the time is too long, the program will hang. Handler is the ability to put these functions in a single thread to execute, and the activity does not affect each other.

First, the definition of handler:
Handler mainly receives the data sent by the child threads, and updates the UI with this data in conjunction with the main thread to interact with the UI main thread. For example, you can use handler to send a message, and then in the handler thread to receive, process the message, to avoid directly in the UI main thread to handle the transaction caused by the main thread of the UI other processing work, Android provides handler as the main thread and child threads of the link You can also pass the handler object to another process to send events through handler in other processes, and you can delay the processing of some transactions by sending a message with the delay of handler.

Explanation: When the application starts, Android first opens a main thread (that is, the UI thread), and the main thread is the UI control in the admin interface for event distribution. For example, if you click on a button,android will distribute the event to the button, to affect your operation. 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, but when there are actions in the child thread that involve manipulating the UI, it can be dangerous to the main thread-that is, the update UI can only be updated in the main thread, and operating in a child thread is dangerous. This time, handler appeared to solve this complex problem, because handler runs 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 to pass over ( The child thread passes the message object with the Sedmessage () method (which contains data), puts the messages into the main thread queue, and updates the UI with the main thread.

Ii. Some features of handler

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), that is, after the handler object is initialized, the default is bound to the message queue of the process it initializes, Therefore, you can make use of the message queue contained in handler to establish some sequence of operations.

It has two functions: (1): Schedule a message or runnable to execute somewhere in a main thread, (2) Schedule an action to execute on a different thread

Some ways to distribute messages in handler

Post (Runnable)

Postattime (Runnable,long)

Postdelayed (Runnablelong)

The Post class method allows you to arrange a runnable object into the main thread queue

Sendemptymessage (int)

SendMessage (Message)

Sendmessageattime (Message,long)

Sendmessagedelayed (Message,long)

The SendMessage class method allows you to schedule a message object with data in the queue

Three, handler simple working principle diagram


Iv. Application Examples:

1, pass the message. Used to accept data sent by a child thread and update the UI with this data in conjunction with the main thread.

In Android, actions for the UI typically need to be placed in the main thread. If there is an action on the UI in the child thread, then it is necessary to send the data message to the message queue as a messages object, then use the Handlermessge method in handler to process the transmitted data information and manipulate the UI. The SendMessage Class (Messagemsg) method implements the operation that sends the message. The Handlemessage method that is overridden when initializing the handler object to receive Messgae and to perform related operations.

2. Pass the Runnable object. Used for Message Queuing that is bound by handler to schedule the execution of different operations.

When the handler object is initialized, the message queue is automatically bound by default. The class post method enables you to send a Runnable object to a message queue and execute the Run method in the different Runnable objects sequentially, in the same way as the queue mechanism.

In addition, Android CPU allocation of the smallest unit is a thread, handler is generally created in a line thread, so handler and thread are bound to each other, one by one. While Runnable is an interface, thread is a subclass of runnable. So, they're both a process.



Mars_androids the code in the video

Package Mars.handler;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public Class Handleractivity extends activity {/** Called when the activity is first created. *///declare two Button controls private button Startbutto    n = null;private Button Endbutton = null;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        The object that represents the control is obtained based on the control's ID, and the corresponding listener Startbutton = (button) Findviewbyid (R.id.startbutton) is not set by the two buttons.        Startbutton.setonclicklistener (New Startbuttonlistener ());        Endbutton = (Button) Findviewbyid (R.id.endbutton);            Endbutton.setonclicklistener (New Endbuttonlistener ()); } class Startbuttonlistener implements onclicklistener{@Overridepublic void OnClick (View v) {//Call handler's post method, the line to be executed        Added to the queue handler.post (updatethread);} } classEndbuttonlistener implements onclicklistener{@Overridepublic void OnClick (View v) {handler.removecallbacks (        Updatethread);}    }//Create a Handler object Handler Handler = new Handler (); The action to be performed writes the Run method of the thread object Runnable updatethread = new Runnable () {@Overridepublic void run () {System.out.println ("Updatet        Hread ");//Inside the Run method, execute the postdelayed or the Post method handler.postdelayed (Updatethread, 3000);} };}

The result of the program is that every 3 seconds, a line of Updatetread is printed on the console. This is because the Updatethread object that implements the Runnable interface enters an empty message queue and is immediately executed by the Run method, and within the Run method, it is sent again into the message queue after 3000ms.


3.handler and multithreading

Although the Post method sends a class object that implements the Runnable interface, it does not create a new thread, but instead executes the Run method in the object. That is, the operations in the entire run are on the same thread as the main threads.

This does not seem to affect those simple operations. But for long-time operations, there will be "suspended animation." To solve this problem, you need to bind the handler to a new open thread's message queue and process the Runnable objects and messages that pass through the message queue on the other thread.

Package Mars.handler;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.os.handlerthread;import Android.os.looper;import Android.os.message;public class HandlerTest2 extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.main);//Print the IDSystem.out.println of the current thread ("activity-->" + Thread.CurrentThread (). GetId ());//generates a Handlerthread object that implements the function of using looper to process Message Queuing, which is provided by the Android application framework Handlerthread Handlerthread = new Handlerthread ("Handler_thread");//The Start () of the class must be called before the Getlooper () method of the handlerthread is used;                  Handlerthread.start ();//The Looper obtained by Handlerthread is passed to the handler object, which is the message queue that is bound by the looper of the other thread instead of the default binding when handler is initialized. Handlerthread as the name implies is the thread that can handle the message loop, it is a thread that has looper can handle the message loop, or actually handler and a thread binding, rather say handler and Looper is one by one corresponding Of MyHandler MyHandler = new MyHandler (Handlerthread.getlooper ()); Message msg = Myhandler.obtainmessage ();//WillMSG is sent to the target object, the so-called target object, is the handler object that generated the Msg object Bundle B = new bundle (); B.putint ("Age", "a"); B.putstring ("Name", "Jhon"); Msg.setdata (b); Msg.sendtotarget ();} Class MyHandler extends Handler{public MyHandler () {}public MyHandler (Looper Looper) {super (Looper);} @Overridepublic void Handlemessage (Message msg) {Bundle b = msg.getdata (); int = B.getint ("Age"); String name = b.getstring ("name"); System.out.println ("Age was" + Age + ", name is" + name); System.out.println ("Handler--->" + thread.currentthread (). GetId ()); System.out.println ("Handlermessage");}}}

Thus, when a message is passed using the SendMessage method or the Runnable object is passed using the Post method, it is passed to the message queue in another thread that is bound to the handler object and will be processed in another message queue. The main thread will also continue at the completion of the send operation, without affecting the current operation.

It is important to note that the multithreading used here is not opened by the Runnable object, but by the Threadhandler object. The Runnable object is passed only as an object that encapsulates the operation and does not produce a new thread.

In the UI thread (main thread):

Mhandler=newhandler ();

Mhandler.post (Newrunnable () {

void Run () {

Execute code:

}

});

This thread is actually running within the UI thread and does not have a new thread.

A common way to create new threads is to:

Thread thread = Newthread ();

Thread.Start ();

Handlerthreadthread = new Handlerthread ("string");

Thread.Start ();





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.