/**
* 下载APK的线程
*/
private Runnable mdownApkRunnable = new Runnable() {
@Override
public void run() {
try {
String apkName = "OSChinaApp_"+mUpdate.getVersionName()+".apk";
//判断是否挂载了SD卡
String storageState = Environment.getExternalStorageState();
if(storageState.equals(Environment.MEDIA_MOUNTED)){
savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/OSChina/Update/";
File file = new File(savePath);
if(!file.exists()){
file.mkdirs();
}
apkFilePath = savePath + apkName;
}
//没有挂载SD卡,无法下载文件
if(apkFilePath == null || apkFilePath == ""){
mHandler.sendEmptyMessage(DOWN_NOSDCARD);
return;
}
File ApkFile = new File(apkFilePath);
//是否已下载更新文件
if(ApkFile.exists()){
downloadDialog.dismiss();
installApk();
return;
}
//输出流,从程序输出到SD卡上
FileOutputStream fos = new FileOutputStream(ApkFile);
//从APK包的下载网址中获取输入流
URL url = new URL(apkUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
//比特数组,储存下载的数据
int count = 0;
byte buf[] = new byte[1024];
do{
/**
* 读取数据并储存到buf中
* 返回的是buf的数据长度
*/
int numread = is.read(buf);
count += numread;
progress =(int)(((float)count / length) * 100);
//更新进度
mHandler.sendEmptyMessage(DOWN_UPDATE);
if(numread <= 0){
//下载完成通知安装
mHandler.sendEmptyMessage(DOWN_OVER);
break;
}
/**
* 从buf中写数据到SD卡中
* 地址为FileOutputStream fos = new FileOutputStream(ApkFile);
*/
fos.write(buf,0,numread);
}while(!interceptFlag);//点击取消就停止下载
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
};