AsyncTask實現斷點續傳,asynctask斷點續傳
之前公司裡面項目的下載模組都是使用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 }
這樣簡單的斷點續傳功能就實現了,這裡只是單個線程的,如果涉及多個線程同時下載,那複雜很多,後面再琢磨琢磨。