Please respect other people's labor results, reproduced please specify the source: Asynchronous explanation of Android Development (ii) Asynctask
http://blog.csdn.net/fengyuzhengfan/article/details/40212745
I have described asynchronous operations through Thread+handler in the article "Thread+handler of asynchronous elaboration of Android development" (i). Interested friends can take a look.
Although Thread+handler can implement the UI for updating the main thread and implement Asynchrony, the Thread+handler pattern requires a new thread for each task, and a message is sent through the handler instance to the UI thread after the task is completed, updating the interface. , this way for the whole process of control is relatively fine, but there are shortcomings, such as code cumbersome, when multiple tasks are executed simultaneously, it is not easy to control the thread precisely.
Here's a look at Android in Asynctask Use of:
Asynctask Introduction:
starting with Android 1.5, the system introduces asynctask into the Android.os package. Asynctask, a lightweight asynchronous class provided by Android, 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 results of the execution to the UI main thread.
class overview:
The advent of Asynctask makes using the UI thread lightweight and simple. This class allows background operations to be performed and updates the results of the operation to the UI thread without the need to manipulate threads and handlers.
Asynctask is designed around threading and handler an auxiliary class and does not constitute a generic threading framework. Asynchronous tasks should preferably take short jobs. If you need to keep a thread running for a long time, you can replace it with various APIs such as Threadpoolexecutor and futuretask, such as the Java.util.concurrent package.
An asynchronous task is defined to run on a background thread and an operation to publish the results on the UI thread. Asynchronous tasks are defined as Params,Progress and Result 3 common types, and onpreexecute,doinbackground ,onprogressupdate and onpostexecute 4 steps.
definition of Asynctask
Asynctask defines three types of generics Params , Progress and the Result .
Public abstract class Asynctask<params, Progress, result>
The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request.
Progress The progress of the background task execution.
result background performs the final return of the task, such as String.
the main methods in Asynctask are:
OnPreExecute () , the method will be called by the UI thread before performing the actual background operation. You can do some preparatory work in the method, such as displaying a progress bar on the interface, or instantiating some controls, and this method can be used without implementation.
Doinbackground (Params ...) is executed immediately after the OnPreExecute method executes, and the method runs in the background thread. This will be the main responsibility for performing those very time-consuming background processing work. You can call the Publishprogress method to update the real-time task progress. The method is an abstract method that the subclass must implement.
onprogressupdate (Progress ...) , in publishprogress (Progress ...) When the method is called, the UI thread will invoke this method to show the progress of the task on the interface, for example, by displaying it through a progress bar.
OnPostExecute (Result) , after Doinbackground execution completes, the OnPostExecute method is called by the UI thread, and the results of the background are passed through the method to the UI thread and displayed to the user on the interface.
oncancelled (), called when the user cancels the thread operation. Called when oncancelled () is called in the main thread.
steps to use Asynctask
Asynctask allows you to perform asynchronous operations on your user interface. It performs time-consuming operations on a child thread, and then publishes the execution results on the UI thread without requiring you to handle thread and handler.
to use Asynctask, you must inherit the Asynctask and implement the Doinbackground () callback method, Asynctask run in a thread pool in the background. To update your UI, you should implement the OnPostExecute () method, which gets the results from the doinbackground () method and runs in the UI Thread, so you can safely update your UI. You can call the Execute () method in the UI thread to start your task.
Use Asynctask the steps:
1) Create a class that inherits Asynctask
2) Implement the abstract method defined in Asynctask doinbackground (Params ...), and then rewrite it as needed for other methods.
3) call execute () to start the task.
See an example:
<string,integer, bitmap>//represents the argument from the call location//Integer: Indicates the progress of reading network data//The value returned from the network class Nettask extends asynctask< String, Integer, bitmap> {private String path; Private ImageView IV; Public Nettask (String path, ImageView iv) {this.path = path; THIS.IV = IV; }//main thread, feedback network access progress @Override protected void onprogressupdate (Integer ... values) {super.onprogressupdate (v Alues); LOG.I ("Netutil", "values=" + values[0]); }//main thread, execution of the child thread before execution @Override protected void OnPreExecute () {super.onpreexecute (); }//Child thread @Override protected Bitmap doinbackground (String ... params) {try {URL url = new URL (p ATH); HttpURLConnection conn = (httpurlconnection) URL. OpenConnection (); Set some connection properties Conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET");//POST//Set HTTP header information//conn.setrequestproperty ("Content-type", NewValue) IF (conn.getresponsecode () = =) {InputStream is = Conn.getinputstream (); Return Bitmapfactory.decodestream (IS); }} catch (Malformedurlexception e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); } return null; }//In the main thread, the network returns data when the @Override protected void OnPostExecute (Bitmap result) {Super.onpostexecute (result) is executed; if (result! = null) {Iv.setimagebitmap (result); } }}
Precautions :
To properly use the Asynctask class, here are a few guidelines to follow:
1) An instance of Asynctask must be created in the UI thread.
2) The Execute method must be called in the UI thread.
3) do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These methods need to be instantiated in the UI thread to invoke this asynctask.
4) The asynctask can only be executed once, otherwise an exception will occur when multiple calls are made.
5) The parameters of the Doinbackground method and the OnPostExecute must correspond, the two parameters are specified in the generic parameter list of the asynctask Declaration, and the first one is Doinbackground accepts the parameter, the second is the parameter that shows the progress, the third is the doinbackground return and the onpostexecute the parameters passed in.
advantages and disadvantages of Thread+handler mode and Asynctask:
Asynctask implementation of the principle and application of advantages and disadvantages:
Asynctask, a lightweight asynchronous class provided by Android, 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 via interfaces). The final feedback executes the result to the UI main thread.
Advantages of using :
1) simple , fast
2) process controllable
Disadvantages of using :
1) it becomes complex when multiple asynchronous operations are used and Ui changes are required .
Handler The principle of asynchronous implementation and the pros and cons of 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) running and generating message-looper getting Messa GE and pass it to Handlerhandler to get the message in Looper one by one and make UI changes.
Advantages of Use:
1) clear structure and clear function definition
2) for multiple background tasks, simple, clear
Disadvantages of using:
1) in a single background asynchronous processing, appear too much code, the structure is too complex (relativity)
finally need to explain Asynctask cannot completely replace threads, and logic that is more complex or needs to be executed repeatedly in the background may require Thread+handler to achieve it.
If you think this blog post is helpful to you, please give this blog a praise! You can also pay attention to Fengyuzhengfan's blog, watch more wonderful!http://blog.csdn.net/fengyuzhengfan/
Asynchronous explanation of Android Development (ii) Asynctask