android 文件下载

  LinearLayout progresslayout = (LinearLayout) lftr.inflate(
  R.layout.op_down_probar, null);
  layout.addView(progresslayout);
  bar = (ProgressBar) progresslayout
  .findViewById(R.id.downloadProgressBar);



  void download() {
        new Thread(runnable).start();
    }

    private void sendMsg(int flag)
    {
        Message msg = new Message();
        msg.what = flag;
        handler.sendMessage(msg);
    }
    Runnable runnable = new Runnable() {
        String rootPath = "i.work";

        @Override
        public void run() {
            
            try {

                URL url = new URL(HttpUtil.BASE_URL + "/assets/" + optiondir);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                filesize = connection.getContentLength();
                InputStream in = connection.getInputStream();
                File radio = new File(sdCardPath + rootPath + optiondir);
                radio.createNewFile();
                OutputStream out = new FileOutputStream(radio);
                byte[] buffer = new byte[1024];
                int length;
                sendMsg(0);
                do {
                    // 循环读取
                    int numread = in.read(buffer);
                    if (numread == -1) {
                        break;
                    }
                    out.write(buffer, 0, numread);
                    downloadfilesize += numread;
                    sendMsg(1);
                } while (true);
                sendMsg(2);
                out.flush();
                out.close();
                in.close();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
            case 0:
                bar.setMax(filesize);
                break;
            case 1:
                bar.setProgress(downloadfilesize);
                break;
            case 2:
                Toast.makeText(OptionsToDo.this, "文件下载完成", 1).show();
                break;
            }
        }
    };
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/downloadProgressBarLayout" >
    <ProgressBar
        android:id="@+id/downloadProgressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

 

posted @ 2014-02-12 15:05  ggaaooppeenngg  阅读(322)  评论(0编辑  收藏  举报