多线程下载

public class DialogUtils {
    public static int MAX=0;
    public static int PROGRESS=-2;
    public static void ShowUpdateProgress(final Context context){
        AlertDialog builder=new AlertDialog.Builder(context)
                .setTitle("版本有点低,请选择更新最新版本")
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        new DownloadThread("http://169.254.35.159:8080/wyq/jinritoutiao_460.apk",context.getCacheDir()+"/d.apk",4).start();
                        showDownProgress(context,context.getCacheDir()+"/d.apk");
                    }
                })
                .setNegativeButton("不用了",null)
                .show();


    }

    private static void showDownProgress(final Context context, final String fileurl) {

        final ProgressDialog dialog=new ProgressDialog(context);
        dialog.setTitle("正在更新");
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax(100);
        dialog.show();
        new AsyncTask<String, Integer, String>() {
            @SuppressLint("LongLogTag")
            @Override
            protected String doInBackground(String... strings) {
                Log.i("==========DialogUtils========", "doInBackground:+Progress: "+PROGRESS+"Max:"+MAX);
                while (PROGRESS<MAX) {
                    Log.i("==========DialogUtils========", "doInBackground:+Progress: "+PROGRESS+"Max:"+MAX);
                    SystemClock.sleep(100);
                    if (MAX > 0) {

                        publishProgress((int) (PROGRESS * 100 / MAX));
                    } else {
                        publishProgress(0);
                    }

                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                dialog.dismiss();
                File file=new File(fileurl);
                //重新给下载的文件设置权限
                String[] command = {"chmod", "777", file.getPath() };
                ProcessBuilder builder = new ProcessBuilder(command);
                try {
                    builder.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //设置跳转到系统安装页面
                Intent intent = new Intent(Intent.ACTION_VIEW);

                intent.addCategory(Intent.CATEGORY_DEFAULT);

                intent.setDataAndType(Uri.parse("file://"+fileurl),"application/vnd.android.package-archive");
                context.startActivity(intent);
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                dialog.setProgress(values[0]);
            }
        }.execute();
    }

}



public class DownloadThread extends Thread{
    private String downUrl="";
    private int ThreadNum=5;
    private String path;

    public DownloadThread(String downUrl,String path,int threadNum){
        this.downUrl=downUrl;
        this.path=path;
        this.ThreadNum=threadNum;
    }
    @SuppressLint("LongLogTag")
    @Override
    public void run() {
        super.run();

        //获取要下载文件的长度,即大小
        int fileLength = NetUtils.getFileContentLength(downUrl);
        DialogUtils.MAX=fileLength;
        Log.i("=============DownLoadThread===============", "fileLength: "+fileLength);
        int DownSize=fileLength/ThreadNum;
        for (int i=0;i<ThreadNum;i++){
            int startPosition=i*DownSize;
            if (i==ThreadNum-1) {
                DownSize=fileLength-DownSize*(ThreadNum-1);
            }
            new DownTask(DownSize,downUrl,startPosition,path).start();
        }

    }
}


public class DownTask extends Thread {
    private int DownSize;
    private String DownUrl;
    private int startPosition;
    private String path;

    public DownTask(int downSize, String downUrl, int startPosition, String path) {
        DownSize = downSize;
        DownUrl = downUrl;
        this.startPosition = startPosition;
        this.path = path;
    }

    @Override
    public void run() {
        super.run();
       NetUtils.DownLoad(DownUrl,DownSize,path,startPosition);
    }
}

public class NetUtils {

    /**
     * 获取要下的文件的长度
     * @param downloadUrl
     * @return
     */
    public static int getFileContentLength(String downloadUrl){
        int contentLength=0;
        try {
            URL url=new URL(downloadUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5000);
            con.setConnectTimeout(5000);
            //获取下载的长度
           contentLength = con.getContentLength();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  contentLength;
    }
    public static void DownLoad(String downUrl,int DownSize,String path,int startPosition){
        BufferedInputStream buffer = null;
        RandomAccessFile raf = null;
        try {
            File file=new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            URL url=new URL(downUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5000);
            con.setReadTimeout(5000);

            if (DownSize>0) {
                int endPosition=DownSize+startPosition-1;
                con.setRequestProperty("Range","bytes="+startPosition+"-"+endPosition);
            }
            int responseCode = con.getResponseCode();//获取响应码
            if (400>responseCode) {
                buffer = new BufferedInputStream(con.getInputStream());
                raf = new RandomAccessFile(file, "rwd");
                raf.seek(startPosition);
                int len=0;
                byte[] bytes=new byte[1024*8];
                while ((len=buffer.read(bytes))!=-1){
                    synchronized (NetUtils.class){
                        raf.write(bytes,0,len);
                        if (DialogUtils.PROGRESS<0) {
                            DialogUtils.PROGRESS=0;
                        }
                        DialogUtils.PROGRESS+=len;
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (buffer!=null) {
                try {
                    buffer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (raf!=null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}


  DialogUtils.ShowUpdateProgress(this);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值