日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

AsyncTask实现断点续传

發(fā)布時間:2024/4/13 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 AsyncTask实现断点续传 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

  之前公司里面項目的下載模塊都是使用xUtils提供的,最近看了下xUtils的源碼,它里面也是使用AsyncTask來執(zhí)行異步任務的,它的下載也包含了斷點續(xù)傳的功能。這里我自己也使用AsyncTask也實現(xiàn)了簡單的斷點續(xù)傳的功能。

  首先說一說AsyncTask吧,先來看看AsyncTask的定義:

1 public abstract class AsyncTask
三種泛型類型分別代表“啟動任務執(zhí)行的輸入參數(shù)”、“后臺任務執(zhí)行的進度”、“后臺計算結果的類型”。在特定場合下,并不是所有類型都被使用,如果沒有被使用,可以用java.lang.Void類型代替。

一個異步任務的執(zhí)行一般包括以下幾個步驟:

1.execute(Params… params),執(zhí)行一個異步任務,需要我們在代碼中調用此方法,觸發(fā)異步任務的執(zhí)行。

2.onPreExecute(),在execute(Params… params)被調用后立即執(zhí)行,一般用來在執(zhí)行后臺任務前對UI做一些標記。

3.doInBackground(Params… params),在onPreExecute()完成后立即執(zhí)行,用于執(zhí)行較為費時的操作,此方法將接收輸入參數(shù)和返回計算結果。在執(zhí)行過程中可以調用publishProgress(Progress… values)來更新進度信息。

4.onProgressUpdate(Progress… values),在調用publishProgress(Progress… values)時,此方法被執(zhí)行,直接將進度信息更新到UI組件上。

5.onPostExecute(Result result),當后臺操作結束時,此方法將會被調用,計算結果將做為參數(shù)傳遞到此方法中,直接將結果顯示到UI組件上。

在使用的時候,有幾點需要格外注意:

1.異步任務的實例必須在UI線程中創(chuàng)建。

2.execute(Params… params)方法必須在UI線程中調用。

3.不要手動調用onPreExecute(),doInBackground(Params… params),onProgressUpdate(Progress… values),onPostExecute(Result result)這幾個方法。

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

5.一個任務實例只能執(zhí)行一次,如果執(zhí)行第二次將會拋出異常。

下面是使用AsyncTask實現(xiàn)斷點續(xù)傳的代碼:

斷點續(xù)傳的思路其實也挺簡單,首先判斷待下載的文件在本地是否存在,如果存在,則表示該文件已經下載過一部分了,只需要獲取文件當前大小即已下載大小,設置給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”>89 <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、斷點續(xù)傳核心代碼:

1 package com.bbk.lling.myapplication;23 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;1112 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;1819 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;2627 public class AsyncTaskDemoActivity extends Activity {2829 private ProgressBar progressBar;30 //下載路徑31 private String downloadPath = Environment.getExternalStorageDirectory() +32 File.separator + “download”;33 private DownloadAsyncTask downloadTask;3435 @Override36 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 @Override43 public void onClick(View v) {44 /45 一個AsyncTask只能被執(zhí)行一次,否則會拋異常46 java.lang.IllegalStateException: Cannot execute task: the task is already running.47 如果要重新開始任務的話要重新創(chuàng)建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 });5657 //暫停下載58 findViewById(R.id.end).setOnClickListener(new View.OnClickListener() {59 @Override60 public void onClick(View v) {61 if(downloadTask != null && downloadTask.getStatus() == AsyncTask.Status.RUNNING) {62 downloadTask.cancel(true);63 }64 }65 });6667 }6869 /70 下載的AsyncTask71 /72 private class DownloadAsyncTask extends AsyncTask {73 private static final String TAG = “DownloadAsyncTask”;74 private String mUrl;7576 public DownloadAsyncTask(String url) {77 this.mUrl = url;78 }7980 @Override81 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;9293 try {94 //創(chuàng)建存儲文件夾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 //創(chuàng)建文件輸出流 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 //一旦任務被取消則退出循環(huán),否則一直執(zhí)行,直到結束 120 if(isCancelled()) { 121 output.flush(); 122 return null; 123 } 124 } 125 output.flush(); 126 } else { 127 long readedSize = file.length(); //文件大小,即已下載大小 128 //設置下載的數(shù)據(jù)位置XX字節(jié)到XX字節(jié) 129 Header header_size = new BasicHeader(“Range”, “bytes=” + readedSize + “-“); 130 request.addHeader(header_size); 131 //執(zhí)行請求獲取下載輸入流 132 response = client.execute(request); 133 is = response.getEntity().getContent(); 134 //文件總大小=已下載大小+未下載大小 135 long total = readedSize + response.getEntity().getContentLength(); 136 137 //創(chuàng)建文件輸出流 138 fos = new RandomAccessFile(file, “rw”); 139 //從文件的size以后的位置開始寫入,其實也不用,直接往后寫就可以。有時候多線程下載需要用 140 fos.seek(readedSize); 141 //這里用RandomAccessFile和FileOutputStream都可以,只是使用FileOutputStream的時候要傳入第二哥參數(shù)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 }

  這樣簡單的斷點續(xù)傳功能就實現(xiàn)了,這里只是單個線程的,如果涉及多個線程同時下載,那復雜很多,后面再琢磨琢磨。

?

源碼下載:https://github.com/liuling07/MultiTaskAndThreadDownload

總結

以上是生活随笔為你收集整理的AsyncTask实现断点续传的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。