赞
踩
Service生命周期最全面解
http://www.jianshu.com/p/8d0cde35eb10
Service服务史上最全面解析
http://www.jianshu.com/p/d963c55c3ab9
DwonloadListener.class
下载过程中的各状态进行监听和回调
public interface DownloadListener {
//下载进度
void onProgress(int progress);
//下载成功
void onSuccess();
//下载失败
void onFailed();
//下载暂停
void onPaused();
//下载取消
void onCanceled();
}
DownloadTask.class
下载类
public class DownloadTask extends AsyncTask <String,Integer,Integer>{
public static final int TYPE_SUCCES = 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 isPaused = false;
private int lastProgress;
public DownloadTask(DownloadListener listener){
//接收一个接口实现类
this.listener = listener;
}
//下载逻辑
@Override
protected Integer doInBackground(String... params) {
InputStream is = null;
//RandomAccessFile 是随机访问文件(包括读/写)的类。
//它支持对文件随机访问的读取和写入,即我们可以从指定的位置读取/写入文件数据。
//如果要想对文件内容进行操作,则可以使用RandomAccessFile类
RandomAccessFile savedFile = null;
File file = null;
try{
long downloadedLength = 0;
String downloadUrl = params[0];
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS).getPath();
file = new File(directory + fileName);
if(file.exists()){
//已下载的文件字节长度
downloadedLength = file.length();
}
//服务器文件字节长度
long contentLength = getContentLength(downloadUrl);
if(contentLength == 0){
//如果服务器文件字节长度等于0,说明下载文件有问题,下载失败
return TYPE_FAILED;
}else if(contentLength == downloadedLength){
//如果服务器文件字节长度等于已下载文件字节长度,说明已经下载完成
return TYPE_SUCCES;
}
OkHttpClient client =
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。