在了解了java和Android的多线程断点续传之后,再来介绍一个github上的开源库HttpUtils。
这个库本身有许多功能,这里只介绍下载相关的部分。库地址:https://github.com/wyouflf/xUtils
也可以直接到github上查看,上面的介绍也很详细。
下面直接上代码,主要部分都添加了注释。
package test.multdownload;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.fc.rssreader.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
public class HttpUtilsActivity extends Activity {
public String url = "http://dldir1.qq.com/qqfile/qq/QQ7.2/14810/QQ7.2.exe";
// public String url = "http://hiphotos.baidu.com/240728057/pic/item/6a50e38242aad8f60cf4d2b3.jpg";
public String target = "sdcard/QQ7.2.exe";
private ProgressBar pb;
private TextView tv_progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_utils);
pb = (ProgressBar) findViewById(R.id.pb);
tv_progress = (TextView) findViewById(R.id.tv_progress);
}
public void click(View v) {
HttpUtils http = new HttpUtils();
HttpHandler handler = http.download(url,// 请求的地址
target, // 下载文件保存的位置
true, // 是否断点续传
true,// 如果响应头可以拿到文件名,那么下载完成后自动重命名
new RequestCallBack<File>() {
//下载完成后调用此方法
@Override
public void onSuccess(ResponseInfo<File> arg0) {
Toast.makeText(HttpUtilsActivity.this,
arg0.result.getPath(), Toast.LENGTH_SHORT).show();
}
//下载失败调用此方法
@Override
public void onFailure(HttpException arg0, String arg1) {
TextView tv = (TextView) findViewById(R.id.tv_status);
tv.setText(arg1);
}
//用于刷新进度条
@Override
public void onLoading(long total, long current,
boolean isUploading) {
super.onLoading(total, current, isUploading);
pb.setMax((int) total);
pb.setProgress((int) current);
tv_progress.setText(current * 100 / total + "%");
}
});
}
}
不得不说现在的开源库真的很厉害,在自己写的下载程序中大约200行,而且功能相当简陋,而使用开源库实现的主体部分只有20行左右,功能完善使用方便而且没有bug。