Android provides a tool class: Asynctask, which makes it easier to create long-running tasks that need to interact with the user interface. Asynctask is more lightweight than handler, and is suitable for simple asynchronous processing without the need for threading and handter. Asynctask is an abstract class. Asynctask defines three types of generic type params,progress and result:
The params 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.
By using the Asynctask to implement the file download and the progress update prompt to demonstrate the dynamic diagram:
This real-time demo download directory for the download folder, first into the download folder, no picture files, download completed, again, you can see the demo download pictures
let's start with a brief introduction to Asynctask's execution steps:
The implementation of Asynctask is divided into four steps, each of which corresponds to a callback method, what we need is to implement these methods.
(1) First define a class inheritance Asynctask
(2) Implement one or more of the following methods as defined in Asynctask
The four step methods are:
(1) OnPreExecute (): Called by Uithread, this method is used to do some preparatory work, such as displaying a progress bar on the interface.
(2) Dolnbackground (Params ...) : Executes after OnPreExecute and runs in the background thread. Take responsibility for time-consuming work. You can call the Publishprogress method to update the real-time task progress.
(3) onprogressupdate (Progress ... ): After the Publishprogress method is called, Uithread will invoke the method to show the progress of the task on the interface, for example, by showing it through a progress bar.
(4) OnPostExecute (Result): After Dolnbackground execution completes, the OnPostExecute method is called by Uithread, and the results of the background calculation are passed to Uithread through this method.
example of an effect implementation code:
The first step: layout file of activity Activity_main.xml
1<?xml version= "1.0" encoding= "Utf-8"?>2<LinearLayout3Xmlns:android= "Http://schemas.android.com/apk/res/android"4Xmlns:tools= "Http://schemas.android.com/tools"5Android:id= "@+id/activity_main"6Android:layout_width= "Match_parent"7android:layout_height= "Match_parent"8android:orientation= "Vertical"9tools:context= "Com.example.administrator.asynctask.MainActivity" >Ten<TextView OneAndroid:id= "@+id/tv" AAndroid:layout_width= "Match_parent" -android:layout_height= "Wrap_content" -android:text= "panhouye!" theAndroid:textsize= "20sp"/> -<ProgressBar -Android:id= "@+id/progress" -Android:layout_width= "Match_parent" +android:layout_height= "Wrap_content" -style= "@style/base.widget.appcompat.progressbar.horizontal" +android:visibility= "Visible"/> A<Button atAndroid:layout_width= "Match_parent" -android:layout_height= "Wrap_content" -android:onclick= "Image" -android:text= "Download Picture"/> -</LinearLayout>
Step Two: Java implementation code Mainactivity.java file
1 ImportAndroid.os.AsyncTask;2 Importandroid.os.Environment;3 Importandroid.support.v7.app.AppCompatActivity;4 ImportAndroid.os.Bundle;5 ImportAndroid.view.View;6 ImportAndroid.widget.ProgressBar;7 ImportAndroid.widget.TextView;8 ImportJava.io.BufferedInputStream;9 ImportJava.io.BufferedOutputStream;Ten ImportJava.io.File; One ImportJava.io.FileOutputStream; A Importjava.net.HttpURLConnection; - ImportJava.net.URL; - /** the * Created by Panchengjia on 2016/12/19. - */ - Public classMainactivityextendsappcompatactivity { - //declaring the update flag for publishprogress + Private Static Final intProgress_max = 0x1; - Private Static Final intUPDATE = 0X2; + PrivateTextView TV; A ProgressBar progress; at intContentlen;//declare the total length of files to download - @Override - protected voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); -TV =(TextView) Findviewbyid (r.id.tv); inProgress =(ProgressBar) Findviewbyid (r.id.progress); - } to Public voidimage (view view) { + //enable Asynctask, incoming content to be executed (picture address) - NewDownLoad (). Execute ("Http://cdnq.duitang.com/uploads/item/201402/22/20140222115440_jWNmx.thumb.700_0.jpeg"); the } * classDownLoadextendsAsynctask<string,integer,string>{ $ //called by the UI thread before performing the actual background operationPanax Notoginseng @Override - protected voidOnPreExecute () { the Super. OnPreExecute (); + //prepare for initial progress before downloading AProgress.setprogress (0); the } + //in OnPreExecute execution, the method runs in the background thread - @Override $ protectedstring Doinbackground (String ... params) { $ Try { -URL url =NewURL (params[0]); - //Get Connections theHttpURLConnection connection =(HttpURLConnection) url.openconnection (); - //get the size of the download fileWuyiContentlen =connection.getcontentlength (); the //set the maximum progress bar based on the download file size (use tags to differentiate real-time progress updates) - publishprogress (Progress_max,contentlen); Wu //cyclic download (side read side deposit) -Bufferedinputstream bis =NewBufferedinputstream (Connection.getinputstream ()); AboutBufferedoutputstream BOS =NewBufferedoutputstream (NewFileOutputStream (New $File (Environment.getexternalstoragedirectory () + "/download/ss.jpg"))); - intLen =-1; - byte[] bytes =New byte[1024]; - while((Len=bis.read (bytes))!=-1){ ABos.write (bytes,0, Len); + Bos.flush (); the //update download progress in real-time (use tags to distinguish maximum values) - publishprogress (Update,len); $ //Demo Download the picture is too small, the speed is too fast, sleep 300 milliseconds, convenient for everyone to observe theThread.Sleep (300); the } the bos.close (); the bis.close (); -}Catch(Exception e) { in e.printstacktrace (); the } the return"Download Complete"; About } the //after Publishprogress is called, the UI thread calls this method the @Override the protected voidonprogressupdate (Integer ... values) { + Super. Onprogressupdate (values); - Switch(values[0]){ the CaseProgress_max:BayiProgress.setmax (values[1]); the Break; the CaseUPDATE: -Progress.incrementprogressby (values[1]); - //get the download progress percentage and update TextView the intI= (Progress.getprogress () *100)/Contentlen; theTv.settext ("Download progress is:" +i+ "%"); the Break; the } - } the //The UI thread executes after the Doinbackground method finishes executing the @Override the protected voidOnPostExecute (String s) {94 Super. OnPostExecute (s); the progress.setvisibility (view.gone); the Tv.settext (s); the }98 } About}
Finally, emphasize the Asynctask design guidelines:
(1) An instance of Asynctask must be created in Ulthread.
(2) The Execute method must be called in Ulthread.
(3) Do not manually call OnPreExecute (), OnPostExecute (Result), Dolnbackground (Params ...), Onprogressupdate (Progress ...) These several methods.
(4) The task can only be executed once, otherwise an exception will occur when multiple calls are made.
(5) Asynctask can not completely replace threads, in some logic is more complex or need to be repeated in the background of the logic may need to implement the thread.
Use Asynctask in Android for file download and progress update tips