Android版本更新下载apk文件到sd卡

    private void downLoadApk(final String downURL, final String appName){
        final ProgressDialog pd = new ProgressDialog(this);
        //必须一直下载完,不可取消
        pd.setCancelable(false);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载安装包");
//        pd.setTitle("版本更新");
        pd.show();

        Thread t = new Thread(){
            @Override
            public void run() {
                try {
                    File file = downloadFile(downURL, appName, pd);

                    sleep(1000);
                    // 结束掉进度条对话框
                    pd.dismiss();

                    if (file!=null){
                        installApk(file);
                    } else {
                        Toast.makeText(BrowserActivity.this, "更新包无法下载", Toast.LENGTH_LONG).show();
                    }

                } catch (Exception e) {
                    pd.dismiss();

                }
            }
        };

        t.start();
    }

    private File downloadFile(String path,String appName ,ProgressDialog pd) throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            String fileName = Environment.getExternalStorageDirectory()+ "/cuair/" + appName+".apk";
            File file = new File(fileName);
            // 目录不存在创建目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                // 获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    /**
     * 安装apk
     */
    private void installApk(File file) {
        Uri fileUri = Uri.fromFile(file);
        Intent it = new Intent();
        it.setAction(Intent.ACTION_VIEW);
        it.setDataAndType(fileUri, "application/vnd.android.package-archive");
        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 防止打不开应用
        it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(it);
    }

猜你喜欢

转载自blog.csdn.net/chenkaisq/article/details/80815061