这篇文章是 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作为我们定义版本升级的参数。 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. }
复制代码 如下图:

  好,我们现在把这些东西串一下:
  第一步 在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. return super.onStartCommand(intent, flags, startId);
  24. }
复制代码 上面都是准备工作,如图:

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

  4. }
  5. };
复制代码 再来创建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. HttpURLConnection httpConnection = null;
  8. InputStream is = null;
  9. FileOutputStream fos = null;

  10. try {
  11. URL url = new URL(downloadUrl);
  12. httpConnection = (HttpURLConnection)url.openConnection();
  13. httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
  14. if(currentSize > 0) {
  15. httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
  16. }
  17. httpConnection.setConnectTimeout(10000);
  18. httpConnection.setReadTimeout(20000);
  19. updateTotalSize = httpConnection.getContentLength();
  20. if (httpConnection.getResponseCode() == 404) {
  21. throw new Exception("fail!");
  22. }
  23. is = httpConnection.getInputStream();
  24. fos = new FileOutputStream(saveFile, false);
  25. byte buffer[] = new byte[4096];
  26. int readsize = 0;
  27. while((readsize = is.read(buffer)) > 0){
  28. fos.write(buffer, 0, readsize);
  29. totalSize += readsize;
  30. //为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次
  31. if((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>downloadCount){
  32. downloadCount += 10;
  33. updateNotification.setLatestEventInfo(UpdateService.this, "正在下载", (int)totalSize*100/updateTotalSize+"%", updatePendingIntent);
  34. updateNotificationManager.notify(0, updateNotification);
  35. }
  36. }
  37. } finally {
  38. if(httpConnection != null) {
  39. httpConnection.disconnect();
  40. }
  41. if(is != null) {
  42. is.close();
  43. }
  44. if(fos != null) {
  45. fos.close();
  46. }
  47. }
  48. return totalSize;
  49. }
复制代码 显示下载进度,如图:

下载完成后,我们提示用户下载完成,并且可以点击安装,那么我们来补全前面的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 = newHandler(){
  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. updateNotification.defaults = Notification.DEFAULT_SOUND;//铃声提醒
  12. updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent);
  13. updateNotificationManager.notify(0, updateNotification);

  14. //停止服务
  15. stopService(updateIntent);
  16. case DOWNLOAD_FAIL:
  17. //下载失败
  18. updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent);
  19. updateNotificationManager.notify(0, updateNotification);
  20. default:
  21. stopService(updateIntent);
  22. }
  23. }
  24. };
复制代码 下载完成,如图:

至此,文件下载并且在通知栏通知进度。
发现本人废话很多,其实几句话的事情,来来回回写了这么多,啰嗦了,后面博文我会朝着精简方面努力。
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. }
复制代码 谢谢大家!!!!


更多相关文章

  1. android EditText设置不可写
  2. android 使用html5作布局文件: webview跟javascript交互
  3. android studio调试c/c++代码
  4. IM-A820L限制GSM,WCDMA上网的原理(其他泛泰机型可参考)7.13
  5. 使用NetBeans搭建Android开发环境
  6. 锁屏界面
  7. android studio Could not find com.android.support.constraint
  8. android(NDK+JNI)---Eclipse+CDT+gdb调试android ndk程序
  9. Android(安卓)version and Linux Kernel version

随机推荐

  1. Android 学习--ListView 的使用(三)
  2. Android仿QQ消息导航UI
  3. android 加下划线
  4. Android 自定义弹出框
  5. android 链式模式 责任链
  6. Android修改自定义Dialog的大小
  7. Android 判断手机的Rom类型
  8. Android 获取播放视频的相关 内容,  分
  9. android音量控制以及硬件同步
  10. Android调用自定义Dialog中的控件