• 通过HttpUrlConnection下载文件并显示进度条


    实现效果:

    核心下载块:


    int count = 0;
    URL url = new URL("http://hezuo.downxunlei.com/xunlei_hezuo/thunder(127891).exe");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();//建立连接
     
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    }else return;

    totalSize = connection.getContentLength();//获取文件总大小

    InputStream is = connection.getInputStream();
    OutputStream os = new FileOutputStream(
    Environment.getExternalStorageDirectory() + "/download.exe");
    int len=0;

    bar.setMax(totalSize);//设置进度条最大长度
    Log.i("xiaohong", "max" + bar.getMax());

    byte bs[] = new byte[1024];
    while ((len = is.read(bs)) != -1) {
    os.write(bs, 0, len);//写入文件
    count += len;handler.sendEmptyMessage(count);

    }
    os.flush();
    is.close();
    os.close();//最后关闭输入输出流

    //设置进度条及文本

    final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
    // TODO Auto-generated method stub
    super.handleMessage(msg);
    bar.setProgress(msg.what);
    textView.setText("进度" + String.format("%.1f", msg.what * 1f / totalSize * 100) + "%");//保留一位小数点,且需注意数据在计算时应转为浮点型!
    }
    };

  • 相关阅读:
    火狐下button标签子元素无法点击
    js里面的this指向
    (转载)http协议的Request Payload 和 Form Data 的区别
    (转载)http压缩 Content-Encoding: gzip
    函数的length属性
    Expires
    Etag 和 If-None-Match
    Mac下升级node到最新版本
    高级函数之函数绑定
    Java数据结构和算法day01 稀疏数组与队列
  • 原文地址:https://www.cnblogs.com/lzh-Linux/p/4983977.html
Copyright © 2020-2023  润新知