手机端多线程下载

文件来源于在 imooc 网站的学习视频,安装视频敲写出来的,。
由于用到了,。多线程下载,利用线程池的方式,不是全部下载逻辑自己书写的,代码简单好用,所以分享出来,参考参考

public class Download {

    /** * 创建线程池 */
    private Executor threadPool = Executors.newFixedThreadPool(3);
    private Handler handler;
    public Download(Handler handler) {
        this.handler = handler;
    }
    static class DownLoadRunnable implements Runnable {

        private String url;
        private String fileName;
        private long start;
        private long end;


        private Handler handler;

        public DownLoadRunnable(String url, String fileName, long start, long end, Handler handler) {

            this.url = url;
            this.fileName = fileName;
            this.start = start;
            this.end = end;
            this.handler = handler;
        }

        @Override
        public void run() {

            try {
                URL httpurl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();

                conn.setReadTimeout(5000);
                conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
                conn.setRequestMethod("GET");

                RandomAccessFile access = new RandomAccessFile(
                        new File(fileName), "rwd"
                );
                access.seek(start);

                InputStream in = conn.getInputStream();
                byte[] b = new byte[1024 * 4];
                int len = 0;
                while ((len = in.read(b)) != -1) {
                    access.write(b, 0, len);
                }


                if (access != null) {
                    access.close();

                }
                if (in != null) {
                    in.close();
                }

                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);

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

        }
    }

    public void dowmLoadFile(String url) {
        try {
            URL httpurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();

            conn.setReadTimeout(5000);

            conn.setRequestMethod("GET");
            int count = conn.getContentLength();
            int block = count / 3;

            String fileName = getFileName(url);//拿到文件名
            System.out.println("======= "+fileName+" =======");

            File parent = Environment.getExternalStorageDirectory();
            System.out.println(parent.toString()+"/"+fileName+"====111=======");
            File fileDownLoad = new File(parent, fileName);
            /** * */
            for (int i = 0; i < 3; i++) {
                long start = i * block;
                long end = (i + 1) * block - 1;
                //最后一个进程,要下载一下全部的
                if (i == 2) {
                    end = count;
                }
                DownLoadRunnable runnable =
                        new DownLoadRunnable(
                                url, fileDownLoad.getAbsolutePath()
                                , start, end,handler);
                threadPool.execute(runnable);

            }

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public String getFileName(String url) {

        return url.substring(url.lastIndexOf("/") + 1);
    }

}
   private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int result = msg.what;
            count += result;
            if (count == 3) {
                textView.setText("downlaod success");

                String laoding = Environment.getExternalStorageDirectory().toString() + "/70.jpg";
                Drawable d = Drawable.createFromPath(laoding);

                imageView.setImageDrawable(d);
                System.out.println(laoding+"===2222====");

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button1);
        textView = (TextView) findViewById(R.id.textView);
        imageView = (ImageView) findViewById(R.id.imageView);
        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, uploadActivity.class);
                startActivity(intent);
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        Download load = new Download(handler);
                        load.dowmLoadFile("http://img15.3lian.com/2015/f2/50/d/70.jpg");

                    }
                }.start();
            }
        });

你可能感兴趣的:(android)