Public classAsynctasktest extends activity{PrivateTextView Show; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Show=(TextView) Findviewbyid (r.id.show); } //Override this method to provide an event response method for the interface's buttons Public voidDownload (View source) throws Malformedurlexception {Downtask task=NewDowntask ( This); Task.execute (NewURL ("http://www.crazyit.org/ethos.php")); } classDowntask extends Asynctask<url, Integer, string> { //variable-length input parameters, corresponding to Asynctask.exucute ()ProgressDialog Pdialog; //defines the number of rows that the record has read intHasread =0; Context Mcontext; PublicDowntask (Context ctx) {Mcontext=CTX; } @OverrideprotectedString Doinbackground (URL ...params) {StringBuilder sb=NewStringBuilder (); Try{URLConnection conn=params[0].openconnection (); //Open the Conn connection corresponding to the input stream and wrap it into a bufferedreaderBufferedReader br =NewBufferedReader (NewInputStreamReader (Conn.getinputstream (),"Utf-8")); String Line=NULL; while(line = Br.readline ())! =NULL) {sb.append ( line+"\ n"); Hasread++; Publishprogress (Hasread); } returnsb.tostring (); } Catch(Exception e) {e.printstacktrace (); } return NULL; } @Overrideprotected voidOnPostExecute (String result) {//returns the contents of an HTML pageShow.settext (Result); Pdialog.dismiss (); } @Overrideprotected voidOnPreExecute () {Pdialog=NewProgressDialog (Mcontext); //setting the caption of a dialog boxPdialog.settitle ("The task is being executed"); //setting what the dialog box displaysPdialog.setmessage ("task is in progress, please wait ..."); //The Settings dialog box cannot be closed with the Cancel buttonPdialog.setcancelable (false); //set the maximum progress value for this progress barPdialog.setmax (202); //set the progress bar style of the dialog boxPdialog.setprogressstyle (progressdialog.style_horizontal); //sets whether the progress bar of the dialog box shows ProgressPdialog.setindeterminate (false); Pdialog.show (); } @Overrideprotected voidonprogressupdate (Integer ... values) {//Update ProgressShow.settext ("has read the ""+ values[0] +""All right!" "); Pdialog.setprogress (values[0]); } }}
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:
Android Asynchronous loading