多线程下载及安装

数据请求类
public class DownLoadUtils {
    public static void setNet(String baseUrl, String path,int blockSize,int startPosition){
        RandomAccessFile raf=null;
        BufferedInputStream bis=null;
        try {
            File f=new File(path);
            if(!f.exists()){
                f.createNewFile();
            }
            URL url=new URL(baseUrl);
            HttpURLConnection con=(HttpURLConnection) url.openConnection();
            con.setReadTimeout(5000);
            con.setConnectTimeout(5000);
            if(blockSize>0){
                long end=blockSize+startPosition-1;
                con.setRequestProperty("Range","bytes="+startPosition+"-"+end);
                Log.i("--------------", "setNet: "+startPosition+"-"+end);
            }

            int code = con.getResponseCode();
            if(code<400){
                bis = new BufferedInputStream(con.getInputStream());
                raf=new RandomAccessFile(f,"rwd");
                raf.seek(startPosition);
                int len=0;
                byte[] buff=new byte[1024*8];
                while ((len=bis.read(buff))!=-1){
                    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 baseUrl){
        int length=0;
        try {
            URL url=new URL(baseUrl);
            HttpURLConnection con=(HttpURLConnection) url.openConnection();
            con.setReadTimeout(5000);
            length=con.getContentLength();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length;
    }
}
数据赋值类
public class DownTask extends Thread {
    String downloadUrl;
    String path;
    int blockSize;
    int startPosition;

    public DownTask(String downloadUrl, String path, int blockSize, int startPosition) {
        this.downloadUrl = downloadUrl;
        this.path = path;
        this.blockSize = blockSize;
        this.startPosition = startPosition;
    }

    @Override
    public void run() {
        DownLoadUtils.setNet(downloadUrl,path,blockSize,startPosition);
    }
}
设置线程类
public class DownThread extends Thread {
    private  String baseurl="";
    private String path;
    private  int threadNum=5;
    int start;
    int end;
    public DownThread(String baseurl, String path) {
        this.baseurl = baseurl;
        this.path = path;
    }

    @Override
    public void run() {
        int len=DownLoadUtils.getFileLength(baseurl);
        Log.i("----len--------", "run: len"+len);
        DialogUtils.MAX=len;
        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 DownTask(baseurl,path,blockSize,startPosition).start();
        }
    }
}
alertAialog类及下载
public class DialogUtils{
    public static  long MAX =0 ;
    public static  long PROGRESS = -2;
    public  void getDialog(final Context context){
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("发现新版本");
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setMessage("最新版本:V1.0.1.1686");
        builder.setMessage("新版本大小:11.79MB");
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                http://169.254.154.213:8080/QQ.apk

                new DownThread("http://169.254.51.153:8080/com.taobao.taobao_161.apk", context.getCacheDir()+"/com.taobao.taobao_161.apk").start();
//                new DownThread("http://169.254.51.153:8080/app-release.apk",context.getCacheDir()+"/app-release.apk").start();
                showProgress(context);
            }
        });

        builder.setNegativeButton("以后在说",null);
        builder.show();
    }

    public  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... params) {
                while (PROGRESS+1<MAX){
//                    SystemClock.sleep(10);
                    if(MAX>0){
                        publishProgress((int)(PROGRESS * 100 / MAX));
                    }
                };
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                pd.dismiss();
                installApp(context);
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
//                Log.i("--onProgressUpdate---", "onProgressUpdate: "+values[0]);
                pd.setProgress(values[0]);
            }
        }.execute();
    }
    private  void installApp(Context con) {
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//sd 卡已挂载
            //获取外部存储(SD 卡)根路径 我的模拟器是:/storage/emulated/0
//            String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator;
            String path =con.getCacheDir()+"/";

            //apk 文件 放在 SD 卡的 /demos/data/ 下,名称是 JianShu-1.11.1.apk
            File targetFile = new File(path ,"com.taobao.taobao_161.apk");
//            Log.i("11111111111111111", "getDialog: "+targetFile);
//            if (targetFile.exists()) {//先判断文件是否已存在
                Log.i("--","targetFile: " + targetFile.getPath());
                String[] s=new String[]{"chmod","777",targetFile.getPath()};
                ProcessBuilder builder=new ProcessBuilder(s);
                try {
                    builder.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //Log.i(TAG,"Uri: " + Uri.fromFile(targetFile));
                //1. 创建 Intent 并设置 action
                Intent intent = new Intent(Intent.ACTION_VIEW);
                //2. 设置 category
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                //添加 flag ,不记得在哪里看到的,说是解决:有些机器上不能成功跳转的问题
                //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //3. 设置 data  type
                intent.setDataAndType(Uri.fromFile(targetFile),"application/vnd.android.package-archive");
                //3. 设置 data  type (效果和上面一样)
                //intent.setDataAndType(Uri.parse("file://" + targetFile.getPath()),"application/vnd.android.package-archive");
                //4. 启动 activity
                con.startActivity(intent);

//            }else {
//                Toast.makeText(getApplicationContext(), "apk 文件不存在",Toast.LENGTH_SHORT).show();
//                Log.i("---", "installApp: "+"文件不存在");
//            }
//        }
    }

}
mainActivity
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DialogUtils dialogUtils=new DialogUtils();
        dialogUtils.getDialog(this);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值