Android AsyncTask实现断点续传

来源:互联网 发布:网络合同无效管辖法院 编辑:程序博客网 时间:2024/04/30 03:19

转至:http://www.cnblogs.com/liuling/p/2015-10-10-01.html


之前公司里面项目的下载模块都是使用xUtils提供的,最近看了下xUtils的源码,它里面也是使用AsyncTask来执行异步任务的,它的下载也包含了断点续传的功能。这里我自己也使用AsyncTask也实现了简单的断点续传的功能。

  首先说一说AsyncTask吧,先来看看AsyncTask的定义:

1 public abstract class AsyncTask<Params, Progress, Result> 

  三种泛型类型分别代表“启动任务执行的输入参数”、“后台任务执行的进度”、“后台计算结果的类型”。在特定场合下,并不是所有类型都被使用,如果没有被使用,可以用java.lang.Void类型代替。

  一个异步任务的执行一般包括以下几个步骤:

  1.execute(Params... params),执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。

  2.onPreExecute(),在execute(Params... params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记。

  3.doInBackground(Params... params),在onPreExecute()完成后立即执行,用于执行较为费时的操作,此方法将接收输入参数和返回计算结果。在执行过程中可以调用publishProgress(Progress... values)来更新进度信息。

  4.onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上。

  5.onPostExecute(Result result),当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上。

  在使用的时候,有几点需要格外注意:

  1.异步任务的实例必须在UI线程中创建。

  2.execute(Params... params)方法必须在UI线程中调用。

  3.不要手动调用onPreExecute(),doInBackground(Params... params),onProgressUpdate(Progress... values),onPostExecute(Result result)这几个方法。

  4.不能在doInBackground(Params... params)中更改UI组件的信息。

  5.一个任务实例只能执行一次,如果执行第二次将会抛出异常。

  下面是使用AsyncTask实现断点续传的代码:

  断点续传的思路其实也挺简单,首先判断待下载的文件在本地是否存在,如果存在,则表示该文件已经下载过一部分了,只需要获取文件当前大小即已下载大小,设置给http的header就行了:

1 Header header_size = new BasicHeader("Range", "bytes=" + readedSize + "-");2 request.addHeader(header_size);

 

  1、布局文件代码:

复制代码
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 3     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 4     android:paddingRight="@dimen/activity_horizontal_margin" 5     android:paddingTop="@dimen/activity_vertical_margin" 6     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".AsyncTaskDemoActivity" 7     android:orientation="vertical"> 8  9     <Button10         android:id="@+id/begin"11         android:layout_width="wrap_content"12         android:layout_height="wrap_content"13         android:text="开始下载"/>14 15     <Button16         android:id="@+id/end"17         android:layout_width="wrap_content"18         android:layout_height="wrap_content"19         android:text="暂停下载"/>20 21     <ProgressBar22         android:id="@+id/progressbar"23         style="?android:attr/progressBarStyleHorizontal"24         android:layout_width="fill_parent"25         android:layout_height="3dp"26         android:layout_marginTop="10dp"27         android:max="100" />28 29 </LinearLayout>
复制代码

  布局比较简单,就两个按钮和一个进度条控件,按钮控制下载与暂停。

 

  2、断点续传核心代码:

复制代码
  1 package com.bbk.lling.myapplication;  2   3 import android.app.Activity;  4 import android.os.AsyncTask;  5 import android.os.Bundle;  6 import android.os.Environment;  7 import android.util.Log;  8 import android.view.View;  9 import android.widget.ProgressBar; 10 import android.widget.Toast; 11  12 import org.apache.http.Header; 13 import org.apache.http.HttpResponse; 14 import org.apache.http.client.HttpClient; 15 import org.apache.http.client.methods.HttpGet; 16 import org.apache.http.impl.client.DefaultHttpClient; 17 import org.apache.http.message.BasicHeader; 18  19 import java.io.File; 20 import java.io.FileOutputStream; 21 import java.io.IOException; 22 import java.io.InputStream; 23 import java.io.OutputStream; 24 import java.io.RandomAccessFile; 25 import java.net.MalformedURLException; 26  27 public class AsyncTaskDemoActivity extends Activity { 28  29     private ProgressBar progressBar; 30     //下载路径 31     private String downloadPath = Environment.getExternalStorageDirectory() + 32             File.separator + "download"; 33     private DownloadAsyncTask downloadTask; 34  35     @Override 36     protected void onCreate(Bundle savedInstanceState) { 37         super.onCreate(savedInstanceState); 38         setContentView(R.layout.activity_async_task_demo); 39         progressBar = (ProgressBar) findViewById(R.id.progressbar); 40         //开始下载 41         findViewById(R.id.begin).setOnClickListener(new View.OnClickListener() { 42             @Override 43             public void onClick(View v) { 44                 /** 45                  * 一个AsyncTask只能被执行一次,否则会抛异常 46                  * java.lang.IllegalStateException: Cannot execute task: the task is already running. 47                  * 如果要重新开始任务的话要重新创建AsyncTask对象 48                  */ 49                 if(downloadTask != null && !downloadTask.isCancelled()) { 50                     return; 51                 } 52                 downloadTask = new DownloadAsyncTask("http://bbk-lewen.u.qiniudn.com/3d5b1a2c-4986-4e4a-a626-b504a36e600a.flv"); 53                 downloadTask.execute(); 54             } 55         }); 56  57         //暂停下载 58         findViewById(R.id.end).setOnClickListener(new View.OnClickListener() { 59             @Override 60             public void onClick(View v) { 61                 if(downloadTask != null && downloadTask.getStatus() == AsyncTask.Status.RUNNING) { 62                     downloadTask.cancel(true); 63                 } 64             } 65         }); 66  67     } 68  69     /** 70      * 下载的AsyncTask 71      */ 72     private class DownloadAsyncTask extends AsyncTask<String, Integer, Long> { 73         private static final String TAG = "DownloadAsyncTask"; 74         private String mUrl; 75  76         public DownloadAsyncTask(String url) { 77             this.mUrl = url; 78         } 79  80         @Override 81         protected Long doInBackground(String... params) { 82             Log.i(TAG, "downloading"); 83             if(mUrl == null) { 84                 return null; 85             } 86             HttpClient client = new DefaultHttpClient(); 87             HttpGet request = new HttpGet(mUrl); 88             HttpResponse response = null; 89             InputStream is = null; 90             RandomAccessFile fos = null; 91             OutputStream output = null; 92  93             try { 94                 //创建存储文件夹 95                 File dir = new File(downloadPath); 96                 if(!dir.exists()) { 97                     dir.mkdir(); 98                 } 99                 //本地文件100                 File file = new File(downloadPath + File.separator + mUrl.substring(mUrl.lastIndexOf("/") + 1));101                 if(!file.exists()){102                     //创建文件输出流103                     output = new FileOutputStream(file);104                     //获取下载输入流105                     response = client.execute(request);106                     is = response.getEntity().getContent();107                     //写入本地108                     file.createNewFile();109                     byte buffer [] = new byte[1024];110                     int inputSize = -1;111                     //获取文件总大小,用于计算进度112                     long total = response.getEntity().getContentLength();113                     int count = 0; //已下载大小114                     while((inputSize = is.read(buffer)) != -1) {115                         output.write(buffer, 0, inputSize);116                         count += inputSize;117                         //更新进度118                         this.publishProgress((int) ((count / (float) total) * 100));119                         //一旦任务被取消则退出循环,否则一直执行,直到结束120                         if(isCancelled()) {121                             output.flush();122                             return null;123                         }124                     }125                     output.flush();126                 } else {127                     long readedSize = file.length(); //文件大小,即已下载大小128                     //设置下载的数据位置XX字节到XX字节129                     Header header_size = new BasicHeader("Range", "bytes=" + readedSize + "-");130                     request.addHeader(header_size);131                     //执行请求获取下载输入流132                     response = client.execute(request);133                     is = response.getEntity().getContent();134                     //文件总大小=已下载大小+未下载大小135                     long total = readedSize + response.getEntity().getContentLength();136 137                     //创建文件输出流138                     fos = new RandomAccessFile(file, "rw");139                     //从文件的size以后的位置开始写入,其实也不用,直接往后写就可以。有时候多线程下载需要用140                     fos.seek(readedSize);141                     //这里用RandomAccessFile和FileOutputStream都可以,只是使用FileOutputStream的时候要传入第二哥参数true,表示从后面填充142 //                    output = new FileOutputStream(file, true);143 144                     byte buffer [] = new byte[1024];145                     int inputSize = -1;146                     int count = (int)readedSize;147                     while((inputSize = is.read(buffer)) != -1) {148                         fos.write(buffer, 0, inputSize);149 //                        output.write(buffer, 0, inputSize);150                         count += inputSize;151                         this.publishProgress((int) ((count / (float) total) * 100));152                         if(isCancelled()) {153 //                            output.flush();154                             return null;155                         }156                     }157 //                    output.flush();158                 }159             } catch (MalformedURLException e) {160                 Log.e(TAG, e.getMessage());161             } catch (IOException e) {162                 Log.e(TAG, e.getMessage());163             } finally{164                 try{165                     if(is != null) {166                         is.close();167                     }168                     if(output != null) {169                         output.close();170                     }171                     if(fos != null) {172                         fos.close();173                     }174                 } catch(Exception e) {175                     e.printStackTrace();176                 }177             }178             return null;179         }180 181         @Override182         protected void onPreExecute() {183             Log.i(TAG, "download begin ");184             Toast.makeText(AsyncTaskDemoActivity.this, "开始下载", Toast.LENGTH_SHORT).show();185             super.onPreExecute();186         }187 188         @Override189         protected void onProgressUpdate(Integer... values) {190             super.onProgressUpdate(values);191             Log.i(TAG, "downloading  " + values[0]);192             //更新界面进度条193             progressBar.setProgress(values[0]);194         }195 196         @Override197         protected void onPostExecute(Long aLong) {198             Log.i(TAG, "download success " + aLong);199             Toast.makeText(AsyncTaskDemoActivity.this, "下载结束", Toast.LENGTH_SHORT).show();200             super.onPostExecute(aLong);201         }202     }203 204 }
复制代码

  这样简单的断点续传功能就实现了,这里只是单个线程的,如果涉及多个线程同时下载,那复杂很多,后面再琢磨琢磨。

 

源码下载:https://github.com/liuling07/MultiTaskAndThreadDownload


0 0
原创粉丝点击