App自动更新之通知栏下载(转)
原文地址: http://www.cnblogs.com/qianxudetianxia/archive/2011/04/12/2010919.html#2092962
?
见证过博客园的多次升级,你也希望你的软件通过更新发布新特性通知用户吧,是的。
这篇文章是android开发人员的必备知识,是我特别为大家整理和总结的,不求完美,但是有用。?
1.设计思路,使用VersionCode定义为版本升级参数。
android为我们定义版本提供了2个属性:
2.工程目录
为了对真实项目或者企业运用有实战指导作用,我模拟一个独立的项目,工程目录设置的合理严谨一些,而不是仅仅一个demo。
假设我们以上海地铁为项目,命名为"Subway",工程结构如下,
?? ? ?
3.版本初始化和版本号的对比。
首先定义在全局文件Global.java中定义变量localVersion和serverVersion分别存放本地版本号和服务器版本号。
好,我们现在把这些东西串一下:
第一步在SubwayApplication的onCreate()方法中执行initGlobal()初始化版本变量。
从代码中可以看出来,updateRunnable类才是真正下载的类,出于用户体验的考虑,这个类是我们单独一个线程后台去执行的。
下载的过程有两个工作:1.从服务器上下载数据;2.通知用户下载的进度。
线程通知,我们先定义一个空的updateHandler。
显示下载进度,如图:

下载完成后,我们提示用户下载完成,并且可以点击安装,那么我们来补全前面的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(); }谢谢大家!!!!