之前公司里面項目的下載模塊都是使用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 <Button 10 android:id="@+id/begin" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="開始下載"/> 14 15 <Button 16 android:id="@+id/end" 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" 19 android:text="暫停下載"/> 20 21 <ProgressBar 22 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 @Override 182 protected void onPreExecute() { 183 Log.i(TAG, "download begin "); 184 Toast.makeText(AsyncTaskDemoActivity.this, "開始下載", Toast.LENGTH_SHORT).show(); 185 super.onPreExecute(); 186 } 187 188 @Override 189 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 @Override 197 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