见证过博客园的多次升级,你也希望你的软件通过更新发布新特性通知用户吧,是的。
这篇文章是android开发人员的必备知识,是我特别为大家整理和总结的,不求完美,但是有用。
1.设计思路,使用VersionCode定义为版本升级参数。
android为我们定义版本提供了2个属性:
1 |
<manifest package="com.cnblogs.tianxia.subway" |
2 |
android:versionCode="1" |
3 |
android:versionName="1.0" |
谷歌建议我们使用versionCode自增来表明版本升级,无论是大的改动还是小的改动,而versionName是显示用户看的软件版本,作为显示使用。所以我们选择了VersionCode作为我们定义版本升级的参数。
2.工程目录
为了对真实项目或者企业运用有实战指导作用,我模拟一个独立的项目,工程目录设置的合理严谨一些,而不是仅仅一个demo。
假设我们以上海地铁为项目,命名为"Subway",工程结构如下,

3.版本初始化和版本号的对比。
首先定义在全局文件Global.java中定义变量localVersion和serverVersion分别存放本地版本号和服务器版本号。
3 |
public static int localVersion = 0; |
4 |
public static int serverVersion = 0; |
5 |
public static String downloadDir = "app/download/"; |
因为本文只是重点说明升级更新,为了防止其他太多无关代码冗余其中,我直接在SubwayApplication中定义方法initGlobal()方法。
03 |
* 实际工作中这个方法中serverVersion从服务器端获取,最好在启动画面的activity中执行 |
05 |
public void initGlobal(){ |
07 |
Global.localVersion = getPackageManager().getPackageInfo(getPackageName(),0).versionCode; |
08 |
Global.serverVersion = 1; |
09 |
}catch (Exception ex){ |
如果检测到新版本发布,提示用户是否更新,我在SubwayActivity中定义了checkVersion()方法:
04 |
public void checkVersion(){ |
06 |
if(Global.localVersion < Global.serverVersion){ |
08 |
AlertDialog.Builder alert = new AlertDialog.Builder(this); |
09 |
alert.setTitle("软件升级") |
10 |
.setMessage("发现新版本,建议立即更新使用.") |
11 |
.setPositiveButton("更新", new DialogInterface.OnClickListener() { |
12 |
public void onClick(DialogInterface dialog, int which) { |
16 |
Intent updateIntent =new Intent(SubwayActivity.this, UpdateService.class); |
17 |
updateIntent.putExtra("titleId",R.string.app_name); |
18 |
startService(updateIntent); |
21 |
.setNegativeButton("取消",new DialogInterface.OnClickListener(){ |
22 |
public void onClick(DialogInterface dialog, int which) { |
26 |
alert.create().show(); |
如下图:

好,我们现在把这些东西串一下:
第一步在SubwayApplication的onCreate()方法中执行initGlobal()初始化版本变量。
1 |
public void onCreate() { |
第二步在SubwayActivity的onCreate()方法中检测版本更新checkVersion()。
1 |
public void onCreate(Bundle savedInstanceState) { |
2 |
super.onCreate(savedInstanceState); |
3 |
setContentView(R.layout.main); |
现在入口已经打开,在checkVersion方法的第18行代码中看出,当用户点击更新,我们开启更新服务,从服务器上下载最新版本。
4.使用Service在后台从服务器端下载,完成后提示用户下载完成,并关闭服务。
定义一个服务UpdateService.java,首先定义与下载和通知相关的变量:
02 |
private int titleId = 0; |
05 |
private File updateDir = null; |
06 |
private File updateFile = null; |
09 |
private NotificationManager updateNotificationManager = null; |
10 |
private Notification updateNotification = null; |
12 |
private Intent updateIntent = null; |
13 |
private PendingIntent updatePendingIntent = null; |
在onStartCommand()方法中准备相关的下载工作:
02 |
public int onStartCommand(Intent intent, int flags, int startId) { |
04 |
titleId = intent.getIntExtra("titleId",0); |
06 |
if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){ |
07 |
updateDir = new File(Environment.getExternalStorageDirectory(),Global.downloadDir); |
08 |
updateFile = new File(updateDir.getPath(),getResources().getString(titleId)+".apk"); |
11 |
this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); |
12 |
this.updateNotification = new Notification(); |
15 |
updateIntent = new Intent(this, SubwayActivity.class); |
16 |
updatePendingIntent = PendingIntent.getActivity(this,0,updateIntent,0); |
18 |
updateNotification.icon = R.drawable.arrow_down_float; |
19 |
updateNotification.tickerText = "开始下载"; |
20 |
updateNotification.setLatestEventInfo(this,"上海地铁","0%",updatePendingIntent); |
22 |
updateNotificationManager.notify(0,updateNotification); |
25 |
new Thread(new updateRunnable()).start(); |
27 |
return super.onStartCommand(intent, flags, startId); |
上面都是准备工作,如图:

从代码中可以看出来,updateRunnable类才是真正下载的类,出于用户体验的考虑,这个类是我们单独一个线程后台去执行的。
下载的过程有两个工作:1.从服务器上下载数据;2.通知用户下载的进度。
线程通知,我们先定义一个空的updateHandler。
1 |
private Handler updateHandler = new Handler(){ |
3 |
public void handleMessage(Message msg) { |
再来创建updateRunnable类的真正实现:
01 |
class updateRunnable implements Runnable { |
02 |
Message message = updateHandler.obtainMessage(); |
04 |
message.what = DOWNLOAD_COMPLETE; |
07 |
if(!updateDir.exists()){ |
10 |
if(!updateFile.exists()){ |
11 |
updateFile.createNewFile(); |
18 |
updateHandler.sendMessage(message); |
22 |
message.what = DOWNLOAD_FAIL; |
24 |
updateHandler.sendMessage(message); |
28 |
</uses-permission></uses-permission> |
下载函数的实现有很多,我这里把代码贴出来,而且我们要在下载的时候通知用户下载进度:
01 |
public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception { |
03 |
int downloadCount = 0; |
06 |
int updateTotalSize = 0; |
08 |
HttpURLConnection httpConnection = null; |
09 |
InputStream is = null; |
10 |
FileOutputStream fos = null; |
13 |
URL url = new URL(downloadUrl); |
14 |
httpConnection = (HttpURLConnection)url.openConnection(); |
15 |
httpConnection.setRequestProperty("User-Agent", "PacificHttpClient"); |
17 |
httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-"); |
19 |
httpConnection.setConnectTimeout(10000); |
20 |
httpConnection.setReadTimeout(20000); |
21 |
updateTotalSize = httpConnection.getContentLength(); |
22 |
if (httpConnection.getResponseCode() == 404) { |
23 |
throw new Exception("fail!"); |
25 |
is = httpConnection.getInputStream(); |
26 |
fos = new FileOutputStream(saveFile, false); |
27 |
byte buffer[] = new byte[4096]; |
29 |
while((readsize = is.read(buffer)) > 0){ |
30 |
fos.write(buffer, 0, readsize); |
31 |
totalSize += readsize; |
33 |
if((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>downloadCount){ |
35 |
updateNotification.setLatestEventInfo(UpdateService.this, "正在下载", (int)totalSize*100/updateTotalSize+"%", updatePendingIntent); |
36 |
updateNotificationManager.notify(0, updateNotification); |
40 |
if(httpConnection != null) { |
41 |
httpConnection.disconnect(); |
显示下载进度,如图:

下载完成后,我们提示用户下载完成,并且可以点击安装,那么我们来补全前面的Handler吧。
先在UpdateService.java定义2个常量来表示下载状态:
2 |
private final static int DOWNLOAD_COMPLETE = 0; |
3 |
private final static int DOWNLOAD_FAIL = 1; |
根据下载状态处理主线程:
01 |
private Handler updateHandler = new Handler(){ |
03 |
public void handleMessage(Message msg) { |
05 |
case DOWNLOAD_COMPLETE: |
07 |
Uri uri = Uri.fromFile(updateFile); |
08 |
Intent installIntent = new Intent(Intent.ACTION_VIEW); |
09 |
installIntent.setDataAndType(uri, "application/vnd.android.package-archive"); |
10 |
updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0); |
12 |
updateNotification.defaults = Notification.DEFAULT_SOUND; |
13 |
updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent); |
14 |
updateNotificationManager.notify(0, updateNotification); |
17 |
stopService(updateIntent); |
20 |
updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent); |
21 |
updateNotificationManager.notify(0, updateNotification); |
23 |
stopService(updateIntent); |
下载完成,如图:

至此,文件下载并且在通知栏通知进度。
发现本人废话很多,其实几句话的事情,来来回回写了这么多,啰嗦了,后面博文我会朝着精简方面努力。
PS:前面说要附上cheanUpdateFile()的代码
File updateFile = new File(Global.downloadDir,getResources().getString(R.string.app_name)+".apk"); |
}