Asynchronous Task Asynctask
Asynctask is primarily used to update the UI thread, and more time-consuming operations can be used in asynctask.
Asynctask is an abstract class that needs to inherit the class and then invoke the Execute () method. Note that inheritance requires the setting of three generic params,progress and result types, such as asynctask<void,inetger,void>:
- The params refers to the type of arguments passed in when the Execute () method is called and the parameter type of Doinbackgound ().
- Progress refers to the type of arguments passed when the progress is updated, that is, the parameter types of publishprogress () and onprogressupdate ()
- Result refers to the return value type of Doinbackground ()
- < Span style= "font-family: ' Times New Roman '; font-size:16px; Color:rgb (51,51,51) ">doinbackgound () This method is inherited Asynctask must be implemented, running in the background, the time-consuming operation can be done here
- publishprogress () Update Progress, Pass the Progress parameter (in the UI master process) to Onprogressupdate ()
- onprogressupdate () in Publishprogress () call is finished, update progress
The three types of asynchronous tasks that are used:
Params , the type parameter that is sent to the task is executed.
- Progress The type of progressive unit period published in the background calculation.
- result, the type calculation of the results of the background.
Use Asynctask as follows three steps:
1. Create the Asynctask class and specify the type for the three generic parameters. If a generic parameter does not require a specified type, it can be specified as void
2, according to the need to implement Asynctask the following methods:
(1) OnPreExecute (): This method is called before performing a background time-consuming operation Doinbackground () method. Typically, this method is used to perform some initialization work, such as displaying a progress bar on the interface.
(2) Doinbackground (Params ...): Overriding this method is a time-consuming task that the background thread is about to complete, and the UI cannot be modified in the method.
(3) Onprogressupdate (progress...values): After the Doinbackground () method calls the Publishprogress () method to update the execution progress of the task, the method is triggered and is often used to update the progress bar.
(4) OnPostExecute (result result): When Doinbackground completes, the system automatically calls the OnPostExecute () method, passes the return value of the Oinbackground () method to the method, and updates the UI. Displays the results.
3. Invoke instance execute (params...params) of the Asynctask subclass to start the time-consuming task
The following rules must be followed when using Asynctask:
- The Asynctask Exetue () method must be created in the UI thread.
- An instance of Asynctask must be called in the UI thread
- Asynctask Onperexecute (), onpostexecute (result result), Doinbackground (Params ...). Params), Onprogressupdate (Progress...values) method, should not have the programmer code called, but there is the Android system responsible for calling.
- Each asynctask can only be executed once, and multiple calls will throw an exception.
Example: The following is an example of the use of Android Asynctask, which is performed in the background with a progress bar.
Package Com.example.asynctestdemo;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.httpstatus;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Android.app.activity;import Android.os.AsyncTask;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;public class Mainactivity extends Activity {private Button Bt_execute;private button bt_cancel;private ProgressBar progressbar;private TextView TextView; MyTask mytask;protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Bt_execute = (Button) Findviewbyid (r.id.bt_execute); bt_cancel = (Button) Findviewbyid (r.id.bt_cancel);p Rogressbar = (progressBar) Findviewbyid (R.id.progressbar ); TextView = (TextView) Findviewbyid (R.id.text_view); Bt_execute.setonclicklistener (new Onclicklistener () {public void OnClick (View v) {//Instantiate asynchronous Task MyTask class MyTask = new MyTask (); Mytask.execute ("http://www.baidu.com");}}); Bt_cancel.setonclicklistener (New Onclicklistener () {public void OnClick (View v) {Mytask.cancel (true);}}); Class MyTask extends Asynctask<string, Integer, string> {//OnPreExecute () method is used to do some UI action before performing a background task protected void OnPreExecute () {textview.settext ("Loading ...");} The Doinbackground () method internally performs a background time-consuming task operation, but is not unable to modify the uiprotected String doinbackground (String ... params) {try {HttpClient) within this method Client = new Defaulthttpclient (); HttpGet get = new HttpGet (params[0]); HttpResponse response = Client.execute (GET), if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) { httpentity entity = response.getentity (); InputStream is = Entity.getcontent (); Long total = entity. Getcontentlength (); SYSTEM.OUT.PRINTLN (total); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); byte[] buf = new Byte[1024];int count = 0;int length = -1;while ( (length = Is.read (BUF))! =-1) {baos.write (buf, 0, length); count+=length;//calls the Publishprogress () method to advertise the progress, The last Onprogressupdata method will be executed publishprogress ((int) (count/length));//For a more pronounced effect, each pause 0.5sthread.sleep (500);} return new String (Baos.tobytearray (), "Utf-8");}} catch (Clientprotocolexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} catch ( Interruptedexception e) {e.printstacktrace ();} return null;} Onprogressupdata method for updating progress information, such as executing a progress bar program protected void Onprogressupdate (Integer ... values) {progressbar.setprogress (Values[0]); Textview.settext ("Loading ..." + values[0]); The OnPostExecute method, used to update the UI after performing a background task, displays the result protected void OnPostExecute (String result) {Textview.settext (result);} Oncacelled method, used to change uiprotected void oncancelled () {Textview.settext ("cancelled") when canceling a task in execution; Progressbar.setprogress (0);}}
Android Asynchronous Task Asynctask