原始下载

一:工具类


public class NetUtils {

    public static void downloadFile(String downloadUrl,String path,int blockSize,int threadId){
        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 * (threadId + 1) - 1;
                //多线程下载  需要告诉服务器我要请求的是哪部分内容  需要写在请求头里面
                conn.setRequestProperty("Range", "bytes=" + start + "-" + end);

                Log.i(threadId + "======", "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);
                        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;
    }

}
public class DownThread extends Thread {
    private String downloadUrl = "";
    private String path;
    private int threadNum = 5;

    public DownThread(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
        float tempSize = (float) len/threadNum;
        //四舍五入---  让一个数字+0。5在四舍五入 就变成 向上取整
        int blockSize = (int) Math.round(tempSize + 0.5);

        //计算出下载块以后   创建线程执行下载操作
        for (int i = 0; i < threadNum; i++) {
            //让最后一个线程下载的大小是正好的,  总长度 - 除了最后一个块的大小和
            if(i == threadNum - 1){
                blockSize = len - blockSize * (threadNum - 1);
            }
            new DownloadTask(downloadUrl, path, blockSize, i).start();
        }


    }

}
public class DownloadTask extends Thread{
    String downloadUrl;
    String path;
    int blockSize;
    int threadId;

    public DownloadTask(String downloadUrl, String path, int blockSize, int threadId) {
        this.downloadUrl = downloadUrl;
        this.path = path;
        this.blockSize = blockSize;
        this.threadId = threadId;
    }

    @Override
    public void run() {
        NetUtils.downloadFile(downloadUrl,path,blockSize,threadId);
    }
}
public class DialogUtils {

    public static long MAX_SIZE = 0;
    public static long PROGRESS = 0;

    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 DownThread("http://gdown.baidu.com/data/wisegame/d2fbbc8e64990454/wangyiyunyinle_87.apk", context.getCacheDir() + "/hhh.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 < MAX_SIZE){
                    SystemClock.sleep(100);
                    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();
    }
}

mainactivity:
DialogUtils.showUpdataDialog(this);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值