Comparison of the pros and cons of Asynctask and handler (update thread's summary of issues

Source: Internet
Author: User
Tags message queue

Comparison of advantages and disadvantages of Asynctask and handler:

http://blog.csdn.net/onlyonecoder/article/details/8484200

Handler primarily accepts data sent by a child thread, and updates the UI with this data in conjunction with the main thread. When the application starts, Android first opens a main thread, the main thread is the UI control in the management interface, the event is distributed, the update UI can only be updated in the main thread, and the operations in the child threads are dangerous. This time, handler need to come out to solve this complex problem. Since handler runs in the mainline approached (UI thread), it and the child thread can pass the data through the Message object, at this time, the handler undertakes to accept the child thread passed (the child thread passes with the Sedmessage () method) the Message object ( Contains data), put these messages into the main thread queue, with the main thread to update the UI. In summary: The data is simple to use asynctask: the implementation of simple code, data volume and complex use of handler+thread: compared to Asynctask to better use of system resources and efficient

The following turns from:

Http://www.cnblogs.com/net168/p/4075126.html

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:

The method of life cycle such as private Button btn;//oncreate is to allow @overrideprotected void OnCreate (Bundle savedinstancestate) in the main thread of the UI {  Super.oncreate (savedinstancestate);  Setcontentview (r.layout.activity_main);        BTN = (Button) Findviewbyid (R.ID.BTN);        Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {downLoad ();//download letter calling the main thread of the UI Number}});    private void DownLoad () {try {thread.sleep (10000);//hibernate 10 seconds, analog network file download time-consuming operation} catch (Interruptedexception e) {E.print  StackTrace (); }}

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 you can not hold the hand at this time, although a few points under the interface, nothing ~androi system will immediately send you a copy of the ANR gift OH

Summary one: Do not take time-consuming actions in the main thread of the UI, you may wonder what the UI main thread is, the main thread of the UI is the life cycle method inside the activity, service, etc., so do not download these events in the life cycle methods such as OnCreate (). 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 and put the download in it.

protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);  Setcontentview (r.layout.activity_main);        BTN = (Button) Findviewbyid (R.ID.BTN);  Text = (TextView) Findviewbyid (r.id.text);        Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {new Thread () {@Ov          Erride public void Run () {//download operation in child thread try {thread.sleep (10000);//hibernate 10 seconds, simulate time-consuming operation          } catch (Interruptedexception e) {e.printstacktrace ();    } text.settext ("Download Complete");//Set TextView to notify UI interface Download complete}}.start (); }  });}

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.

Private Button btn;private TextView text;  Private Handler Handler = new Handler () {private int process = 0;      @Override public void Handlemessage (Message msg) {switch (msg.what) {case 0://finer download progress process + = 1;    Text.settext ("Download" + process + "%");//Update UI interface break in the main thread;    Case 1://Prompt Download complete text.settext ("Download Complete");//Update UI interface break in main thread;    Default:break; The}};//oncreate-like life cycle approach is to allow @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate in the main thread of the UI (  Savedinstancestate);          Setcontentview (R.layout.activity_main);  BTN = (Button) Findviewbyid (R.ID.BTN);          Text = (TextView) Findviewbyid (R.id.text);      Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {new Thread () {@Override public void Run () {//download operation in child thread for (int i = 0; i < i++) {try {Thread.slee P (200);//hibernate 0.2 seconds, simulate 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 (); }  });}

 Summary one: For more time-consuming tasks, we generally need to be executed in a child thread, and when the child thread updates the UI interface, the child thread can notify the main thread update via handler, typically by sending a message to trigger the Handlermessage () callback method to perform an 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

New Thread () {@Override public void run () {//download operation in a child thread try {thread.sleep (1000);    } catch (Interruptedexception e) {e.printstacktrace ();      } handler.post (New Runnable () {@Override public void run () {text.settext ("Download Complete"); });//Send disappears to handler, notify main thread to 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 the runnable 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 public void run () {text.settext ("Download Complete"); });//Send disappears to handler, notify main thread download complete

View.post Learning

Runnable does not necessarily open a new thread, such as the following method of invocation is run in the main thread of the UI:

    Handler mhandler=new Handler ();      Mhandler.post (New Runnable () {         @Override public void Run ()         {//TODO auto-generated method stub          }      });

The official explanation for this method is as follows: "The runnable would be run on the user interface thread. ”

Boolean android.view.View. Post (Runnable action)

Causes the Runnable to is added to the message queue. The runnable'll be run on the user interface thread.

Parameters:

Action the Runnable that would be executed.

Returns:

Returns true if the Runnable is successfully placed in to the message queue. Returns false on failure, usually because the Looper processing the message queue is exiting.

We can pass the Runnable object (usually the subclass of runnable) by calling Handler's post method, and handler will invoke the Looper run method in runnable.

Runnable is an interface, not a thread, and a generic thread implements Runnable. So if we use an anonymous inner class that is running on the main thread of the UI, if we use the threading class that implements the Runnable interface, it is run on the corresponding thread.

Specifically, this function works as follows:

View.post (Runnable) method. In the post (Runnable action) method, view obtains the handler of the current thread (that is, the UI thread) and then posts the action object into the handler. In handler, it wraps the action object passed in as a message (the callback of the message is the action) and then puts it into the message loop of the UI thread. When handler processes the message again, there is a branch (the one that is not explained) that is set for it to call the runnable run method directly. At this point, it has been routed to the UI thread, so we can update the UI with no worries.

As seen earlier in the code, we here message callback for an anonymous inner class of runnable

In this case, do not make complex computational logic because it is not used in a new thread.

Comparison of the pros and cons of Asynctask and handler (update thread's summary of issues

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.