Handler and Asynctask in Android

Source: Internet
Author: User

1, Handler profile handler is responsible for sending and processing messages in Android. Its main uses:

1) Send a message on a schedule or execute a runnanble (using the Post method), similar to a timer;

2) messages sent from other threads are placed in the message queue to avoid thread collisions (common in updating the UI thread);

By default, Handler accepts a message loop instance under the current thread (using Handler (Looper Looper), Handler (Looper Looper, Handler.callback Callback) to specify a thread), At the same time a message queue (MessageQueue and Looper encapsulation) can be distributed and processed by multiple objects in the current thread (in the UI thread, the system already has an activity to handle, and you can take a few more handler to handle).

When instantiating handler, Looper can be any thread, as long as there are handler pointers, any thread can sendmessage.

Handler handling of message is not concurrent. A looper will read the next one only after processing one message, so the processing of the message is blocked (the Handlemessage () method should not have a time-consuming operation that can place time-consuming operations on other threads. Send a message after the operation (via the Sendmessges method), and then update the UI by Handlemessage ().

2, Asynctask Introduction

Asynctask, like handler, is used to handle time-consuming operations in the UI thread, and Asynctask has some of the following features:

(1) Asynctask is an abstract class that defines three generic type Params,progress,result. The Params is the input parameter that the task executes, such as the percentage of the Url;progress background task execution of the HTTP request, and the result that results in the background execution of the task, such as String.

(2) We will implement some methods, mainly such as four: OnPreExecute (), Doinbackground (Params ...), Onprogressupdate (Progress ...), OnPostExecute (Result). From these names we can know that the OnPreExecute () method mainly performs some preparatory work before the start; Doinbackground (Params ...) The method is called in the background and the usual time-consuming operations are performed here; Onprogressupdate (Progress ...) The main method is to display the update of the progress bar, mainly to show the current situation of the user, the OnPostExecute (result) method will get the result of the call.


3. Difference

(1) When using handler message processing, thread processing is used at the same time, and Asynctask itself is a threading mechanism.

(2) Asynctask can only be called once, cannot be called repeatedly, otherwise an exception will occur, and the handler processing mechanism can use multiple threads, as long as a different return message ID value can be specified.


4. Handler instances

/** Handler Message processing mechanism */private Handler Handler = new Handler () {public void Handlemessage (android.os.Message msg) {switch (ms G.what) {case Constantvalues.get_net_succeed:break;case constantvalues.get_net_failed://get network failure break;case Constantvalues.del_result_succeed:break;case constantvalues.del_result_failed:break;default:break;}};
/** * Construction method using Get Commit *  * @param handler *            Message Object * @param URL *            request URL address */public Httpgetthread (handler handler, S Tring URL) {this.handler = Handler;this.url = URL;} @Overridepublic void Run () {//Gets our callback main UI messagemessage msg = Handler.obtainmessage (); try {String result = Httprequestuti Ls.doget (URL); msg.what = Constantvalues.get_net_succeed;msg.obj = result;} catch (Clientprotocolexception e) {msg.what = 404;} catch (IOException e) {msg.what = 100;} Send Message delivery data to the main UI handler.sendmessage (msg);}

5. Examples of Asynctask

Private class Getdatatask extends Asynctask<void, Void, string[]> {@Overrideprotected string[] Doinbackground ( Void ... params) {//simulates a background job.try {thread.sleep (4000);} catch (Interruptedexception e) {}return mstrings; } @Overrideprotected void OnPostExecute (string[] result) {Mlistitems.addfirst ("Added after Refresh ..."); Madapter.notifydatasetchanged ();//Call Onrefreshcomplete If the list has been Refreshed.mPullRefreshListView.onRefreshComplete (); Super.onpostexecute (result);}}

6. Summary

In the asynctask processing mechanism, there is no need to use complex thread invocation and return operations, and if we are dealing with a single network request, we can use this class directly to implement some of these methods. Handler+thread's processing mechanism, which needs to define its own threads to perform operations, also needs to handle the returned results using handler, which is relatively suitable for customization in complex network requests.



Handler and Asynctask in Android

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.