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吧。
先在UpdateService.java定义2个常量来表示下载状态:
//下载状态private final static int DOWNLOAD_COMPLETE = 0;private final static int DOWNLOAD_FAIL = 1;
根据下载状态处理主线程:
private Handler updateHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch(msg.what){ case DOWNLOAD_COMPLETE: //点击安装PendingIntent Uri uri = Uri.fromFile(updateFile); Intent installIntent = new Intent(Intent.ACTION_VIEW); installIntent.setDataAndType(uri, "application/vnd.android.package-archive"); updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0); updateNotification.defaults = Notification.DEFAULT_SOUND;//铃声提醒 updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent); updateNotificationManager.notify(0, updateNotification); //停止服务 stopService(updateIntent); case DOWNLOAD_FAIL: //下载失败 updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent); updateNotificationManager.notify(0, updateNotification); default: stopService(updateIntent); } }};
下载完成,如图:
至此,文件下载并且在通知栏通知进度。
发现本人废话很多,其实几句话的事情,来来回回写了这么多,啰嗦了,后面博文我会朝着精简方面努力。
PS:前面说要附上
cheanUpdateFile()的代码File updateFile = new File(Global.downloadDir,getResources().getString(R.string.app_name)+".apk");if(updateFile.exists()){ //当不需要的时候,清除之前的下载文件,避免浪费用户空间 updateFile.delete(); }
谢谢大家!!!!