下载下来的文件不能安装
用老师这种方式为什么下载下来的文件不能安装呢
用老师这种方式为什么下载下来的文件不能安装呢
2015-04-24
/**
* 下载线程
*/
class DownloadThread extends Thread {
private ThreadInfo threadInfo; // 线程信息
// public boolean isFinished = false;
public DownloadThread(ThreadInfo threadInfo) {
this.threadInfo = threadInfo;
Log.i(tag, "thread info = " + threadInfo);
}
@Override
public void run() {
URL url = null;
HttpURLConnection con = null; // http链接
RandomAccessFile accessFile = null; // 下载文件
InputStream inputStream = null; // 输入流
try {
int start = threadInfo.getStart() + threadInfo.getFinished(); // 读取文件的位置
// int startPos = blockSize * (threadId - 1);//开始位置
// int endPos = blockSize * threadId - 1;//结束位置
// start 初始化下载链接
url = new URL(threadInfo.getUrl());
con = (HttpURLConnection) url.openConnection();
con.setAllowUserInteraction(true);
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setRequestProperty("Range", "bytes=" + start + "-"
+ threadInfo.getEnd()); // 设置读取文件的位置,和结束位置
// end 初始化下载链接
// start 初始化下载到本地的文件
accessFile = new RandomAccessFile(new File(
mTaskInfo.getFilePath(), mTaskInfo.getFileName()),
"rwd");
accessFile.seek(start); // 设置开始写入的位置
// end 初始化下载到本地的文件
int responseCode = con.getResponseCode();
if ((con.getResponseCode() == HttpURLConnection.HTTP_PARTIAL)
|| (con.getResponseCode() == HttpURLConnection.HTTP_OK)) {
inputStream = con.getInputStream();
int finished = threadInfo.getFinished(); // 已经下载的长度
// int len = threadInfo.getEnd()-threadInfo.getStart();
// //本线程要下载的长度
int readLen = -1; // 读取的长度
byte[] buffer = new byte[1024 * 4];
long time = System.currentTimeMillis();
// start 读取输入流写入文件
while ((readLen = inputStream.read(buffer)) != -1) {
accessFile.write(buffer, 0, readLen);
// Log.i(tag, "readLen = " + readLen);
finished += readLen;
threadInfo.setFinished(threadInfo.getFinished()+readLen); // 设置已经下载进度
if (System.currentTimeMillis() - time > 2000) {
// Log.i(tag, "readLen = " + readLen);
notifyProgress(threadInfo.getId(), threadInfo.getFinished()); // 每隔2秒通知下载进度
time = System.currentTimeMillis();
}
// start 停止下载,保存进度
if (isPause) {
Log.i(tag,
"pause name = " + mTaskInfo.getFileName());
notifyProgress(threadInfo.getId(), threadInfo.getFinished()); // 通知下载进度
mThreadDao.updateThread(threadInfo.getUrl(),
threadInfo.getId(), threadInfo.getFinished()); // 更新数据库对应的线程信息
return;
}
// end 停止下载,保存进度
}
// end 读取输入流写入文件
// mThreadDao.updateThread(threadInfo.getUrl(),threadInfo.getId(),finished);
// isFinished = true;
// checkIsAllThreadFinished();
// broadcastFinished(threadInfo.getId(),finished);
notifyProgress(threadInfo.getId(), finished);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (accessFile != null) {
accessFile.close();
}
if (null != con) {
con.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
super.run();
}
}
举报