/** 开始下载文件到SD卡 */ private synchronized void startDownloadToSd(DownTask task, String urlDown) { try { // 打开连接 URL url = new URL(urlDown); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); // 创建本地文件 StringBuilder downFilePath = new StringBuilder(Util.getSDPath()).append("/").append("zckj_down"); File file = new File(downFilePath.toString()); if (!file.exists()) { file.mkdirs(); } downFilePath.append("/").append(task.getDownFileName()); file = new File(downFilePath.toString()); file.createNewFile(); // 打开写入流 FileOutputStream fileOut = new FileOutputStream(file); BufferedOutputStream bufferOut = new BufferedOutputStream(fileOut); int BUFFER_SIZE = 4096; // //解决编码问题,如地址包含空格,中文等 // String strUrl = Uri.encode(urlDown, "utf-8") // .replaceAll("%3A", ":").replaceAll("%2F", "/"); int fileLength = urlConnection.getContentLength(); int downCount = 0; byte[] readBuffer = new byte[BUFFER_SIZE]; int count; long startTimeSpeed = System.currentTimeMillis(); // 保存开始下载的时间,用于计算下载速度 long startTime = startTimeSpeed; long speed = 0; // 速率 long readSize = 0; // 一个计速周期内,读取的数据大小 while ((count = inputStream.read(readBuffer, 0, BUFFER_SIZE)) != -1) { // 开始读写数据 bufferOut.write(readBuffer, 0, count); downCount += count; long time = System.currentTimeMillis(); if ((time - startTimeSpeed) <= 300) { // 计算速率的时间间隔 readSize += count; } else { speed = (readSize * 1000) / (time - startTimeSpeed); readSize = 0; startTimeSpeed = time; } downloadCallback.onDownProgress(speed, downCount * 100 / fileLength); } downloadCallback.onDownEnd( task, urlDown, file.getPath(), (System.currentTimeMillis() - startTime) / 1000); if (task.isInstall()) { if (!CmdUtil.installApk(file.getPath())) { // 静态安装失败,调用手动安装 downloadCallback.onDownError("静默安装失败,调用手动安装..."); CmdUtil.startInstallApk(SocketService.service, file); } else { downloadCallback.onDownError("静默安装成功."); } } curTask = null; bufferOut.flush(); bufferOut.close(); inputStream.close(); urlConnection.disconnect(); } catch (Exception e) { // 异常Exception e.printStackTrace(); downloadCallback.onDownError(e.toString()); curTask = null; } }