Android Development notes-Summary of Handler (I) and Android handler

Source: Internet
Author: User

Android Development notes-Summary of Handler (I) and Android handler

Next, I wrote "android Development notes-about the use of AsyncTask". Today, I am going to talk about another Asynchronous Operation Handler in Android development.

Today, I plan to explain some basic definitions and usage of Handler.

Take a download image as an example. Let's take a look at the instance effect first:

 

Now let's take a look at the definition of Handler:

The above is an official description of the Hanler class, which roughly means: Handler is mainly used for processing asynchronous messages: After a message is sent, it first enters a message queue, the function that sends a message returns immediately. The other part extracts the message one by one in the message queue and processes the message. That is, sending and receiving messages are not synchronous processing. This mechanism is usually used to process operations that are relatively time-consuming.

1. Handler is a set of UI update mechanisms that perform time-consuming operations in sub-threads and then notify the main thread to update the UI.

2. Handler is also a set of message processing mechanisms that can be used to send and process messages.

 

Handler usage:

Handler can distribute the Message object and Runnable object to the main thread. Each Handler instance is bound to the thread where the Handler is created (usually located in the main thread)

Purpose: 1. Schedule a message or Runnable to run somewhere in a main thread. 2. Schedule an action to run in different threads.

 

Next, let's talk about the basic usage of Handler. Today, we will not talk about the complexity or introduce the concept of thread and message queue. Let's talk about it in the next article.

Let's first use a textbook Handler: (the comment is full)

1 package com. example. handlertest_01; 2 3 import java. io. IOException; 4 5 import org. apache. http. httpEntity; 6 import org. apache. http. httpResponse; 7 import org. apache. http. client. clientProtocolException; 8 import org. apache. http. client. httpClient; 9 import org. apache. http. client. methods. httpGet; 10 import org. apache. http. impl. client. defaultHttpClient; 11 import org. apache. http. util. entityUtils; 12 13 import android. app. activity; 14 import android. app. progressDialog; 15 import android. graphics. bitmap; 16 import android. graphics. bitmapFactory; 17 import android. OS. bundle; 18 import android. OS. handler; 19 import android. OS. message; 20 import android. view. view; 21 import android. view. view. onClickListener; 22 import android. widget. button; 23 import android. widget. imageView; 24 25 public class MainActivity extends Activity {26 // declare the control 27 private ImageView imageView; 28 private Button button; 29 private ProgressDialog progre; 30 private String path = "http://pic.baomihua.com/photos/201110/m_6_634545730007187500_16585344.jpg"; // download image resource address 31 32 // create a Handler object 33 private Handler handler = new Handler () {34 public void handleMessage (android. OS. message msg) {35 byte [] data = (byte []) msg. obj; // directly obj object 36 Bitmap bitmap = BitmapFactory. decodeByteArray (data, 0, data. length); 37 progressDialog. dismiss (); 38 imageView. setImageBitmap (bitmap); 39}; 40}; 41 42 @ Override43 protected void onCreate (Bundle savedInstanceState) {44 super. onCreate (savedInstanceState); 45 setContentView (R. layout. activity_main); 46 // instantiate the control and set the corresponding property 47 imageView = (ImageView) findViewById (R. id. imageView); 48 button = (Button) findViewById (R. id. bt); 49 progressDialog = new ProgressDialog (this); 50 progressDialog. setTitle ("current task"); 51 progressDialog. setMessage ("the image is being downloaded. Please wait .. "); 52 53 // bind the listener to the button 54 button. setOnClickListener (new OnClickListener () {55 56 @ Override57 public void onClick (View v) {58 progressDialog. show (); 59 new Thread (new MyThread ()). start (); // open up a thread and execute this thread 60} 61}); 62 63} 64 65 // inherit the Runnable interface, open up a new thread to access network resources 66 public class MyThread implements Runnable {67 @ Override68 public void run () {69 HttpClient httpClient = new DefaultHttpClient (); 70 HttpGet httpGet = new HttpGet (path); 71 try {72 HttpResponse httpResponse = httpClient.exe cute (httpGet); 73 if (httpResponse. getStatusLine (). getStatusCode () = 200) {74 // access successful 75 HttpEntity entity = httpResponse. getEntity (); 76 // The tool EntityUtils provided by Apache can easily convert an object to a bytecode array 77 byte [] data = EntityUtils. toByteArray (entity); 78 79 Message message = handler. obtainMessage (); // get the Message object 80 message. obj = data; 81 handler. sendMessage (message); // use handler to send the message 82} 83} catch (ClientProtocolException e) {84 e. printStackTrace (); 85} catch (IOException e) {86 e. printStackTrace (); 87} 88} 89 90} 91 92}

 

Here, the Message is the Message mentioned above. Here, we have a special need for how to obtain an instance object of Message. The official government does not advocate direct new Message (), it provides many methods for us to obtain them. For details, refer to the API documentation:

Handler class:

Message class:

Why don't you go to the new Message () object directly? If you have checked the source code, you can find that the Message is actually used. obtain () or Handler. obtainMesssage () in the source code, we can find that Android provides us with a message pool with a size of 50 and locks. When we call these methods, the system first retrieves the Message object from the Message pool. If the object does not exist, the system generates a new Message object.

Message source code:

 

 

Here is another example of the above API:

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

It's easy. You just need to follow the API specifications.

 

 

Message object. In addition to providing us with the obj storage object, it also provides us with some other types of storage variables, such:

These variables are the light-consumption variables provided by Android. We can use them. For example, arg1 and arg2 can be used to store simple integer variables, what can be used to store the Message identifier, and then use a switch in handMessgae (Message msg) to determine the operations to be executed. The usage is consistent with the code given above.

For details, refer to the API and the comments I just gave. They are actually very simple. Here we will not illustrate them one by one.

 

Finally, let's take a look at several APIs for sending messages:

Let's talk about some confusing things. Others can try it on their own.

For example, sendMessageDelayed delays sending back a message, followed by a long time, in milliseconds.

In addition, sendMessAtTime is used to send messages at a scheduled time, which is transmitted by uptimeMills ().

The two statements are equivalent. messages are added to the queue after 1 second delay:

1 handler.sendMessageAtTime(msg, SystemClock.uptimeMillis()+1000);2 handler.sendMessageDelayed(msg, 1000);

 

Well, let's introduce it so much. Let's wait for the next article.

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.