Android: Application of asynchronous Processing Handler+thread (i)

Source: Internet
Author: User

Objective

As I've heard a long time ago, every Android application runs in a separate Dalvik virtual machine process, and each virtual machine runs a main thread of the UI at startup, And why is it called the main thread of the UI instead of the AI main thread or the BI main thread? Because it handles all UI-related events, because the Android system uses a UI single-threaded model, it can only be UI manipulated by the UI main thread, and if the child thread is crowds aware to help the UI main thread update the UI interface, I'm sorry. The ~android system will give an error. The vulgar point is: we can only use the UI thread to ravage the UI interface, but other threads will be accused of GONGSUI female dry drops.

So here's the problem! In view of the recent excavator so fire, I am also embarrassed to continue to ask this question ... Yes, yes. Time-consuming operations such as network operations are like excavators, and we need time to dig a big hole in the same way as the excavator when we download the file. When the excavator driver digs a big hole to find the boss feedback work is done, we download the good one file naturally to immediately tell the screen before the bitter waiting users, Who knows how anxious they want to see **.avi, but when you dig a hole, you ask your boss to see you next to you? Boss minutes for tens of millions of up and down things busy ~ so the same, for the network operation, we certainly can not do the network operation in the main thread of the UI, because this will block the main thread caused the interface card dead, also cause the ANR (application unresponsive). We should put the time-consuming operations such as file downloads, file reads, and so on into sub-threads, and then notify the UI to respond when the child thread time-consuming operation completes.

Do not take time-consuming actions in the main thread of the UI

If you are not superstitious be sure to download the files, load the large files, and so on in the UI main thread for time-consuming operations. The following code:

PrivateButton btn;//The OnCreate-like life cycle approach is to allow in the main thread of the UI@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);          Setcontentview (R.layout.activity_main); BTN=(Button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {downLoad ();//Call the download function for the main thread of the UI      }} ); Private voiddownLoad () {Try{Thread.Sleep (10000);//hibernation 10 seconds, analog network file download time-consuming Operation}Catch(interruptedexception e) {e.printstacktrace (); }}

You will find the interface card master for 10 seconds: ( the button that simulates the download operation is dark, indicating that the button has been pressed )

If at this time you can not control the hand, although a few points under the interface, nothing ~androi system will immediately send you a copy of the ANR gift Oh, and do not have 998 dollars yes!

Summary one: do not take time-consuming actions in the main thread of the UI, you may question what is the UI main thread, the main thread of the UI is the activity, service, etc. inside the life cycle method, so do not in the life cycle method such as OnCreate () To download these big events. For time-consuming operations, we should create a new sub-thread and give it to him, but be aware of it.

Do not update the UI interface in a child thread

Now that we say the download file is going to be in a sub-thread, we'll just create a new sub-thread to put the download into the inside, and the code is as follows:

protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);          Setcontentview (R.layout.activity_main); BTN=(Button) Findviewbyid (R.ID.BTN); Text=(TextView) Findviewbyid (R.id.text); Btn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {NewThread () {@Override Public voidrun () {//downloading operations in child threads            Try{Thread.Sleep (10000);//sleeps 10 seconds, simulates time-consuming operation}Catch(interruptedexception e) {e.printstacktrace (); } text.settext ("Download Complete");//Set TextView, notify UI interface Download complete}}.start (); }});

After 10 seconds, do you think the "Download complete" will be displayed perfectly in the UI interface? Generally, the appearance of this is in line with the Androi system's consistent style

and the error in log is as follows

Little brother English is actually very waste wood, but vaguely someone told me: this is not called only in the main thread to update the UI? Do not believe, Jinshan translation go ah ....

Summary one: do not update the UI interface in the sub-thread, this will cause the Android system error, application crashes exit. UI interface when the single-threaded mode, we can only through the UI in the main thread of the UI to update the relevant, do not cross-line, you have to remember that the ~ui interface is the main thread of the wife of the UI, you these sub-threads who do not want to move!

Using Thread+handler for asynchronous processing

So here's the problem, now that we need to do time-consuming operations (such as downloading a file), we can't do it on the main thread, and we need to notify the user in the UI that we're done with our work. This seems to be a tricky hot potato ah, fortunately, Google has provided us with a rescue in distress in the handler, a can let the main thread to listen to Cheng send messages to the east, as for the handler principle I will be in the following article in detail, Now we just need to understand the usage of handler first.

PrivateButton btn;PrivateTextView text; PrivateHandler Handler =NewHandler () {Private intProcess = 0; @Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Case0://more detailed download ProgressProcess + = 1; Text.settext ("Download" + process + "%");//updating the UI interface in the main thread         Break;  Case1://Prompt Download CompleteText.settext ("Download Complete");//updating the UI interface in the main thread         Break; default: Break; }}};//The OnCreate-like life cycle approach is to allow in the main thread of the UI@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);          Setcontentview (R.layout.activity_main); BTN=(Button) Findviewbyid (R.ID.BTN); Text=(TextView) Findviewbyid (R.id.text); Btn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {NewThread () {@Override Public voidrun () {//downloading operations in child threads           for(inti = 0; I < 100; i++) {Try{Thread.Sleep (200);//sleeps 0.2 seconds, simulates time-consuming operation}Catch(interruptedexception e) {e.printstacktrace (); } handler.sendemptymessage (0);//send message to handler, notify download Progress          } handler.sendemptymessage (1);//send disappears to handler, notify main thread download complete          }}.start (); }});

Here to explain how handler is used:

1. In order to not block the main thread, we will download the task through the child thread to execute.

NewThread () {@Override Public voidrun () {//downloading operations in child threads       for(inti = 0; I < 100; i++) {Try{Thread.Sleep (200);//sleeps 0.2 seconds, simulates time-consuming operation}Catch(interruptedexception e) {e.printstacktrace (); } handler.sendemptymessage (0);//send message to handler, notify download Progress      } handler.sendemptymessage (1);//send disappears to handler, notify main thread download complete    }}.start ();

2, when the child thread needs to communicate with the main thread, that is, when the child thread to the main thread of the UI said: Pro, I downloaded the file to 80% or I have already downloaded the file completed! Execute this Code

Handler.sendemptymessage (1); // send disappears to handler, notify main thread download complete

3, when the empty message is sent, the handler will receive a message from the child thread, triggering the callback method Handlermessage (), we are here to update the UI interface, this callback method is run on the main thread of the UI

@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Case0://more detailed download ProgressProcess + = 1; Text.settext ("Download" + process + "%");//updating the UI interface in the main thread       Break;  Case1://Prompt Download CompleteText.settext ("Download Complete");//updating the UI interface in the main thread       Break; default: Break; }}

4, finally, the UI interface update success! (Picture, I'm not here ....) )

Summary one: for more time-consuming tasks, we generally need to put in a child thread execution; When a child thread updates the UI interface, the child thread can notify the main thread update via handler, typically by sending a message to trigger Handlermessage () This callback method to perform the update of the UI interface.

Further brief de operations: Handler.post method and View.post method

But if you think it's more troublesome to rewrite handlermessage every time, we can use a more abbreviated approach to our needs, that is, using the Post method in handler. The code is as follows

NewThread () {@Override Public voidrun () {//downloading operations in child threads      Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } handler.post (NewRunnable () {@Override Public voidrun () {Text.settext ("Download Complete"); }});//send disappears to handler, notify main thread download complete    }}.start ();

This way we can not rewrite the Handlermessage () method, suitable for the sub-thread and the main thread for a relatively single communication. But here we want to emphasize the point is that therunnable in the post is still in the main thread of the UI running, and will not open the threads to run , do not in the runnable run () in the time-consuming task, or when the ANR will not find me oh.

If you don't even want to do handler sometimes, you can write the code.

We only need to replace the handler with the view component for post, and the update task will naturally load into the main thread of the UI for processing.

Text.post (new  Runnable () {@Override  publicvoid  run () {text.settext ("Download  Completed "); }}); // send disappears to handler, notify main thread download complete

As for the handler mechanism and the principles of these two posts, I will present a presentation in a later blog post that provides only one way to use it.

Finally finished to sleep, how did not applause it?? Eggs, beer bottles hit a few come up ~ ~ ~ haha

Enjoy wind chimes
Source: http://www.cnblogs.com/net168/
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph statement, and in the article page obvious location to the original connection, or next time not to you reproduced.

Android: Application of asynchronous Processing Handler+thread (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.