Handler,looper,message,messagequeue,handlerthread use summary (above)

Source: Internet
Author: User

In an Android program, there are often time-consuming operations such as downloads, network access, and so on, which can be time-consuming if placed on the main thread, which could cause an exception called the ANR exception (application not responding) to block the UI thread. This causes the program to become unresponsive. So we'll put some time-consuming operations on sub-threads, but because Android's UI is not thread-safe, it can cause thread-safety problems if multiple threads operate the UI at the same time, so Android has a rule that allows only the UI thread (the main thread) to do the UI. So how do we know when a child thread is done? For example, when a child thread downloads a good picture, notifies the main thread to update the view.

About message

a child thread needs to send a message to the main thread after the task is completed, which is a message An instance that defines three instance variables when you define a message

1. What type int message code, used to describe the message

2. obj user-specified object sent with message

3. Target handles the handler of the message


Ways to create a message

1, new one on the line

2. Using Handler.obtainmessage (...) This approach allows us to get a message instance from the public loop pool, and the efficiency will increase



So it would be better for us to use this method


MessageQueue Introduction

MessageQueue (Message Queuing) is used to store messages in FIFO mode,


Looper Introduction

Looper is called a message loop, and he constantly checks for new messages on MessageQueue, and then crawls the messages to complete the specified task. Each thread has and has only one Looper object, which is used to manage MessageQueue. The main thread also has looper, which is automatically created, and all the work of the main thread is done by his looper. There are two main methods of Looper

1. Looper.prepare is used to enable Looper

2, Looper.loop let Looper start to work, from the message queue to crawl processing messages



Handler Introduction

To process the message and the task specified by the message, you need to use handler, she can issue a new message to the MessageQueue, or read the message looper from MessageQueue. A handler is associated with only one looper, and a message is associated with only one target hander.

Handler how to send a message:


Looper gets the message, it is processed by the target of the message (that is, the target property of the message), and the message is generally in the handler.handlemessage (...). method is processed in the



Relationship Diagram




After a brief look at this knowledge, we wrote a small program that took advantage of handler and message. The application's main interface has only one imageview so the code is no longer given, the main function is to open a sub-thread to simulate the download picture, and then after the download is completed on the UI thread to update.


Main code

Declaration handler, an array of resource IDs for simulating downloaded images

<span style= "FONT-SIZE:18PX;" ><pre name= "code" class= "java" ><span style= "font-size:18px;" ><span style= "White-space:pre" ></span>private ImageView mimageview;//define a handlerprivate Handler mhandler;private int mindex;//The array that holds the photo resource ID int[] imageids = new int[] {r.drawable.pic1, R.DRAWABLE.PIC2,R.DRAWABLE.PIC3, R.drawable.pic4};</span></span>



How to simulate downloading pictures

<span style= "FONT-SIZE:18PX;" >//simulates the downloaded operation, randomly generates a number public int virtualdown () {Random ran = new Random (); int value = Ran.nextint (5); return value;} </span>



Use TimerTask to open a downloaded sub-thread, get to the message, and send

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >//opens a timertask simulated download of the child Thread New Timer (). Schedule (new TimerTask () {@Overridepublic void run () {Bundle bundle = new Bundle ( ); Bundle.putint ("Value", Virtualdown ());//gets to the message//Message msg = new Message (); Message msg = Mhandler.obtainmessage (); msg.what = 0x1233;msg.setdata (bundle);//Send a message and pass the generated number to the past Mhandler.sendmessage (msg);}}, 0, 2000);} </span></span>


Generate handle instances and process messages in Handlemessage

<span style= "FONT-SIZE:18PX;" ><span style= "White-space:pre" ></span>mhandler = new Handler () {@Override//method for handling messages public void Handlemessage (Message msg) {//What property is the identity of the message used to differentiate each message if (Msg.what = = 0x1233) {Mindex = Msg.getdata (). GetInt ("value");// Set the display of the picture, which is a switch (mindex) {case 0:mimageview.setimageresource (Imageids[0]) in the main thread, Break;case 1: Mimageview.setimageresource (Imageids[1]); Break;case 2:mimageview.setimageresource (imageIds[2]); Break;case 3: Mimageview.setimageresource (imageids[3]); break;}}}; </span>



Run the program we can see the main interface of the picture every two seconds will change once, of course, the picture is prepared beforehand, not download, over a period of time Bo Master will achieve real download.


Why didn't you see Looper in the program above? This is because the main thread automatically creates the Looper during the boot process. and the child thread by default is not with Looper, so we need to create a Looper, this time we need to use the above two methods, Looper.prepare and Looper.loop start Looper, the official API Demo Example:

Class Looperthread extends Thread {public Handler mhandler;public void Run () {looper.prepare (); mhandler = new Handler () {p ublic void Handlemessage (Message msg) {//Process incoming messages here}}; Looper.loop ();}}





Handler,looper,message,messagequeue,handlerthread use summary (above)

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.