Asynctask, Handlerthread, Intentservice, and thread pools

Source: Internet
Author: User
Tags message queue

Asynctask

Asynctask is a lightweight asynchronous task class that can perform background tasks in a thread pool, and then pass the progress of execution and the final result to the main thread for updating the UI.

You can directly inherit Asynctask, implement asynchronous operations in a class, and provide interface feedback about the current level of asynchronous execution (UI Progress updates can be implemented through an interface), and finally feedback the execution results to the UI main thread.

Asynctask is not suitable for particularly time-consuming background tasks, and it is recommended to use thread pooling for particularly time-consuming tasks.

Asynctask and handler comparison:

1) Advantages of async use:

L Simple, fast

II Process controllable

Disadvantages of using :

L becomes complex when multiple asynchronous operations are used and UI changes are required.

2) The principle of handler asynchronous implementation and the advantages and disadvantages of its application

When Handler is implemented asynchronously, it involves Handler, Looper, Message,thread four objects, the process of implementing asynchronous is the main thread starting thread (child thread) àthread (child thread)

Run and generate Message-àlooper get a message and pass it to handleràhandler one by one to get the message in Looper and make UI changes.

Advantages of Use:

L Clear structure, clear function definition

LI for multiple background tasks, simple, clear

Disadvantages of using:

L in a single background asynchronous processing, appear too much code, the structure is too complex (relativity)

Android's asynctask is more lightweight than handler and is suitable for simple asynchronous processing.

Asynctask defines three types of generic type params,progress and result.

    • The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request.
    • Progress the percentage of background task execution.
    • Result background performs the final return of the task, such as String.

Students who have used Asynctask know that an asynchronous load of data must be overridden by the following two methods:

    • Doinbackground (Params ...) is performed in the background, and more time-consuming operations can be placed here. Note that it is not possible to manipulate the UI directly. This method is performed on a background thread, and it usually takes a long time to complete the task's main work. You can call Publicprogress (Progress ...) during execution. To update the progress of the task.
    • OnPostExecute (Result) is equivalent to the way handler handles the UI, where it is possible to use the resulting processing action UI in Doinbackground. This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method

You also have to rewrite these three methods, if necessary, but not necessarily:

    • Onprogressupdate (Progress ...) You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.
    • OnPreExecute () Here is the interface when the end user calls Excute, and the progress dialog can be displayed here before the task executes before calling this method.
    • Oncancelled () The action to be made when the user calls Cancel

Using the Asynctask class, here are a few guidelines to follow:

    • The instance of the task must be created in the UI thread;
    • The Execute method must be called in the UI thread;
    • Do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods;
    • The task can only be executed once, otherwise the exception will occur when multiple calls are made;

Handlerthread

Handlerthread is actually a thread, it can use handler thread, its implementation is actually very simple is in the Run method through Looper.prepare () to create message queue, and Looper.loop to turn on the message loop, so that in actual use

Allows you to create a handler in Handlerthread.

Private voidinit4 () {//Create a thread, thread name: Handler-threadMyhandlerthread =NewHandlerthread ("Handler-thread") ; //Open a threadMyhandlerthread.start (); //create a handler object in this threadLOG.D (TAG, "INIT4:" +Thread.CurrentThread (). GetId ()); Handler3=NewHandler (Myhandlerthread.getlooper ()) {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); //This method is run in the Handler-thread thread and can take a time-consuming actionLOG.D (TAG, "message:" + Msg.what + "Thread:" +Thread.CurrentThread (). GetId ());        }        }; //send a message to handler on the main threadHandler3.sendemptymessage (1 ) ; NewThread (NewRunnable () {@Override Public voidrun () {LOG.D (TAG,"New runnable" +Thread.CurrentThread (). GetId ()); //send data to handler on a child threadHandler3.sendemptymessage (2 ) ;    }}). Start (); }
View Code

    • In the code above, a new thread is opened through Handlerthread, and the loop in the main thread is processed to the child thread, reducing the pressure on the main thread.

Make the main interface more fluid. It has its own MessageQueue that does not interfere with Message Queuing in the main thread.

    • If this handlerthread is commented out in the program, the program will make an error because it will send a message to the main thread to process it in the main thread.
    • In Handlerthread internal messages, the processing task is serially executed, and the messages are sequentially arrived. When a task in the queue takes a long time to execute, subsequent tasks are deferred.
Thread pool:

Asynctask, Handlerthread, Intentservice, and thread pools

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.