多线程下载

来源:互联网 发布:php获取跳转前的url 编辑:程序博客网 时间:2024/06/05 14:43

Net包


package com.example.greendao.net;/** * Created by eh on 2017/11/11. */public class DownLoadTask extends Thread {    String downloadUrl;    String path;    int blockSize;    int startPosition;    public DownLoadTask(String downloadUrl, String path, int blockSize, int startPosition) {        this.downloadUrl = downloadUrl;        this.path = path;        this.blockSize = blockSize;        this.startPosition = startPosition;    }    @Override    public void run() {        NetUtils.downloadFile(downloadUrl,path,blockSize,startPosition);    }}


package com.example.greendao.net;import com.example.greendao.utils.Dialogutils;/** * Created by eh on 2017/11/11. */public class DownLoadThread extends Thread{    private String downloadUrl = "";    private String path;    private int threadNum = 5;    public DownLoadThread(String downloadUrl, String path) {        this.downloadUrl = downloadUrl;        this.path = path;    }    @Override    public void run() {        int len = NetUtils.getFileLength(downloadUrl);        Dialogutils.MAX_SIZE = len;        //例如  1000kb  3   333        int blockSize = len/threadNum;        //计算出下载块以后   创建线程执行下载操作        for (int i = 0; i < threadNum; i++) {            //计算开始位置            int startPosition = blockSize * i;            //让最后一个线程下载的大小是正好的,  总长度 - 除了最后一个块的大小和            if(i == threadNum - 1){                blockSize = len - blockSize * (threadNum - 1);            }            new DownLoadTask(downloadUrl, path, blockSize, startPosition).start();        }    }    public void setThreadNum(int threadNum){        this.threadNum = threadNum;    }}



package com.example.greendao.net;import android.util.Log;import com.example.greendao.utils.Dialogutils;import java.io.BufferedInputStream;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;import static android.R.attr.start;/** * Created by eh on 2017/11/11. */public class NetUtils {    public static void downloadFile(String downloadUrl, String path, int blockSize, int startPosition){        BufferedInputStream bis = null;        RandomAccessFile raf = null;        try {            File f = new File(path);            if(!f.exists()){                f.createNewFile();            }            URL url = new URL(downloadUrl);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setReadTimeout(8000);            conn.setConnectTimeout(8000);//            long start = 0;            if(blockSize > 0){//                //使用线程id来计算 当前线程的开始位置和结束位置//                start = blockSize * threadId;                long end = blockSize + startPosition - 1;                //多线程下载  需要告诉服务器我要请求的是哪部分内容  需要写在请求头里面                conn.setRequestProperty("Range", "bytes=" + start + "-" + end);                Log.i(Thread.currentThread() + "======", "bytes=" + start + "-" + end);            }            int code = conn.getResponseCode();            if(code < 400){                bis = new BufferedInputStream(conn.getInputStream());                raf = new RandomAccessFile(f, "rwd");                //                raf.seek(start);                //                int len = 0;                byte[] buff = new byte[1024 * 8];                while((len = bis.read(buff)) != -1){                    synchronized (NetUtils.class){                        raf.write(buff, 0, len);                        if (Dialogutils.PROGRESS<0){                            Dialogutils.PROGRESS=0;                        }                        Dialogutils.PROGRESS += len;                    }                }            }        } catch (Exception e) {            e.printStackTrace();        }finally {            if(bis != null){                try {                    bis.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if(raf != null){                try {                    raf.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    public static int getFileLength(String downloadUrl){        int len = 0;        try {            URL url = new URL(downloadUrl);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setReadTimeout(8000);            conn.setConnectTimeout(8000);            len = conn.getContentLength();        } catch (Exception e) {            e.printStackTrace();        }        return len;    }}


package com.example.greendao.utils;import android.app.ProgressDialog;import android.content.Context;import android.content.DialogInterface;import android.os.AsyncTask;import android.os.SystemClock;import android.support.v7.app.AlertDialog;import com.example.greendao.net.DownLoadThread;/** * Created by eh on 2017/11/11. */public class Dialogutils {    public static long MAX_SIZE = 0;    public static long PROGRESS = -2;    public static void showUpdataDialog(final Context context){        AlertDialog.Builder builder = new AlertDialog.Builder(context);        builder.setTitle("是否更新")                .setMessage("太旧了,更新吧")                .setNegativeButton("就不", null)                .setPositiveButton("可以", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialogInterface, int i) {                        new DownLoadThread("http://169.254.51.153:8080/com.taobao.taobao_161.apk", context.getCacheDir() + "/com.taobao.taobao_161.apk").start();                        showProgress(context);                    }                }).show();    }    public static void showProgress(final Context context){        final ProgressDialog pd = new ProgressDialog(context);        pd.setTitle("正在更新");        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);        pd.setMax(100);        pd.show();        new AsyncTask<String, Integer, String>(){            @Override            protected String doInBackground(String... strings) {                while (PROGRESS+1 < MAX_SIZE){                    SystemClock.sleep(1000);                    if (MAX_SIZE>0){                        publishProgress((int)(PROGRESS * 100 / MAX_SIZE));                    }                }                return null;            }            @Override            protected void onPostExecute(String s) {                super.onPostExecute(s);                pd.dismiss();            }            @Override            protected void onProgressUpdate(Integer... values) {                super.onProgressUpdate(values);                pd.setProgress(values[0]);            }        }.execute();    }}


package com.example.greendao;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import com.example.greendao.utils.Dialogutils;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Dialogutils.showUpdataDialog(this);    }}

原创粉丝点击