1.设计思路,使用VersionCode定义为版本升级参数。
  android为我们定义版本提供了2个属性:

view source print ?
1 <manifest package="com.cnblogs.tianxia.subway"
2 android:versionCode="1" <!--Integer类型,系统不显示给用户-->
3 android:versionName="1.0"<!--String类型,系统显示用户-->
4 ></manifest>

谷歌建议我们使用versionCode自增来表明版本升级,无论是大的改动还是小的改动,而versionName是显示用户看的软件版本,作为显示使用。所以我们选择了VersionCode作为我们定义版本升级的参数。

2.工程目录
  为了对真实项目或者企业运用有实战指导作用,我模拟一个独立的项目,工程目录设置的合理严谨一些,而不是仅仅一个demo。
  假设我们以上海地铁为项目,命名为"Subway",工程结构如下,

3.版本初始化和版本号的对比。
  首先定义在全局文件Global.java中定义变量localVersion和serverVersion分别存放本地版本号和服务器版本号。

view source print ?
1 public class Global {
2 //版本信息
3 public static int localVersion = 0;
4 public static int serverVersion = 0;
5 public static String downloadDir = "app/download/";
6 }

 因为本文只是重点说明升级更新,为了防止其他太多无关代码冗余其中,我直接在SubwayApplication中定义方法initGlobal()方法。

view source print ?
01 /**
02 * 初始化全局变量
03 * 实际工作中这个方法中serverVersion从服务器端获取,最好在启动画面的activity中执行
04 */
05 public void initGlobal(){
06 try{
07 Global.localVersion = getPackageManager().getPackageInfo(getPackageName(),0).versionCode; //设置本地版本号
08 Global.serverVersion = 1;//假定服务器版本为2,本地版本默认是1
09 }catch (Exception ex){
10 ex.printStackTrace();
11 }
12 }

如果检测到新版本发布,提示用户是否更新,我在SubwayActivity中定义了checkVersion()方法:

view source print ?
01 /**
02 * 检查更新版本
03 */
04 public void checkVersion(){
05
06 if(Global.localVersion < Global.serverVersion){
07 //发现新版本,提示用户更新
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) {
13 //开启更新服务UpdateService
14 //这里为了把update更好模块化,可以传一些updateService依赖的值
15 //如布局ID,资源ID,动态获取的标题,这里以app_name为例
16 Intent updateIntent =new Intent(SubwayActivity.this, UpdateService.class);
17 updateIntent.putExtra("titleId",R.string.app_name);
18 startService(updateIntent);
19 }
20 })
21 .setNegativeButton("取消",new DialogInterface.OnClickListener(){
22 public void onClick(DialogInterface dialog, int which) {
23 dialog.dismiss();
24 }
25 });
26 alert.create().show();
27 }else{
28 //清理工作,略去
29 //cheanUpdateFile(),文章后面我会附上代码
30 }
31 }

如下图:

  好,我们现在把这些东西串一下:
  第一步在SubwayApplication的onCreate()方法中执行initGlobal()初始化版本变量

view source print ?
1 public void onCreate() {
2 super.onCreate();
3 initGlobal();
4 }

第二步在SubwayActivity的onCreate()方法中检测版本更新checkVersion()。

view source print ?
1 public void onCreate(Bundle savedInstanceState) {
2 super.onCreate(savedInstanceState);
3 setContentView(R.layout.main);
4 checkVersion();
5 }

  现在入口已经打开,在checkVersion方法的第18行代码中看出,当用户点击更新,我们开启更新服务,从服务器上下载最新版本。

4.使用Service在后台从服务器端下载,完成后提示用户下载完成,并关闭服务。
  定义一个服务UpdateService.java,首先定义与下载和通知相关的变量:

view source print ?
01 //标题
02 private int titleId = 0;
03
04 //文件存储
05 private File updateDir = null;  
06 private File updateFile = null;
07
08 //通知栏
09 private NotificationManager updateNotificationManager = null;
10 private Notification updateNotification = null;
11 //通知栏跳转Intent
12 private Intent updateIntent = null;
13 private PendingIntent updatePendingIntent = null;

在onStartCommand()方法中准备相关的下载工作:

view source print ?
01 @Override
02 public int onStartCommand(Intent intent, int flags, int startId) {
03 //获取传值
04 titleId = intent.getIntExtra("titleId",0);
05 //创建文件
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");
09 }
10
11 this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
12 this.updateNotification = new Notification();
13
14 //设置下载过程中,点击通知栏,回到主界面
15 updateIntent = new Intent(this, SubwayActivity.class);
16 updatePendingIntent = PendingIntent.getActivity(this,0,updateIntent,0);
17 //设置通知栏显示内容
18 updateNotification.icon = R.drawable.arrow_down_float;
19 updateNotification.tickerText = "开始下载";
20 updateNotification.setLatestEventInfo(this,"上海地铁","0%",updatePendingIntent);
21 //发出通知
22 updateNotificationManager.notify(0,updateNotification);
23
24 //开启一个新的线程下载,如果使用Service同步下载,会导致ANR问题,Service本身也会阻塞
25 new Thread(new updateRunnable()).start();//这个是下载的重点,是下载的过程
26
27 return super.onStartCommand(intent, flags, startId);
28 }

上面都是准备工作,如图:

  从代码中可以看出来,updateRunnable类才是真正下载的类,出于用户体验的考虑,这个类是我们单独一个线程后台去执行的。
  下载的过程有两个工作:1.从服务器上下载数据;2.通知用户下载的进度。
  线程通知,我们先定义一个空的updateHandler。

view source print ?
1 private Handler updateHandler = new Handler(){
2 @Override
3 public void handleMessage(Message msg) {
4
5 }
6 };

再来创建updateRunnable类的真正实现:

view source print ?
01 class updateRunnable implements Runnable {
02 Message message = updateHandler.obtainMessage();
03 public void run() {
04 message.what = DOWNLOAD_COMPLETE;
05 try{
06 //增加权限<USES-PERMISSION android:name="android.permission.WRITE_EXTERNAL_STORAGE">;
07 if(!updateDir.exists()){
08 updateDir.mkdirs();
09 }
10 if(!updateFile.exists()){
11 updateFile.createNewFile();
12 }
13 //下载函数,以QQ为例子
14 //增加权限<USES-PERMISSION android:name="android.permission.INTERNET">;
15 long downloadSize = downloadUpdateFile("http://softfile.3g.qq.com:8080/msoft/179/1105/10753/MobileQQ1.0(Android)_Build0198.apk",updateFile);
16 if(downloadSize>0){
17 //下载成功
18 updateHandler.sendMessage(message);
19 }
20 }catch(Exception ex){
21 ex.printStackTrace();
22 message.what = DOWNLOAD_FAIL;
23 //下载失败
24 updateHandler.sendMessage(message);
25 }
26 }
27 }
28 </USES-PERMISSION></USES-PERMISSION>

下载函数的实现有很多,我这里把代码贴出来,而且我们要在下载的时候通知用户下载进度:

view source print ?
01 public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
02 //这样的下载代码很多,我就不做过多的说明
03 int downloadCount = 0;
04 int currentSize = 0;
05 long totalSize = 0;
06 int updateTotalSize = 0;
07
08 HttpURLConnection httpConnection = null;
09 InputStream is = null;
10 FileOutputStream fos = null;
11
12 try {
13 URL url = new URL(downloadUrl);
14 httpConnection = (HttpURLConnection)url.openConnection();
15 httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
16 if(currentSize > 0) {
17 httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
18 }
19 httpConnection.setConnectTimeout(10000);
20 httpConnection.setReadTimeout(20000);
21 updateTotalSize = httpConnection.getContentLength();
22 if (httpConnection.getResponseCode() == 404) {
23 throw new Exception("fail!");
24 }
25 is = httpConnection.getInputStream();
26 fos = new FileOutputStream(saveFile, false);
27 byte buffer[] = new byte[4096];
28 int readsize = 0;
29 while((readsize = is.read(buffer)) > 0){
30 fos.write(buffer, 0, readsize);
31 totalSize += readsize;
32 //为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次
33 if((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>downloadCount){
34 downloadCount += 10;
35 updateNotification.setLatestEventInfo(UpdateService.this, "正在下载", (int)totalSize*100/updateTotalSize+"%", updatePendingIntent);
36 updateNotificationManager.notify(0, updateNotification);
37 }
38 }
39 } finally {
40 if(httpConnection != null) {
41 httpConnection.disconnect();
42 }
43 if(is != null) {
44 is.close();
45 }
46 if(fos != null) {
47 fos.close();
48 }
49 }
50 return totalSize;
51 }

显示下载进度,如图:

下载完成后,我们提示用户下载完成,并且可以点击安装,那么我们来补全前面的Handler吧。
先在UpdateService.java定义2个常量来表示下载状态:

view source print ?
1 //下载状态
2 private final static int DOWNLOAD_COMPLETE = 0;
3 private final static int DOWNLOAD_FAIL = 1;

根据下载状态处理主线程:

view source print ?
01 private Handler updateHandler = new Handler(){
02 @Override
03 public void handleMessage(Message msg) {
04 switch(msg.what){
05 case DOWNLOAD_COMPLETE:
06 //点击安装PendingIntent
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);
11
12 updateNotification.defaults = Notification.DEFAULT_SOUND;//铃声提醒
13 updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent);
14 updateNotificationManager.notify(0, updateNotification);
15
16 //停止服务
17 stopService(updateIntent);
18 case DOWNLOAD_FAIL:
19 //下载失败
20 updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent);
21 updateNotificationManager.notify(0, updateNotification);
22 default:
23 stopService(updateIntent);
24 }
25 }
26 };

下载完成,如图:

至此,文件下载并且在通知栏通知进度。
发现本人废话很多,其实几句话的事情,来来回回写了这么多,啰嗦了,后面博文我会朝着精简方面努力。
PS:前面说要附上cheanUpdateFile()的代码

view source print ?
File updateFile = new File(Global.downloadDir,getResources().getString(R.string.app_name)+".apk");
if(updateFile.exists()){
//当不需要的时候,清除之前的下载文件,避免浪费用户空间
updateFile.delete();
}

谢谢大家!!!!


更多相关文章

  1. Android中MPAndroidChart自定义绘制最高点标识的方法
  2. Android(安卓)Notification 用法的4种形式
  3. android Fragment与Activity交互,互相发数据(附图详解)
  4. Android探索之旅 | Android(安卓)Studio自定义文件类头
  5. Android定制ListView的界面(使用继承自ArrayAdapter的自定义适配
  6. 安卓开发笔记(六)—— SQLite数据库与ContentProvider的使用
  7. Android(安卓)ApiDemo分析(八)
  8. Android(安卓)Activity 和 Task 设计指导(SDK)
  9. 自定义View系列教程07--详解ViewGroup分发Touch事件

随机推荐

  1. android动态修改横竖屏
  2. 近日微软呼吁欧盟对谷歌Android系统展开
  3. A014-values资源
  4. Android 全屏与沉浸式
  5. react native android
  6. 配置flutter --Android license status u
  7. Android 的OpenGL ES与EGL
  8. Android MediaRecorder系统结构
  9. Android中Dialog的使用
  10. Ubuntu Android NDK环境的配置