Android学习系列(2)--App自动更新之通知栏下载

这篇文章是 Android开发人员的必备知识,是我特别为大家整理和总结的,不求完美,但是有用。
1.设计思路,使用VersionCode定义为版本升级参数。
  android为我们定义版本提供了2个属性:
  1. <manifest package="com.cnblogs.tianxia.subway"
  2.       android:versionCode="1" <!--Integer类型,系统不显示给用户-->
  3.       android:versionName="1.0"<!--String类型,系统显示用户-->
  4. ></manifest>
复制代码
谷歌建议我们使用versionCode自增来表明版本升级,无论是大的改动还是小的改动,而versionName是显示用户看的软件版本,作为显示使用。所以我们选择了VersionCode作为我们定义版本升级的参数。
1.png
2.工程目录
  为了对真实项目或者企业运用有实战指导作用,我模拟一个独立的项目,工程目录设置的合理严谨一些,而不是仅仅一个demo。
  假设我们以上海地铁为项目,命名为"Subway",工程结构如下,
      
3.版本初始化和版本号的对比。
  首先定义在全局文件Global.java中定义变量localVersion和serverVersion分别存放本地版本号和服务器版本号。
  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()方法。
  1. /**
  2. * 初始化全局变量
  3. * 实际工作中这个方法中serverVersion从服务器端获取,最好在启动画面的activity中执行
  4. */
  5. public void initGlobal(){
  6.     try{
  7.         Global.localVersion = getPackageManager().getPackageInfo(getPackageName(),0).versionCode; //设置本地版本号
  8.         Global.serverVersion = 1;//假定服务器版本为2,本地版本默认是1
  9.     }catch (Exception ex){
  10.         ex.printStackTrace();
  11.     }
  12. }
复制代码
如果检测到新版本发布,提示用户是否更新,我在SubwayActivity中定义了checkVersion()方法:
  1. /**
  2. * 检查更新版本
  3. */
  4. public void checkVersion(){

  5.     if(Global.localVersion < Global.serverVersion){
  6.         //发现新版本,提示用户更新
  7.         AlertDialog.Builder alert = new AlertDialog.Builder(this);
  8.         alert.setTitle("软件升级")
  9.              .setMessage("发现新版本,建议立即更新使用.")
  10.              .setPositiveButton("更新", new DialogInterface.OnClickListener() {
  11.                  public void onClick(DialogInterface dialog, int which) {
  12.                      //开启更新服务UpdateService
  13.                      //这里为了把update更好模块化,可以传一些updateService依赖的值
  14.                      //如布局ID,资源ID,动态获取的标题,这里以app_name为例
  15.                      Intent updateIntent =new Intent(SubwayActivity.this, UpdateService.class);
  16.                      updateIntent.putExtra("titleId",R.string.app_name);
  17.                      startService(updateIntent);
  18.                  }
  19.              })
  20.              .setNegativeButton("取消",new DialogInterface.OnClickListener(){
  21.                  public void onClick(DialogInterface dialog, int which) {
  22.                      dialog.dismiss();
  23.                  }
  24.              });
  25.         alert.create().show();
  26.     }else{
  27.         //清理工作,略去
  28.         //cheanUpdateFile(),文章后面我会附上代码
  29.     }
  30. }
复制代码
如下图:
2.png
  好,我们现在把这些东西串一下:
  第一步 在SubwayApplication的onCreate()方法中执行initGlobal()初始化版本变量
  1. public void onCreate() {
  2.     super.onCreate();
  3.     initGlobal();
  4. }
复制代码
第二步 在SubwayActivity的onCreate()方法中检测版本更新checkVersion()。
  1. public void onCreate(Bundle savedInstanceState) {
  2.     super.onCreate(savedInstanceState);
  3.     setContentView(R.layout.main);
  4.     checkVersion();
  5. }
复制代码
现在入口已经打开,在checkVersion方法的第18行代码中看出,当用户点击更新,我们开启更新服务,从服务器上下载最新版本。
4.使用Service在后台从服务器端下载,完成后提示用户下载完成,并关闭服务。
  定义一个服务UpdateService.java,首先定义与下载和通知相关的变量:
  1. //标题
  2. private int titleId = 0;

  3. //文件存储
  4. private File updateDir = null;  
  5. private File updateFile = null;

  6. //通知栏
  7. private NotificationManager updateNotificationManager = null;
  8. private Notification updateNotification = null;
  9. //通知栏跳转Intent
  10. private Intent updateIntent = null;
  11. private PendingIntent updatePendingIntent = null;
复制代码
在onStartCommand()方法中准备相关的下载工作:
  1. @Override
  2. public int onStartCommand(Intent intent, int flags, int startId) {
  3.     //获取传值
  4.     titleId = intent.getIntExtra("titleId",0);
  5.     //创建文件
  6.     if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){
  7.         updateDir = new File(Environment.getExternalStorageDirectory(),Global.downloadDir);
  8.         updateFile = new File(updateDir.getPath(),getResources().getString(titleId)+".apk");
  9.     }

  10.     this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  11.     this.updateNotification = new Notification();

  12.     //设置下载过程中,点击通知栏,回到主界面
  13.     updateIntent = new Intent(this, SubwayActivity.class);
  14.     updatePendingIntent = PendingIntent.getActivity(this,0,updateIntent,0);
  15.     //设置通知栏显示内容
  16.     updateNotification.icon = R.drawable.arrow_down_float;
  17.     updateNotification.tickerText = "开始下载";
  18.     updateNotification.setLatestEventInfo(this,"上海地铁","0%",updatePendingIntent);
  19.     //发出通知
  20.     updateNotificationManager.notify(0,updateNotification);

  21.     //开启一个新的线程下载,如果使用Service同步下载,会导致ANR问题,Service本身也会阻塞
  22.     new Thread(new updateRunnable()).start();//这个是下载的重点,是下载的过程
  23.    
  24.     return super.onStartCommand(intent, flags, startId);
  25. }
复制代码
上面都是准备工作,如图:
3.png
  从代码中可以看出来,updateRunnable类才是真正下载的类,出于用户体验的考虑,这个类是我们单独一个线程后台去执行的。
  下载的过程有两个工作:1.从服务器上下载数据;2.通知用户下载的进度。
  线程通知,我们先定义一个空的updateHandler。
  1. private Handler updateHandler = new  Handler(){
  2.     @Override
  3.     public void handleMessage(Message msg) {
  4.         
  5.     }
  6. };
复制代码
再来创建updateRunnable类的真正实现:
  1. class updateRunnable implements Runnable {
  2.         Message message = updateHandler.obtainMessage();
  3.         public void run() {
  4.             message.what = DOWNLOAD_COMPLETE;
  5.             try{
  6.                 //增加权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">;
  7.                 if(!updateDir.exists()){
  8.                     updateDir.mkdirs();
  9.                 }
  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>
复制代码
下载函数的实现有很多,我这里把代码贴出来,而且我们要在下载的时候通知用户下载进度:
  1. public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
  2.             //这样的下载代码很多,我就不做过多的说明
  3.             int downloadCount = 0;
  4.             int currentSize = 0;
  5.             long totalSize = 0;
  6.             int updateTotalSize = 0;
  7.             
  8.             HttpURLConnection httpConnection = null;
  9.             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.         }
复制代码
显示下载进度,如图:
4.png
下载完成后,我们提示用户下载完成,并且可以点击安装,那么我们来补全前面的Handler吧。
先在UpdateService.java定义2个常量来表示下载状态:
  1. //下载状态
  2. private final static int DOWNLOAD_COMPLETE = 0;
  3. private final static int DOWNLOAD_FAIL = 1;
复制代码
根据下载状态处理主线程:
  1. private Handler updateHandler = new  Handler(){
  2.     @Override
  3.     public void handleMessage(Message msg) {
  4.         switch(msg.what){
  5.             case DOWNLOAD_COMPLETE:
  6.                 //点击安装PendingIntent
  7.                 Uri uri = Uri.fromFile(updateFile);
  8.                 Intent installIntent = new Intent(Intent.ACTION_VIEW);
  9.                 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. };
复制代码
下载完成,如图:
5.png
至此,文件下载并且在通知栏通知进度。
发现本人废话很多,其实几句话的事情,来来回回写了这么多,啰嗦了,后面博文我会朝着精简方面努力。
PS:前面说要附上cheanUpdateFile()的代码
  1. File updateFile = new File(Global.downloadDir,getResources().getString(R.string.app_name)+".apk");
  2. if(updateFile.exists()){
  3.    //当不需要的时候,清除之前的下载文件,避免浪费用户空间
  4.    updateFile.delete();
  5. }
复制代码
谢谢大家!!!!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值