Android uses Asynctask to implement file downloads and progress update tips _android

Source: Internet
Author: User

Android provides a tool class: Asynctask, which makes it easier to create long-running tasks that require interaction with the user interface. Compared with handler, Asynctask is lighter, suitable for simple asynchronous processing, without the use of threads and Handter. Asynctask is an abstract class. Asynctask defines three generic types params,progress and result:

Params the input parameters that start the task execution, such as the URL of the HTTP request.

Progress the percentage of background task execution.

Result background The results returned by the task, such as String.

By using Asynctask to implement file download and progress update prompts demo diagram:

The Real machine demo download directory for the download folder, first into the download folder, no picture files, download completed, see again, you can see this demo download pictures

Let's start with a brief introduction to Asynctask's execution steps:

The execution of Asynctask is divided into four steps, each of which corresponds to a callback method, and what we need is to implement these methods.

(1) First define a class inheritance Asynctask

(2) Implement the following one or several methods defined in Asynctask

The four step methods are:

(1) OnPreExecute (): Called by the Uithread, which is used to do some preparatory work, such as displaying a progress bar on the interface.

(2) Dolnbackground (Params ...) : will be executed after OnPreExecute, running in a background thread. Responsible for performing time-consuming work. You can call the Publishprogress method to update the progress of a live task.

(3) onprogressupdate (Progress ...) ): After the Publishprogress method is invoked, Uithread will invoke the method to display the progress of the task in the interface, for example, by a progress bar.

(4) OnPostExecute (Result): After Dolnbackground execution completes, the OnPostExecute method is called Uithread, and the results of the background calculation are passed to Uithread by this method.

Effect Implementation code example:

The first step: layout the activity in the layout file Activity_main.xml

 <?xml version= "." Encoding= "utf-"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "xmlns:tools=" Http://schemas.android.com/tools "android:id=" @+id/activity_main "Android:layout_width=" mat Ch_parent "android:layout_height=" match_parent "android:orientation=" vertical "tools:context=" Com.example.adminis
     Trator.asynctask.MainActivity "> <textview android:id=" @+id/tv "android:layout_width=" Match_parent "
     android:layout_height= "Wrap_content" android:text= "panhouye!"
     android:textsize= "sp"/> <progressbar android:id= "@+id/progress" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" style= "@style/base.widget.appcompat.progressbar.horizontal" Android:visib
     ility= "visible"/> <button android: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

 Import Android.os.AsyncTask;
 Import android.os.Environment;
 Import android.support.v.app.appcompatactivity;
 Import Android.os.Bundle;
 Import Android.view.View;
 Import Android.widget.ProgressBar;
 Import Android.widget.TextView;
 Import Java.io.BufferedInputStream;
 Import Java.io.BufferedOutputStream;
 Import Java.io.File;
 Import Java.io.FileOutputStream;
 Import java.net.HttpURLConnection;
 Import Java.net.URL;
 /** * Created by Panchengjia on//. */public class Mainactivity extends Appcompatactivity {//Declaration publishprogress update Tag private static final int progress_m
   AX = X;
   private static final int UPDATE = X;
   Private TextView TV;
   ProgressBar progress; int contentlen;//declares the total length of the file to be downloaded @Override protected void onCreate (Bundle savedinstancestate) {super.oncreate
     Instancestate);
     Setcontentview (R.layout.activity_main);
     TV = (TextView) Findviewbyid (r.id.tv);
   Progress = (ProgressBar) Findviewbyid (r.id.progress); } public void Image (VieW view) {//enable Asynctask, incoming content to be executed (picture address) New DownLoad (). Execute ("Http://cdnq.duitang.com/uploads/item///_jWNmx.thumb
   . _.jpeg "); Class DownLoad extends asynctask<string,integer,string>{//is called @Override by UI thread before performing the actual background operation Prote
       CTED void OnPreExecute () {super.onpreexecute ();
     Pre-Download initial progress progress.setprogress ();
         //In OnPreExecute execution, this method runs in the background thread @Override protected string Doinbackground (String ... params) {try {
         URL url = new URL (params[]);
         Get connection HttpURLConnection connection = (httpurlconnection) url.openconnection ();
         Gets the size of the download file Contentlen = Connection.getcontentlength ();
         Set the maximum progress bar based on the download file size (use Mark to distinguish real time progress update) publishprogress (Progress_max,contentlen);
         Cyclic download (save while reading) Bufferedinputstream bis = new Bufferedinputstream (Connection.getinputstream ());
        Bufferedoutputstream BOS = new Bufferedoutputstream (New FileOutputStream     File (Environment.getexternalstoragedirectory () + "/download/ss.jpg"));
         int Len =-;
         byte[] bytes = new byte[];
           while ((Len=bis.read (bytes))!=-) {bos.write (Bytes,,len);
           Bos.flush ();
           Real-time update download progress (using tag to distinguish maximum) publishprogress (Update,len);
         Demo download of the picture is too small, speed too fast, dormant millisecond, convenient for everyone to observe thread.sleep ();
         } bos.close ();
       Bis.close ();
       catch (Exception e) {e.printstacktrace ();
     Return "Download Complete";
       When Publishprogress is invoked, UI thread calls this method @Override protected void Onprogressupdate (Integer ... values) {
       Super.onprogressupdate (values);
           Switch (values[]) {case PROGRESS_MAX:progress.setMax (values[]);
         Break
           Case UPDATE:progress.incrementProgressBy (values[]);
           Gets the download progress percentage and updates the TextView int i= (progress.getprogress () *)/contentlen;
        Tv.settext ("Download Progress:" +i+ "%");   Break @Override protected void OnPostExecute (String s) {SUPER.O After the//doinbackground method is executed by UI thread
       Npostexecute (s);
       Progress.setvisibility (View.gone);
     Tv.settext (s);

 }
   }
 }

Finally, we emphasize the design criteria of Asynctask:

(1) An instance of Asynctask must be created in Ulthread.

(2) The Execute method must be called in Ulthread.

(3) Do not manually Invoke OnPreExecute (), OnPostExecute (Result), Dolnbackground (Params ...), Onprogressupdate (Progress ...) These several methods.

(4) The task can only be executed once, otherwise the exception will occur when multiple calls are made.

(5) Asynctask can not completely replace the thread, in some logic is more complex or need to be repeated in the background of the logic may need a thread to implement.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.