DownloadListener
public interface DownloadListener {
void onProgress(int progress);
void onSuccess();
void onFailed();
void onPause();
void onCanceled();
}
DownloadTask
/**
* 第一个参数表示后台任务
* 第二个为进度
* 第三个为执行结果
*/
public class DownloadTask extends AsyncTask<String, Integer, Integer>{
public static final int TYPE_SUCCESS = 0;
public static final int TYPE_FAILED = 1;
public static final int TYPE_PAUSED = 2;
public static final int TYPE_CANCELED = 3;
private DownloadListener listener;
private boolean isCanceled = false;
private boolean isPauesd = false;
private int lastProgress;
public DownloadTask(DownloadListener listener){
this.listener = listener;
}
@Override
protected Integer doInBackground(String... params) {
InputStream is = null;
RandomAccessFile savedFile = null;
File file = null;
try{
long downloadedLength = 0; //记录已下载的文件长度
String downloadUrl = params[0];
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
//sd卡的download目录
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
file = new File(directory + fileName);
if(file.exists()){
downloadedLength = file.length();
}
long contentLength = getContnetLength(downloadUrl);
if(contentLength == 0){
//文件有问题
return TYPE_FAILED;
}else if(contentLength == downloadedLength){
//已下载字节和文件总字节相等,说明下载已经完成了
return TYPE_SUCCESS;
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//告诉服务器从哪个字节开始下载
.addHeader("RANGE", "bytes=" + downloadedLength + "-")
.url(downloadUrl)
.build();
Response response = client.newCall(request).execute();
if(response !=