Android学习(58) -- xUtils之HttpUtils

来源:互联网 发布:mac系统优化工具 编辑:程序博客网 时间:2024/06/06 10:00

HttpUtils的使用

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
原创粉丝点击