Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/46952835
Comparison of Asynctask and handler
1) Asynctask implementation of the principle, and the advantages and disadvantages of the application
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 Use:
L Simple, fast
L 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
L Simple and clear for multiple background tasks
Disadvantages of using:
L in a single background asynchronous processing, appear too much code, the structure is too complex (relativity)
Asynctask IntroductionAndroid's Asynctask is more lightweight than handler and is suitable for simple asynchronous processing. The first thing to make clear is that Android has handler and Asynctask, both to not block the main thread (the UI thread), and that the UI update can only be done in the main thread, so asynchronous processing is unavoidable.
Android to reduce this development difficulty, provides the asynctask. Asynctask is a packaged background task class, as its name implies, an asynchronous task.
Asynctask directly inherits from the object class, where the position is android.os.AsyncTask. To work with Asynctask we are going to provide three generic parameters and overload several methods (at least one for overloading).
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;
An ultra-simple example of understanding Asynctask:
Main.xml
? xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:orientation=" vertical " android:layout_width=" fill_parent " android:layout_height=" Fill_parent " > <textview android:id=" @+id/textview01 " android:layout_width=" Fill_parent " android:layout_height= "wrap_content" /> <progressbar android:id= "@+id/progressbar02" android:layout_width= "fill_parent" android:layout_height= "wrap_content" style= "? android:attr/ Progressbarstylehorizontal " /> <button android:id=" @+id/button03 " android:layout_ Width= "Fill_parent" android:layout_height= "wrap_content" android:text= "update ProgressBar" /> </LinearLayout>
Mainactivity.java
Package vic.wong.main; Import android.app.Activity; Import Android.os.Bundle; Import Android.view.View; Import Android.view.View.OnClickListener; Import Android.widget.Button; Import Android.widget.ProgressBar; Import Android.widget.TextView; /** * @author Liuyazhuang */public class Mainactivity extends Activity {private Button B Utton; Private ProgressBar ProgressBar; Private TextView TextView; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Button = (button) Findviewbyid (R.ID.BUTTON03); ProgressBar = (ProgressBar) Findviewbyid (R.ID.PROGRESSBAR02); TextView = (TextView) Findviewbyid (R.ID.TEXTVIEW01); Button.setonclicklistener (New Onclicklistener () { @Override public void OnClick (View v) {progressbarasynctask asynctask = new Pr Ogressbarasynctask (TextView, ProgressBar); Asynctask.execute (1000); } }); } }
Netoperator.java
Package vic.wong.main; /** * Simulated network environment * @author Liuyazhuang * /public class Netoperator {public void operator () { try { c10/>//sleeps 1 seconds Thread.Sleep (+), } catch (Interruptedexception e) { //TODO auto-generated catch block< C14/>e.printstacktrace ();}}}
Progressbarasynctask. java
Package vic.wong.main; Import Android.os.AsyncTask; Import Android.widget.ProgressBar; Import Android.widget.TextView; /** * Generates the object of this class, and after calling the Execute method * First executes the Onproexecute method * Next executes the Doinbackgroup method * @author Liuyazhuang */public class Progressbarasynctask extends Asynctask<integer, Integer, string> {private Tex TView TextView; Private ProgressBar ProgressBar; Public Progressbarasynctask (TextView TextView, ProgressBar ProgressBar) {super (); This.textview = TextView; This.progressbar = ProgressBar; }/** * The integer parameter here corresponds to the first parameter in Asynctask * Here the string return value corresponds to the third parameter of Asynctask * This method does not run in the UI thread, primarily for asynchronous operations, where space in the UI cannot be set and modified in the method * but can be called by the Publishprogress method to trigger Onprogressupdate to manipulate the UI */@Override protected String doinbackground (Integer ... params) { Netoperator netoperator = new Netoperator (); int i = 0; for (i = ten; I <=; i+=10) {netoperator.operator (); Publishprogress (i); } return i + params[0].intvalue () + ""; }/** * Here the string parameter corresponds to the third parameter in Asynctask (that is, the return value of the receiving Doinbackground) * on the doinbackground side After the execution of the law is running, and running in the UI thread, you can set the UI space */@Override protected void OnPostExecute (String result) { Textview.settext ("Asynchronous Operation execution End" + result); }//The method runs in the UI thread and runs within the UI thread to set the UI space @Override protected void OnPreExecute () { Textview.settext ("Start executing asynchronous Threads"); }/** * The Intege parameter here corresponds to the second parameter in the Asynctask * in the Doinbackground method, each time the Publishprogress party is called Law will trigger onprogressupdate execution * Onprogressupdate is executed in the UI thread, all can operate on UI space */@Override Protected void Onprogressupdate (Integer ... values) {int vlaue = values[0]; Progressbar.setprogress (Vlaue); } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android--asynctask and handler comparison