多线程下载以及断点续传

public class MainActivity extends AppCompatActivity {

    private ProgressBar pb;
    private TextView tv_info;
    private boolean flag = false;  //是否在下载
    private Button bt_download;
    private Button bt_pause;
    protected static final int SET_MAX = 0;
    public static final int UPDATE_VIEW = 1;
    private static final int threadsize = 3;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SET_MAX:
                    int mlength = msg.arg1;
                    pb.setMax(mlength);
                    break;
                case UPDATE_VIEW:
                    int len = msg.arg1;
                    pb.setProgress(pb.getProgress()+len);
                    //获取进度的最大值
                    int max = pb.getMax();
                    //获取已经下载的数据量
                    int progress = pb.getProgress();
                    int i = (progress * 100) / max;
                    tv_info.setText("下载:"+i+"%");
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_info = (TextView) findViewById(R.id.tv_info);
        pb = (ProgressBar) findViewById(R.id.pb);
        bt_download = (Button) findViewById(R.id.bt_download);
        bt_pause = (Button) findViewById(R.id.bt_pause);

    }

    public void download(View v) {
        flag = true;
        bt_download.setEnabled(false);
        bt_pause.setEnabled(true);
        new Thread() {
            @Override
            public void run() {
                super.run();
                HttpClient client = new DefaultHttpClient();
                String url = "http://pic1.win4000.com/pic/1/95/3a4f1407788.jpg";
                HttpHead head = new HttpHead(url);
                try {
                    HttpResponse response = client.execute(head);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        Header[] headers = response.getHeaders("Content-Length");
                        String value = headers[0].getValue();
                        //获取服务器上文件的大小
                        int mlength = Integer.parseInt(value);
                        Log.i("aaa", "   mlength" + mlength);
                        //设置进度条的最大值
                        Message message = Message.obtain(handler, SET_MAX, mlength, 0);
                        message.sendToTarget();
                        //处理下载记录文件 用于保存每条线程下载记录 创建出来
                        for (int threadid = 0; threadid < threadsize; threadid++) {
                            File file = new File(Environment.getExternalStorageDirectory(), threadid + ".txt");
                            //判断文件是否存在
                            if (!file.exists()) {
                                file.createNewFile();
                            }
                        }
                        //在sdcard创建和服务器上一样大小的文件
                        String name = getfileName(url);
                        File file = new File(Environment.getExternalStorageDirectory(), name);
                        //随机访问文件
                        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");
                        //设置文件大小
                        randomAccessFile.setLength(mlength);
                        //关闭
                        randomAccessFile.close();

                        //计算每条现成的下载量
                        int black = (mlength % threadsize == 0) ? (mlength / threadsize) : (mlength / threadsize + 1);
                        //开启线程进行下载
                        for (int threadid = 0; threadid < threadsize; threadid++) {
                            new DownLoadThread(threadid, url, file, black).start();
                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public class DownLoadThread extends Thread {
        int threadid;
        String url;
        File file;
        int black;
        private int start;
        private final int end;

        public DownLoadThread(int threadid, String url, File file, int black) {
            this.threadid = threadid;
            this.url = url;
            this.file = file;
            this.black = black;
            start = threadid * black;
            end = (threadid + 1) * black - 1;
            //读取该条线程原来的下载记录 先读取每条线程下载记录再下载
            int info = 0;
            try {
                info = readDownLoadInfo(threadid);
                //修改下载的开始位置
                start += info;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void run() {
            super.run();
            try {
                RandomAccessFile raf=new RandomAccessFile(file,"rwd");
                //跳转到起始位置
                raf.seek(start);

                HttpClient client=new DefaultHttpClient();
                HttpGet result=new HttpGet(url);
                //添加请求头
                result.addHeader("Range","bytes"+start+"-"+end);
                HttpResponse response = client.execute(result);
                if(response.getStatusLine().getStatusCode()==200){
                    InputStream inputStream = response.getEntity().getContent();
                    byte[] b=new byte[1024];
                    int len=0;
                    while((len=inputStream.read(b))!=1){
                        //如果暂停下载,就直接return
                        if(!flag){
                            return;
                        }
                        //写数据
                        raf.write(b,0,len);
                        //读取原来数据的下载量
                        int readloadInfo = readDownLoadInfo(threadid);
                        //计算最新的下载量
                        int nowinfo = readloadInfo + len;
                        //文件 更新下载记录
                        updateDownloadInfo(threadid, nowinfo);
                        //更新进度条
                        Message obtain = Message.obtain(handler, UPDATE_VIEW, len, 0);
                        obtain.sendToTarget();

                    }
                    raf.close();
                    inputStream.close();
                    Log.i("aaa", "第"+threadid+"条线程下载完成");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void updateDownloadInfo(int threadid, int nowinfo) {
        File file=new File(Environment.getExternalStorageDirectory(),threadid+".txt");
        try {
            FileWriter fw=new FileWriter(file);
            fw.write(nowinfo+"");
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int readDownLoadInfo(int threadid) throws Exception {
        //下载记录的文件
        File file = new File(Environment.getExternalStorageDirectory(), threadid + ".txt");

        BufferedReader br = new BufferedReader(new FileReader(file));
        String content = br.readLine();
        int downlen = 0;
        if (!TextUtils.isEmpty(content)) {
            downlen = Integer.parseInt(content);
        }
        br.close();
        return downlen;
    }

    private String getfileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public void pause(View v) {
        flag = false;
        bt_download.setEnabled(true);
        bt_pause.setEnabled(false);
    }

}


布局

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载地址" />

    <EditText
        android:id="@+id/et_path"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="http://192.168.190.1:8080/08web/tokhot4.JPG" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/bt_download"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="download"
            android:text="下载" />

        <Button
            android:id="@+id/bt_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:onClick="pause"
            android:text="暂停" />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/pb"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_info"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="下载:0%" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值