Androidx学习笔记(47)--- 借助xUtils实现下载

HttpUtils本身就支持多线程断点续传,使用起来非常的方便

  • 创建HttpUtils对象

    HttpUtils http = new HttpUtils();
    
  • 下载文件

    http.download(url, //下载请求的网址
            target, //下载的数据保存路径和文件名
            true, //是否开启断点续传
            true, //如果服务器响应头中包含了文件名,那么下载完毕后自动重命名
            new RequestCallBack<File>() {//侦听下载状态
    
        //下载成功此方法调用
        @Override
        public void onSuccess(ResponseInfo<File> arg0) {
            tv.setText("下载成功" + arg0.result.getPath());
        }
    
        //下载失败此方法调用,比如文件已经下载、没有网络权限、文件访问不到,方法传入一个字符串参数告知失败原因
        @Override
        public void onFailure(HttpException arg0, String arg1) {
            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 + "%");
        }
    });

代码

public class MainActivity extends Activity {
	private TextView tv_failure;
	private TextView tv_progress;
	private ProgressBar pb;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv_failure = (TextView) findViewById(R.id.tv_failure);
		tv_progress = (TextView) findViewById(R.id.tv_progress);
		pb = (ProgressBar) findViewById(R.id.pb);
	}
	public void click(View v){
		HttpUtils utils = new HttpUtils();
		String fileName = "QQPlayer.exe";
		//确定下载地址
		String path = "http://192.168.13.13:8080/" + fileName;
		utils.download(path, //下载地址
				"sdcard/QQPlayer.exe", //文件保存路径
				true,//是否支持断点续传
				true, new RequestCallBack<File>() {
					
					//下载成功后调用
					@Override
					public void onSuccess(ResponseInfo<File> arg0) {
						Toast.makeText(MainActivity.this, arg0.result.getPath(), 0).show();
						
					}
					
					//下载失败调用
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						tv_failure.setText(arg1);
					}

					//显示进度的时候调用
					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						// TODO Auto-generated method stub
						super.onLoading(total, current, isUploading);
						pb.setMax((int)total);
						pb.setProgress((int)current);
						tv_progress.setText(current * 100 / total + "%");
					}
				});
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值