1. comparison of advantages and disadvantages 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
LL process controllable
Disadvantages of using :
L becomes complex when multiple asynchronous operations are used and UI changes are required.
2) Handler the principle of asynchronous implementation and its application advantages and disadvantages
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)
2, Asynctask introduction
Android'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"?> <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent" > <TextViewAndroid:id= "@+id/textview01"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content" /> <ProgressBarAndroid:id= "@+id/progressbar02"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"style= "? Android:attr/progressbarstylehorizontal" /> <ButtonAndroid:id= "@+id/button03"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Update ProgressBar" /> </LinearLayout>
Mainactivity.java:
PackageVic.wong.main; Importandroid.app.Activity; ImportAndroid.os.Bundle; ImportAndroid.view.View; ImportAndroid.view.View.OnClickListener; ImportAndroid.widget.Button; ImportAndroid.widget.ProgressBar; ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {Privatebutton button; PrivateProgressBar ProgressBar; PrivateTextView TextView; @Override Public voidonCreate (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 (NewOnclicklistener () {@Override Public voidOnClick (View v) {progressbarasynctask Asynctask=NewProgressbarasynctask (TextView, ProgressBar); Asynctask.execute (1000); } }); } }
Netoperator.java:
PackageVic.wong.main; //Simulating network environments Public classNetoperator { Public voidoperator () {Try { //Sleep 1 secondsThread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }
Progressbarasynctask. Java:
PackageVic.wong.main; ImportAndroid.os.AsyncTask; ImportAndroid.widget.ProgressBar; ImportAndroid.widget.TextView; /*** After generating the object of the class and calling the Execute method, * The first execution is the Onproexecute method * followed by the Doinbackgroup method **/ Public classProgressbarasynctaskextendsAsynctask<integer, Integer, string> { PrivateTextView TextView; PrivateProgressBar ProgressBar; PublicProgressbarasynctask (TextView TextView, ProgressBar ProgressBar) {Super(); This. TextView =TextView; This. ProgressBar =ProgressBar; } /*** Here the integer parameter corresponds to the first parameter in Asynctask * Here the string return value corresponds to the third parameter of Asynctask * The method does not run in the UI thread, primarily for asynchronous operations, all in the method The space in the UI cannot be set and modified * but you can invoke the Publishprogress method to trigger Onprogressupdate to manipulate the UI*/@OverrideprotectedString doinbackground (Integer ... params) {netoperator Netoperator=NewNetoperator (); inti = 0; for(i = ten; I <=; i+=10) {netoperator.operator (); Publishprogress (i); } returni + params[0].intvalue () + ""; } /*** Here the string parameter corresponds to the third parameter in Asynctask (that is, the return value of the receiving Doinbackground) * runs after the execution of the Doinbackground method, and runs in the UI thread to the UI space To set*/@Overrideprotected voidOnPostExecute (String result) {Textview.settext ("Asynchronous Operation execution End" +result); } //This method runs in the UI thread and runs within the UI thread to set the UI space@Overrideprotected voidOnPreExecute () {Textview.settext ("Start executing asynchronous Threads"); } /*** The Intege parameter here corresponds to the second parameter in the Asynctask * in the Doinbackground method, each call to the Publishprogress method will trigger Onprogressupdate execution * Onprogressupdate is executed in the UI thread, all of which can manipulate the UI space*/@Overrideprotected voidonprogressupdate (Integer ... values) {intVlaue = Values[0]; Progressbar.setprogress (Vlaue); } }
Android (Java) Learning Note 149:android Asynctask Introduction