Android: Implementing asynchronous processing with Handler

Source: Internet
Author: User

Android: Implementing asynchronous processing with Handler-51cto.com

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:

    1. Runnable r=New Runnable () {
    2. @Override
    3. Public void Run () {
    4. //TODO auto-generated method stub
    5. System.out.println ("thread");
    6. Handler.postdelayed (thread, up);
    7. }
    8. };

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:

    1. Handler handler=New Handler () {
    2. @Override
    3. Public void handlemessage (Message msg) {
    4. //TODO auto-generated method stub
    5. 。。。。。。
    6. 。。。。。。
    7. }
    8. };
Five. Two effects of handler

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

code example:

  1. Public class Handlertestactivity extends Activity {
  2. Private Button start;
  3. @Override
  4. protected void onCreate (Bundle savedinstancestate) {
  5. //TODO auto-generated method stub
  6. Super. OnCreate (savedinstancestate);
  7. Setcontentview (r.layout.handlertest);
  8. Start= (Button) Findviewbyid (R.id.start);
  9. Start.setonclicklistener (new Startlistener ());
  10. System.out.println ("Activity Thread:"+thread.currentthread (). GetId ());
  11. }
  12. Handler handler=New Handler ();
  13. Runnable thread=New Runnable () {
  14. @Override
  15. Public void Run () {
  16. //TODO auto-generated method stub
  17. System.out.println ("handlerthread:"+thread.currentthread (). GetId ());
  18. }
  19. };
  20. class Startlistener implements onclicklistener{
  21. @Override
  22. Public void OnClick (View v) {
  23. //TODO auto-generated method stub
  24. Handler.post (thread);
  25. }
  26. }
  27. }

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:

    1. Runnable r=New Runnable () {
    2. @Override
    3. Public void Run () {
    4. //TODO auto-generated method stub
    5. System.out.println ("thread");
    6. Handler.postdelayed (thread, up);
    7. }
    8. };

Step Two:

    1. Thread t=New thread (r);

Step Three:

    1. 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:

  1. //Create a Handlerthread object named Handler_hread
  2. Handlerthread handlerthread=New handlerthread ("Handler_hread");
  3. //Open Handlerthread, you must first call the Start method before using Handlerthread.getlooper (), otherwise the empty
  4. Handlerthread.start ();
  5. //Bind the handler to the Handlerthread Looper, that is, this handler is run in the Handlerthread thread
  6. MyHandler handler=New MyHandler (Handlerthread.getlooper ());
  7. class MyHandler extends handler{
  8. Public MyHandler () {}
  9. public MyHandler (Looper Looper) {
  10. Super (Looper);
  11. }
  12. @Override
  13. Public void handlemessage (Message msg) {
  14. //TODO auto-generated method stub
  15. System.out.println ("Activity Thread:"+thread.currentthread (). GetId ());
  16. }
  17. }

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.

----------------------------------------------------------------------

Google's instructions for handler

A Handler allows you to send and process and Message Runnable objects associated with a thread ' s MessageQueue . Each Handler instance are associated with a single thread and that thread ' s message queue. When you create a new Handler, it's bound to the thread/message queue of the thread that's creating it--from that PO int on, it'll deliver messages and runnables to that message queue and execute them as they come out of the message Queu E.

There is both main uses for a Handler: (1) to schedule messages and runnables to being executed as some point in the future; and (2) to enqueue an action to being performed on a different thread than your own.

Scheduling messages is accomplished with the post (Runnable) , postattime (Runnable, long) , Code>postdelayed (Runnable, Long) , sendemptymessage (int) , sendMessage (Message) , sendmessageattime (message, long) , and sendmessagedelayed (message, Long) methods. post versions allow you to Enqueue Runnable objects to being called by th E Message queue when they is received; The sendMessage versions allow you to enqueue a message Object containing a bundle of data that would be processed by the Handler ' s handlemessa GE (Message) method (requiring that implement a subclass of Handler).

When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue are ready To does, or specify a delay before it gets processed or absolute time for it to be processed. The latter-implement timeouts, ticks, and other timing-based behavior.

When a process was created for your application, its main thread was dedicated to running a message queue this takes care of Managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is do by calling the same post or SendMessage methods as before, but from your new thread. The given Runnable or message is then is scheduled in the Handler ' s message queue and processed when appropriate.

Android: Implementing asynchronous processing with handler

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.