单线程下载和多线程下载

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"/>
    <Button
        android:id="@+id/simple_download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="单线程下载"/>
    <Button
        android:id="@+id/public_download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="多线程下载"/>

</LinearLayout>

class

public class MultiThread extends Thread{
    public MultiThread(long start, long end, String url, String filePath) {
        this.start = start;
        this.end = end;
        this.urlPath = url;
        this.filePath = filePath;
    }
    private int sum=0;
    private long start;
    private long end;
    private String urlPath;
    private String filePath;

    public int getSum() {
        return sum;
    }

    @Override
    public void run() {
        try {
            URL url=new URL(urlPath);
            URLConnection connection=url.openConnection();
            connection.setAllowUserInteraction(true);
            connection.setRequestProperty("Range", "bytes=" + start + "-"
                    + end);
            InputStream is= connection.getInputStream();
            byte [] array=new byte[1024];
            is.read(array);
            File file=new File(filePath);
            RandomAccessFile randomAccessFileile=new RandomAccessFile(file,"rw");
            randomAccessFileile.seek(start);
            int index=is.read(array);
            while (index!=-1){
                randomAccessFileile.write(array,0,index);
                sum+=index;
                index=is.read(array);
            }
            randomAccessFileile.close();
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

MainAvtivity

public class DownloadActivity  extends Activity{
    private Button mButtonSimpleDown;
    private ProgressBar mProgressBar;
    private Button mButtonMore;
    int length;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0x23:
                    mProgressBar.setProgress(msg.arg1*100/length);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        mProgressBar= (ProgressBar) findViewById(R.id.progressbar);
        mButtonSimpleDown= (Button) findViewById(R.id.simple_download);
        mButtonSimpleDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownTask downtask=new DownTask();
                downtask.execute("sdsa");
            }
        });
        mButtonMore= (Button) findViewById(R.id.public_download);
        mButtonMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String urlPath="http://192.168.0.30:8080/MyWebTest/music/aa.mp3";
                            URL  url = new URL(urlPath);
                            URLConnection connection=url.openConnection();
                            length=connection.getContentLength();
                            File file=new File(Environment.getExternalStorageDirectory(),"cc.mp3");
                            if(!file.exists()){
                                file.createNewFile();
                            }
                            MultiThread[] threads=new MultiThread[5];
                            for (int i=0;i<5;i++){
                                MultiThread thread=null;
                                if(i==4){
                                    thread = new MultiThread(length / 5*4, length , urlPath, file.getAbsolutePath());
                                }else {
                                    thread = new MultiThread(length / 5 * i, length / 5 * (i + 1), urlPath, file.getAbsolutePath());
                                }
                                thread.start();
                                threads[i]=thread;
                            }
                            boolean isFinish=true;

                            while(isFinish){
                                int sum=0;
                                for (MultiThread thread:threads){
                                    sum+= thread.getSum();
                                }
                                  new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            String urlPath="http://192.168.0.30:8080/MyWebTest/music/aa.mp3";
                                            URL  url = new URL(urlPath);
                                            URLConnection connection=url.openConnection();
                                            length=connection.getContentLength();
                                            File file=new File(Environment.getExternalStorageDirectory(),"cc.mp3");
                                            if(!file.exists()){
                                                file.createNewFile();
                                            }
                                            MultiThread[] threads=new MultiThread[5];
                                            for (int i=0;i<5;i++){
                                                MultiThread thread=null;
                                                if(i==4){
                                                    thread = new MultiThread(length / 5*4, length , urlPath, file.getAbsolutePath());
                                                }else {
                                                    thread = new MultiThread(length / 5 * i, length / 5 * (i + 1)-1, urlPath, file.getAbsolutePath());
                                                }
                                                thread.start();
                                                threads[i]=thread;
                                            }
                                            boolean isFinish=true;

                                            while(isFinish){
                                                int sum=0;
                                                for (MultiThread thread:threads){
                                                    sum+= thread.getSum();
                                                }
                                                Message msg=  handler.obtainMessage();
                                                msg.what=0x23;
                                                msg.arg1=sum;
                                                handler.sendMessage(msg);
                                                if(sum+10>=length){
                                                    isFinish=false;
                                                }
                                                Thread.sleep(1000);
                                            }
                                        } catch (MalformedURLException e) {
                                            e.printStackTrace();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                }).start();
                                Message msg=  handler.obtainMessage();
                                msg.what=0x23;
                                msg.arg1=sum;
                                handler.sendMessage(msg);
                                if(sum+10>=length){
                                    isFinish=false;
                                }
                                Thread.sleep(1000);
                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
            }
        });

    }


    class DownTask extends AsyncTask<String,Integer,String> {

        @Override
        protected String doInBackground(String... params) {
            try {
                URL url=new URL("http://192.168.0.30:8080/MyWebTest/music/aa.mp3");
                URLConnection connection=url.openConnection();
                int length=connection.getContentLength();
                InputStream is=connection.getInputStream();
                byte [] array=new byte[1024];
                File file=new File(Environment.getExternalStorageDirectory(),"aa.mp3");
                if (!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream os=new FileOutputStream(file);
                int index=is.read(array);
                int sum=0;
                while (index!=-1){
                    os.write(array,0,array.length);
                    sum+=index;
                    publishProgress(sum,length);
                    is.read(array);
                }
                os.close();
                os.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mProgressBar.setProgress((int) (values[0]*100.0/values[1]));
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值