long downloadSize = downloadUpdateFile("http://www.easck.com/msoft/179/1105/10753/MobileQQ1.0(Android)_Build0198.apk",updateFile);
if(downloadSize>0){
//下载成功
updateHandler.sendMessage(message);
}
}catch(Exception ex){
ex.printStackTrace();
message.what = DOWNLOAD_FAIL;
//下载失败
updateHandler.sendMessage(message);
}
}
}
</uses-permission></uses-permission>
下载函数的实现有很多,我这里把代码贴出来,而且我们要在下载的时候通知用户下载进度:
复制代码
public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
//这样的下载代码很多,我就不做过多的说明
int downloadCount = 0;
int currentSize = 0;
long totalSize = 0;
int updateTotalSize = 0;
HttpURLConnection httpConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL(downloadUrl);
httpConnection = (HttpURLConnection)url.openConnection();
httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
if(currentSize > 0) {
httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
}
httpConnection.setConnectTimeout(10000);
httpConnection.setReadTimeout(20000);
updateTotalSize = httpConnection.getContentLength();
if (httpConnection.getResponseCode() == 404) {
throw new Exception("fail!");
}
is = httpConnection.getInputStream();
fos = new FileOutputStream(saveFile, false);
byte buffer[] = new byte[4096];
int readsize = 0;
while((readsize = is.read(buffer)) > 0){
fos.write(buffer, 0, readsize);
totalSize += readsize;
//为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次
if((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>downloadCount){
downloadCount += 10;
updateNotification.setLatestEventInfo(UpdateService.this, "正在下载", (int)totalSize*100/updateTotalSize+"%", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);
}
}
} finally {
if(httpConnection != null) {
httpConnection.disconnect();
}
if(is != null) {
is.close();
}
if(fos != null) {
fos.close();
}
}
return totalSize;
}
下载完成后,我们提示用户下载完成,并且可以点击安装,那么我们来补全前面的Handler吧。










