Asynctask
Asynctask, an asynchronous task that can simply perform asynchronous operations and publish execution results to the UI main thread. Asynctask is an abstract class that actually combines thread and handler to implement asynchronous threading operations, but it forms a common thread framework, much clearer and simpler. Asynctask should be used for shorter operations (up to a few seconds). If you need to keep running threads for a long time, you can use Threadpooexecutor or futuretask, about the contents of these two classes, later introduced, the blog is mainly about Asynctask.
Asynctask is defined as an operation that runs in a background thread, and the results are posted on the UI thread. Its asynchronous work parameters and return values are specified by three parameters of the generic type: Params, Progress, result. Asynctask will undergo 4 steps: OnPreExecute, Doinbackground, Onprogressupdate, OnPostExecute. The following three parameters and four steps are explained in detail:
Three generic parameters:
- Params: The type of parameter that is sent to the execution task.
- Progress: The type of progress, the calculation progress sent back to the UI thread type.
- Results: The return result type of the asynchronous task.
An asynchronous task will go through four phases:
- OnPreExecute (): is typically used to set up a task before it is invoked on a UI thread to perform a task.
- Doinbackground (Params ...) : A time-consuming operation that is primarily used to perform asynchronous tasks, in which progress information is published through the Publishprogress () method, and the execution results are returned after execution completes.
- Onprogreddupdate (Progress ...) : To accept the progress information passed by Doinbackground () on the UI thread, and to display progress information on the UI thread, the timing of the execution is uncertain.
- OnPostExecute (Result): The return value that is executed on the UI thread by Doinbackground ().
A schematic of the four steps described above:
Asynctask Cancel the task
At any point in the program, you can cancel the task by using the Cancel (Boolean) method, and when the task is canceled, the return value of iscancelled () is changed to return True. The oncancelled (Object) method is then invoked, substituting OnPostExecute () for the return result of Doinbackground (). In a run, you can often see if a task is canceled through the iscancelled () method.
Asynctask Rules of Use
The following rules must be followed for using asynctask:
%20%20%20%20
- Asynctask must be declared on the UI thread.
%20%20%20%20
- Asynctask must be instantiated on the UI thread.
%20%20%20%20
- The task must be performed through the Execute () method.
%20%20%20%20
- You cannot call OnPreExecute (), OnPostExecute (Resut), Doinbackground (Params ...), Onprogressupdate (Progress ...) directly. Method.
%20%20%20%20
- You can set the task to execute only once, and if you attempt to do it again, you will get an error.
Example
A simple example of downloading a picture on a network via asynctask, displaying a wait box when downloading, and displaying it in a imageview.
Implementation code:
%201%20package%20com.bgxt.datatimepickerdemo;
%202%20%203%20import%20org.apache.http.httpentity;
%204%20import%20org.apache.http.httpresponse;
%205%20import%20org.apache.http.client.httpclient;
%206%20import%20org.apache.http.client.methods.httpget;
%207%20import%20org.apache.http.impl.client.defaulthttpclient;
%208%20import%20org.apache.http.util.entityutils;
%209%20 10%20import%20android.app.activity;
11%20import%20android.app.progressdialog;
12%20import%20android.graphics.bitmap;
13%20import%20android.graphics.bitmapfactory;
14%20import%20android.os.asynctask;
15%20import%20android.os.bundle;
16%20import%20android.view.view;
17%20import%20android.widget.button;
18%20import%20android.widget.imageview; 19%20 20%20public%20class%20asynctaskactivity1%20extends%20activity%20{21%20%20%20%20%20private%20button%
20btnDown;
22%20%20%20%20%20private%20imageview%20ivimage; 23%20%20%20%20%20private%20static%20string%20image_path%20=%20 "Http://ww4.sinaimg.cn/bmiddle/786013a5jw1e7akotp4bcj20c80I3aao.jpg ";
ProgressDialog Private Dialog; @Override protected void OnCreate (Bundle savedinstancestate) {A//TODO auto-generated method
Stub super.oncreate (savedinstancestate);
Setcontentview (r.layout.asynctask_activity);
Btndown = (Button) Findviewbyid (R.id.btndown);
Ivimage = (ImageView) Findviewbyid (r.id.ivsinaimage);
34 35//Declare a wait box to prompt the user to wait for dialog=new ProgressDialog (this);
Panax Notoginseng dialog.settitle ("hint Information");
Dialog.setmessage ("Downloading, please later ..."); Btndown.setonclicklistener (New View.onclicklistener () {@Override 43 public void OnClick (View v) {44//performs an asynchronous task and passes the picture address as a parameter in the form of the new MyTask (). Execute (IMA
Ge_path);
46} 47}); 48} 49 50//with a String parameter, void means no progress information, bitmap indicates that the asynchronous task returns a bitmap of the public class MyTask extends asynctask<string , Void, bitmap>{52//indicates the operation of the task prior to execution @Override protected void OnPreExecute () super.onpreexec
Ute ();
56//Show Waiting Box Dialog.show (); 58} 59 60//mainly complete time-consuming operations protected Bitmap doinbackground (String ... params) {httpclient httpclient=new defaulthttpclient (); HttpGet httpget=new HttpGet (params[0)); 65
Bitmap Bitmap=null; try {67//download pictures from the network HttpResponse HttpResponse =httpclient.execute (httpge
T); Httpresponse.getstatusline (). Getstatuscode () ==200) {httpentity httpentity = h
Ttpresponse.getentity ();
Byte[] Data=entityutils.tobytearray (httpentity);
Bitmap=bitmapfactory.decodebytearray (data, 0, data.length); Exception e} catch (E.printstacktra)CE ();
Bitmap return; 78} 79 80//Complete update UI operation Bayi @Override protected void OnPostExecute (Bitmap result) {auto-generated//TODO Super.onpostexecute (result); 85//Set Imagev
Iew Display Picture Ivimage.setimagebitmap (result);
87//Destroy Wait frame Dialog.dismiss (); 89} 90 91} 92}
Effect Display:
The demo above does not use the information of progress, the following provides a complete Asynctask demo, also download a picture, and show to a imageview, but here in the download process to add a progress bar dialog box, to show the progress of the download.
Implementation code:
%20%201%20package%20com.bgxt.datatimepickerdemo;
%20%202%20%20%203%20import%20java.io.bytearrayoutputstream;
%20%204%20import%20java.io.inputstream;
%20%205%20%20%206%20import%20org.apache.http.httpresponse;
%20%207%20import%20org.apache.http.client.httpclient;
%20%208%20import%20org.apache.http.client.methods.httpget;
%20%209%20import%20org.apache.http.impl.client.defaulthttpclient;
%2010%20%2011%20import%20android.app.activity;
%2012%20import%20android.app.progressdialog;
%2013%20import%20android.graphics.bitmap;
%2014%20import%20android.graphics.bitmapfactory;
%2015%20import%20android.os.asynctask;
%2016%20import%20android.os.bundle;
%2017%20import%20android.view.view;
%2018%20import%20android.widget.button;
%2019%20import%20android.widget.imageview; %2020%20%2021%20public%20class%20asynctaskactivity2%20extends%20activity%20{%2022%20%20%20%20%20private%
20button%20btndown;
%2023%20%20%20%20%20private%20imageview%20ivimage; %2024%20%20%20%20%20private%20static%20string%20image_pAth%20=%20 "Http://ww4.sinaimg.cn/bmiddle/786013a5jw1e7akotp4bcj20c80i3aao.jpg";
ProgressDialog Private Dialog; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedinstanc
Estate);
Setcontentview (r.layout.asynctask_activity);
Btndown = (Button) Findviewbyid (R.id.btndown);
Ivimage = (ImageView) Findviewbyid (r.id.ivsinaimage);
dialog = new ProgressDialog (this);
Dialog.settitle ("hint");
Dialog.setmessage ("Downloading, please later ...");
Panax Notoginseng Dialog.setprogressstyle (progressdialog.style_horizontal);
Dialog.setcancelable (FALSE); Btndown.setonclicklistener (New View.onclicklistener () {@Override the pub
LIC void OnClick (View v) {44//Execute Asynchronous task the new MyTask (). Execute (image_path);
46} 47}); The public class MyTask extends AsyNctask<string, Integer, bitmap> {Wuyi @Override protected void OnPreExecute () {53
Super.onpreexecute ();
Dialog.show (); @Override protected void Onprogressupdate (Integer ... values) {s
Uper.onprogressupdate (values);
60//Set Progress dialog box progress value of Dialog.setprogress (Values[0]); @Override protected void OnPostExecute (Bitmap result) {Super.on
PostExecute (result);
Dialog.dismiss ();
Ivimage.setimagebitmap (result); @Override protected Bitmap doinbackground (String ... params) {Bi
TMap bitmap = null;
Bytearrayoutputstream outputstream = new Bytearrayoutputstream ();
InputStream inputstream = null;
A try {httpclient httpclient = new Defaulthttpclient (); 78 HttpGet httpget = new HttpGet (params[0]);
HttpResponse HttpResponse = Httpclient.execute (HttpGet); Httpresponse.getstatusline () getstatuscode () = InputStream = Httpre
Sponse.getentity (). getcontent ();
Long file_length = Httpresponse.getentity () getcontentlength ();
-int len = 0;
byte[] data = new byte[1024];
int total_length = 0; 87//Read picture data in bytes (len = inputstream.read (data)!=-1) {89
Total_length = Len; 90//calculation progress of the int values = (int) (Total_length/(float) file_length) *
100);
92//Release Progress Information publishprogress (values);
Outputstream.write (data, 0, Len); 95 Byte[] Result=outputstream.tobytearray ();
Bitmap=bitmapfactory.decodebytearray (result, 0, result.length); E.printstacktrace} catch (Exception e) {MB) (); nally {102 try {InputStream!= null) {Inputstre
Am.close (); E2} catch (Exception) {107} 108} 109
return bitmap; 110} 111} 112}
Implementation effect: