Android Development Notes--some summaries on handler (i)

Source: Internet
Author: User

The next article, "Android development note-about the use of Asynctask", today, under the "heavy" in Android development, another asynchronous operation class handler.

Today I'm going to talk about some basic definitions and ways of using handler.

Or take a download image for example, first look at the example effect:

Well, let's take a look at the definition of handler:

The above is the official description of the Hanler class, roughly meaning: handler is mainly used for the processing of asynchronous messages: When a message is sent, first enters a message queue, the function that sends the message returns immediately, and the other part takes the message out of the message queue one at a time and then processes the message. That is, sending messages and receiving messages is not a synchronous process. This mechanism is often used to handle relatively long-time operations.

1. Handler is a mechanism for updating the UI, which takes time-consuming action in a child thread and then notifies the main thread to update the UI.

2, Handler is also a set of message processing mechanism, you can use it to send messages and processing messages.

About the use of handler:

Handler can distribute message objects and runnable objects into the main thread, and each instance of handler is bound to create his line approached (typically in the main thread)

Purpose: 1. Arrange for messages or runnable to be executed somewhere in a main thread 2, to schedule an action to execute in a different thread

Next talk about the basic use of handler, today is not too complicated, do not introduce the concept of threading and Message Queuing, and so the next article.

First, a textbook version of the handler use: (Comments very full)

1  Packagecom.example.handlertest_01;2 3 Importjava.io.IOException;4 5 Importorg.apache.http.HttpEntity;6 ImportOrg.apache.http.HttpResponse;7 Importorg.apache.http.client.ClientProtocolException;8 Importorg.apache.http.client.HttpClient;9 ImportOrg.apache.http.client.methods.HttpGet;Ten Importorg.apache.http.impl.client.DefaultHttpClient; One Importorg.apache.http.util.EntityUtils; A  - Importandroid.app.Activity; - ImportAndroid.app.ProgressDialog; the ImportAndroid.graphics.Bitmap; - Importandroid.graphics.BitmapFactory; - ImportAndroid.os.Bundle; - ImportAndroid.os.Handler; + ImportAndroid.os.Message; - ImportAndroid.view.View; + ImportAndroid.view.View.OnClickListener; A ImportAndroid.widget.Button; at ImportAndroid.widget.ImageView; -  -  Public classMainactivityextendsActivity { -     //declaring the controls used -     PrivateImageView ImageView; -     Privatebutton button; in     PrivateProgressDialog ProgressDialog; -     PrivateString Path = "Http://pic.baomihua.com/photos/201110/m_6_634545730007187500_16585344.jpg";//Download the resource address of the picture to      +     //Create a Handler object -     PrivateHandler Handler =NewHandler () { the          Public voidhandlemessage (android.os.Message msg) { *                 byte[] Data= (byte[]) Msg.obj;//Direct obj Object $Bitmap bitmap=bitmapfactory.decodebytearray (data, 0, data.length);Panax Notoginseng Progressdialog.dismiss (); - Imageview.setimagebitmap (bitmap); the         }; +     }; A  the @Override +     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); $ Setcontentview (r.layout.activity_main); $         //instantiate the control and set the relative properties -ImageView =(ImageView) Findviewbyid (R.id.imageview); -button =(Button) Findviewbyid (R.ID.BT); theprogressdialog=NewProgressDialog ( This); -Progressdialog.settitle ("Current Task");WuyiProgressdialog.setmessage ("Downloading pictures, please later ...")); the  -         //to monitor the button bindings WuButton.setonclicklistener (NewOnclicklistener () { -  About @Override $              Public voidOnClick (View v) { - progressdialog.show (); -                 NewThread (NewMyThread ()). Start ();//open a thread to execute the thread operation -             } A         }); +  the     } -  $     //inherit runnable interface, open new thread to access network resources the      Public classMyThreadImplementsRunnable { the @Override the          Public voidrun () { theHttpClient HttpClient =Newdefaulthttpclient (); -HttpGet HttpGet =Newhttpget (path); in             Try { theHttpResponse HttpResponse =Httpclient.execute (httpget); the                 if(Httpresponse.getstatusline (). Getstatuscode () = = 200) { About                     //Successful Access thehttpentity entity =httpresponse.getentity (); the                     //Apache provides a tool class Entityutils can easily convert a solid object into a byte-code array the                     byte[] data =Entityutils.tobytearray (entity); +                      -Message message = Handler.obtainmessage ();//Get Message Object theMessage.obj =data;BayiHandler.sendmessage (message);//sending messages with handler the                 } the}Catch(clientprotocolexception e) { - e.printstacktrace (); -}Catch(IOException e) { the e.printstacktrace (); the             } the         } the  -     } the  the}

The message here is the information mentioned above, there is a special need here is how to get a message instance object, the official does not advocate our direct new message (), it provides a lot of ways for us to get, specifically we can look at the API documentation:

Handler class:

Message class:

Why not go directly to the new message () object, see the source of the friends can find, in fact message.obtain () or handler.obtainmesssage () in the source we can find that Android provides us with a message pool, The size of this message pool is 10 and locked, when we call these methods, the system will first go to the message pool to fetch the message object, if it does not exist then it will go to new Message object.

The Message object, which, in addition to providing us with obj as a storage object, provides us with some other types of storage variables, such as:

These variables are the light-consuming variables that Android gives us, and we can use them, for example ARG1,ARG2 we can use to store simple integer variables, what we can use to hold the identifier of the message, and then Handmessgae (Message msg) Using a switch to determine what to do, and so on, the usage is consistent with the code given above.

For example:

1                     Message message=Message.obtain (handler); 2                     message.obj=data; 3                     Message.sendtotarget ();

The specific view of the API combined with the comments I just gave, in fact, are very simple, here is not an example.

Finally, let's look at the next few APIs that send messages:

Say a few easy to confuse, other people can try to play on their own

For example, sendmessagedelayed is a delay in sending back a message, followed by a long type of time, in milliseconds.

And Sendmessattime is sending messages on a regular basis, and time is passed by Uptimemills ().

These two sentences are equivalent and are delayed 1 seconds to join the message queue:

1 handler.sendmessageattime (msg, Systemclock.uptimemillis () +1000); 2 handler.sendmessagedelayed (msg, 1000);

Well, first introduce so much, and so on the other next article.

Android Development Notes--some summaries on handler (i)

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.