zoukankan      html  css  js  c++  java
  • 通过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) + "%");//保留一位小数点,且需注意数据在计算时应转为浮点型!
    }
    };

  • 相关阅读:
    WTL之CAppModule
    WTL之窗口子类化
    专业的日志系统该包含什么?
    ATL之什么是套间
    Java线程新特征之同步
    Java之用句柄操作对象
    Android之Application Fundamentals
    Android之Dev Guide
    一些思考
    WTL之窗口超类化(父类化)
  • 原文地址:https://www.cnblogs.com/lzh-Linux/p/4983977.html
Copyright © 2011-2022 走看看