Use Asynctask in Android for file download and progress update tips

Source: Internet
Author: User

Tags: str max img IMA live asynctask instance android Async

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://"4Xmlns:tools= "Http://"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 file
1 ImportAndroid.os.AsyncTask;2 Importandroid.os.Environment;3;4 ImportAndroid.os.Bundle;5 ImportAndroid.view.View;6 ImportAndroid.widget.ProgressBar;7 ImportAndroid.widget.TextView;8;9;Ten; One; A; -; - /** 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 (; inProgress =(ProgressBar) Findviewbyid (; -     } to      Public voidimage (view view) { +     //enable Asynctask, incoming content to be executed (picture address) -         NewDownLoad (). Execute ("Http://"); 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(( (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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: