Android:handler implementing asynchronous processing capabilities

Source: Internet
Author: User

I. A question

There is a question worth thinking about, if you write something like a download (which is time-consuming and not necessarily a result) in the activity (main thread), it causes activity to block and is unresponsive for a long time until the page is suspended from animation (if 5 seconds has not been completed, will receive an error "forced shutdown" on the Android system. Therefore, we need to put these time-consuming operations on separate sub-threads. This is the mission of handler. Handler provides the function of asynchronous processing, sending and receiving is not simultaneous (the main thread of the activity and threads in the thread queue are different threads, in parallel, without affecting each other).

Two. Handler Introduction

Handler is a thread communication tool in the Android operating system, which is primarily composed of two functions: (1) arranging messages or runnable somewhere in the main thread to execute (2) to schedule an action to execute in another thread. Each handler object maintains two queues (FIFO), Message Queuing, and runnable queues, all of which are provided by the Android operating system. The handler can be separated by these two queues:

    1. Send, receive, process messages – Message Queuing;
    2. Start, end, hibernate thread –runnable queue;

The use of handler is broadly divided into 3 steps: 1. Create a Handler object. 2. Create runnable and messages. 3. Call the Post and the SendMessage method to add runnable and messages to the queue.

Three. Runnable queue

Threads in 1.java

In Java, there are two ways to create a thread: Inherit the thread class and implement the Runnable interface. The most important thing is to replicate the Run method to implement threading functionality. When the thread's time slice is up and running, the run () function executes and goes to the death state.

To give an example of creating a thread:

Runnable r=new Runnable () {  @Override public void Run () {//TODO auto-generated Method stub System.out.println ("Thread "); handler.postdelayed (thread, 3000); } };

  

2. About the runnable queue

(1) principle

Android thread asynchronous processing mechanism: Handler object maintains a thread queue, with new runnable sent (post ()), put it at the end of the team, while processing runnable, take out runnable execution from the team head. When a runnable is sent to the queue, it is returned immediately, regardless of whether runnable is executed, whether execution succeeds, and so on. and the specific implementation is when queued to the runnable after the system to carry out. This is like the Post office example. When the sender writes the letter and puts it in the mailbox, he does not know when the mail is distributed to the Post office, when it is sent, and how the other person reads it. In this way, the asynchronous processing mechanism of Android is implemented.

(2) Specific operation

To add a thread to a queue:

Handler.post (Runnable); add Runnable directly into the queue

Handler.postdelayed (Runnable, long) after a certain amount of delay, add Runnable into the queue

Handler.postattime (Runnable,long) to add Runnable to queue periodically

To terminate a thread:

Handler.removecallbacks (thread); remove runnable from the runnable queue

Four. Message Queuing

1. Message objects

(1) Message Object

The message object carries the data, usually it uses the ARG1,ARG2 to pass messages, and of course it can have the obj parameter, which can carry the Bundle data. It is characterized by a very low system performance consumption.

Initialization: Message msg=handler.obtainmessage ();

(2) Bundle Object

Bundles are classes provided by Android and can be seen as a special map, a packet of key-value pairs. In particular, the keys and values must be either basic data types or arrays of basic data types (the map's key requirements are objects), and, specifically, the key requirements are string types. Use message to carry bundle data:

Put in: Msg.setdata (bundle bundle);

Remove: Msg.getdata ();

2. About Message Queuing

(1) principle

Android message asynchronous processing mechanism: The handler object maintains a message queue, when a new message is sent (SendMessage ()), it is placed at the end of the team, and then queued until the message is processed by the handler object of the main thread ( Handlemessage ()). The whole process is also asynchronous, and the same principle as the runnable queue.

(2) Specific operation:

Add Runnable:handler.sendMessage (Message) to the queue;

Sends a message to the message Queue msg.sendtotarget ();

After a certain amount of delay, the message is sent to Message Queuing handler.sendmessagedelayed (Message,long);

Timed messages sent to Message Queuing Handler.sendmessageattime (Message,long)

Processing messages:

For the specific processing of the message, you need to override the handler handlemessage (Message msg) method with the anonymous inner class in the new handler object, as follows:

Handler handler=new Handler () {  @Override public void Handlemessage (Message msg) {//TODO auto-generated method stub. 。。。。。  ... } };

  

Five. Two effects of handler

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

code example:

 Public classHandlertestactivityextendsActivity {PrivateButton start; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method StubSuper. OnCreate (savedinstancestate); Setcontentview (r.layout.handlertest); start=(Button) Findviewbyid (R.id.start); Start.setonclicklistener (NewStartlistener ()); System.out.println ("Activity Thread:" +Thread.CurrentThread (). GetId ()); } Handler Handler=NewHandler (); Runnable Thread=NewRunnable () {@Override Public voidrun () {//TODO auto-generated Method StubSystem.out.println ("Handlerthread:" +Thread.CurrentThread (). GetId ()); } }; classStartlistenerImplementsonclicklistener{@Override Public voidOnClick (View v) {//TODO auto-generated Method Stubhandler.post (thread);} }  } 

In this applet, the program starts, enters OnCreate (), prints out the ID of the current thread (i.e. the main thread), and then clicks the button start, which adds thread threads to the thread queue, and the role of the thread thread,thread is to print out the ID of the current thread. In this program, we can see that by handler we can make arrangements for Runnable to execute somewhere in a main thread, that is, the role (1).

But there's a little trap here, you see? This program seems to implement the handler asynchronous mechanism, Handler.post (thread) seems to implement the role of city thread, but through execution we find that two threads have the same ID! That is, actually thread is the original main thread, so that the Handler.post () method is not really a new thread, just executed on the original thread, we do not implement the asynchronous mechanism.

2. Schedule an action to execute in another thread.

(1) Standard method of creating threads in Java

The first step:

Runnable r=New  Runnable () {  publicvoid//  SYSTEM.OUT.PRINTLN ("Thread"3000

Step Two:

Thread t=New thread (r);

Step Three:

T.start ();

If the above example program in the Handler.post (thread), the statement changed to the above form, by printing we can see that two IDs are different, the new thread started!

(2) About Looper

The Looper class is used to open a message loop for a thread that can iterate through the message queue, so looper is actually the encapsulation of the message Queue + message loop. Each thread can only correspond to one looper, except the main thread, and the threads in Android do not have looper turned on by default.

Interacting with Looper through handler, handler can be seen as a looper interface for sending messages to the specified Looper and defining processing methods. By default, handler binds to the looper of its thread, namely:

Handler handler=new Handler (); equivalent to Handler handler=new Handler (Looper.mylooper ());

There are two main methods of Looper:

Looper.prepare (); Enable Looper
Looper.loop (); Let Looper start working, take messages from the message queue, and process the messages.

Note: code written after Looper.loop () will not be executed, the function should be inside a loop, and the loop will not abort until the Mhandler.getlooper (). Quit () is called.

(3) Implementation of handler asynchronous mechanism

Handler is the handlerthread that makes the child thread and the main thread separate from the thread. In fact, Handlerthread is a special thread, it's a thread that encapsulates good looper,

code example:

//Create a Handlerthread object named Handler_hreadHandlerthread handlerthread=NewHandlerthread ("Handler_hread"); //Open Handlerthread, you must call the Start method before using Handlerthread.getlooper (), otherwise the emptyHandlerthread.start (); //bind the handler to the Handlerthread Looper, that is, the handler is running in the Handlerthread thread.MyHandler handler=NewMyHandler (Handlerthread.getlooper ()); classMyHandlerextendshandler{ PublicMyHandler () {} PublicMyHandler (Looper Looper) {Super(Looper);} @Override Public voidhandlemessage (Message msg) {//TODO auto-generated Method StubSystem.out.println ("Activity Thread:" +Thread.CurrentThread (). GetId ()); } } 

In this way, the handler asynchronous processing mechanism is implemented, and the thread ID of the Handler.post () method is called to know that the child thread and the main thread belong to different threads.

Android:handler implementing asynchronous processing capabilities

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.