Why use asynchronous Tasks?
In Android, only the main thread can update the UI, while other threads cannot manipulate the UI directly
Android itself is a multi-threaded operating system, we can not put all the operations in the main thread, such as some time-consuming operation. If placed in the main thread will cause blocking and the system will throw a ANR exception when the blocking event is too long. So we're going to use asynchronous tasks. Android provides us with a packaged component, Asynctask.
Asynctask can update the UI in a child thread, encapsulation simplifies asynchronous operations. Applies to simple asynchronous processing. If you need to use handler for multiple background tasks, it is no longer explained here.
Asynctask are usually used for inheritance. Asynctask defines three types of generics <Params,Progress,Result>
Params: Type of parameter entered when starting a task
Progress: Percentage of background task execution
Result: The type of the result returned after the execution of the task is completed
The methods to be overridden after inheriting asynctask are:
Doinbackgroud: You must rewrite, asynchronously perform the task that the background thread is going to accomplish, the time-consuming task is written here, and the UI cannot be manipulated here. You can call the Publishprogress method to update the real-time task progress
OnPreExecute: Call before a time-consuming operation can complete some initialization operations
OnPostExecute: After Doinbackground execution completes, the main thread calls this method, and you can manipulate the UI in this method
Onprogressupdate: Call the Publishprogress method in the Doinbackgroud method, and then call this method after updating the execution progress of the task
Here's an example to understand Asynctask
First, attach the result of the operation
Layout file:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:orientation= "vertical" > <button android:id= "@+id/btn_download" android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "Center_horizontal" android:text= "Click to download"/> <framelayout android:layout_width= "Fill_parent" android: layout_height= "Fill_parent" > <imageview android:id= "@+id/iv_image" android:layout_width= " Fill_parent " android:layout_height=" fill_parent " android:scaletype=" Fitcenter "/> </ Framelayout></linearlayout>
Mainactivity
Package Com.example.asynctask;import Java.io.bufferedinputstream;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.malformedurlexception;import Java.net.urlconnection;import Android.os.asynctask;import Android.os.bundle;import Android.app.Activity;import Android.app.progressdialog;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.imageview;public class Mainactivity extends Activity implements Onclicklistener{private ImageView image ;p rivate progressdialog progress;private button btn_download;private static String url= "http://img4.imgtn.bdimg.com/ It/u=1256159061,743487979&fm=21&gp=0.jpg "; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); image= (ImageView) Findviewbyid ( R.id.iv_image); btn_download= (Button) finDviewbyid (r.id.btn_download);p rogress=new progressdialog (this);p Rogress.seticon (R.drawable.ic_launcher); Progress.settitle ("hint message");p rogress.setmessage ("Downloading, please wait ...");p Rogress.setprogressstyle (progressdialog.style_ horizontal); Btn_download.setonclicklistener (this);} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubnew Myasynctask (). Execute (URL);} /* * string********* corresponds to our URL type * integer******** progress bar Progress Value * bitmap********* The type returned after the asynchronous task completes * */class Myasynctask extends Asyn Ctask<string, Integer, bitmap>{//executes the asynchronous task (Doinbackground) and executes @overrideprotected void OnPreExecute () in the UI thread {//TODO auto-generated method Stubsuper.onpreexecute (); if (image!=null) {image.setvisibility (view.gone);} Start Download dialog progress bar shows Progress.show ();p rogress.setprogress (0);} @Overrideprotected Bitmap doinbackground (String ... params) {//TODO auto-generated method Stub//params is a variable-length array Here we only pass in a URL String url=params[0]; Bitmap Bitmap=null; URLConnection connection;inputstream is;//The input stream used to get the data bytearrayoutputsTream bos;//can capture data from a memory buffer and convert it into a byte array. int Len;float Count=0,total;//count for the picture has downloaded the size of total size try {//Get network Connection Object connection= (urlconnection) New Java.net.URL ( URL). OpenConnection ();//Gets the total length of the current page total= (int) connection.getcontentlength ();//Gets the input stream Is=connection.getinputstream (); bos=new bytearrayoutputstream (); byte []data=new Byte[1024];while ((Len=is.read (data))!=-1) {Count+=len;bos.write (data,0,len);//Call publishprogress to announce progress, the last Onprogressupdate method will be executed publishprogress ((int) (count/total*100));//In order to show progress Artificial hibernation 0.5 seconds thread.sleep (500);} Bitmap=bitmapfactory.decodebytearray (Bos.tobytearray (), 0, Bos.tobytearray (). length); Is.close (); Bos.close ();} catch (Malformedurlexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return bitmap;} Execution can operate in the UI thread ui@overrideprotected void OnPostExecute (Bitmap Bitmap) {//TODO auto-generated method stubsuper.oNpostexecute (bitmap);//Download Complete dialog box progress bar hidden Progress.cancel (); Image.setimagebitmap (bitmap); Image.setvisibility ( view.visible);} /* * Call this method to update the progress bar after the Publishprogress method has been called in the Doinbackground method to update the execution progress of the task * */@Overrideprotected void Onprogressupdate ( Integer ... values) {//TODO auto-generated method Stubsuper.onprogressupdate (values);p rogress.setprogress (Values[0]) ;}}}
Finally, don't forget to configure network access in the Androidmanifest file
<uses-permission android:name= "Android.permission.INTERNET"/>
Android: Asynchronous task Asynctask Introduction and asynchronous task download picture (with progress bar)