Android 自动检测版本升级

本文介绍了一种在Android应用中实现自动检测版本升级的方法。通过比较客户端与服务器端的版本号,判断是否需要升级。当发现新版本时,会弹窗提示用户并提供更新选项。此外,还详细介绍了如何通过自定义服务类实现后台下载新版本。
Android 自动检测版本升级

首先看一个文件manifest文件.

  1. <manifest xmlns:Android="http://schemas.android.com/apk/res/android"
  2.     package="com.jj.upgrade"
  3.     android:versionCode="1"
  4.     android:versionName="1.0" >

我们可以很清楚的看到versionCode和versionName,我们一般用versionCode来实现,

 

实现原理很简单:服务器端有个serverVersion,我们本地有个localVersion.服务器端serverVersion>localVersion,这个时候我们就需要进行升级版本.原理大致就是这样。具体实现请看下面.

  1. package com.jj.upgrade;
  2. import com.jj.Service.UpdateService;
  3. import Android.app.AlertDialog;
  4. import Android.app.Application;
  5. import Android.content.DialogInterface;
  6. import Android.content.Intent;
  7. import Android.content.pm.PackageInfo;
  8. import Android.content.pm.PackageManager.NameNotFoundException;
  9. /***
  10.  * MyApplication
  11.  * 
  12.  * @author zhangjia
  13.  * 
  14.  */
  15. public class MyApplication extends Application {
  16.     public static int localVersion = 0;// 本地安装版本 
  17.     public static int serverVersion = 2;// 服务器版本 
  18.     public static String downloadDir = "jj/";// 安装目录 
  19.     @Override
  20.     public void onCreate() {
  21.         super.onCreate();
  22.         try {
  23.             PackageInfo packageInfo = getApplicationContext()
  24.                     .getPackageManager().getPackageInfo(getPackageName(), 0);
  25.             localVersion = packageInfo.versionCode;
  26.         } catch (NameNotFoundException e) {
  27.             e.printStackTrace();
  28.         }
  29.         /***
  30.          * 在这里写一个方法用于请求获取服务器端的serverVersion.
  31.          */
  32.     }
  33. }

我们一般把全局的东西放到application里面

  1. public class MainActivity extends Activity {
  2.     private MyApplication myApplication;
  3.     @Override
  4.     public void onCreate(Bundle savedInstanceState) {
  5.         super.onCreate(savedInstanceState);
  6.         setContentView(R.layout.main);
  7.         checkVersion();
  8.     }
  9.     /***
  10.      * 检查是否更新版本
  11.      */
  12.     public void checkVersion() {
  13.         myApplication = (MyApplication) getApplication();
  14.         if (myApplication.localVersion < myApplication.serverVersion) {
  15.             // 发现新版本,提示用户更新 
  16.             AlertDialog.Builder alert = new AlertDialog.Builder(this);
  17.             alert.setTitle("软件升级")
  18.                     .setMessage("发现新版本,建议立即更新使用.")
  19.                     .setPositiveButton("更新",
  20.                             new DialogInterface.OnClickListener() {
  21.                                 public void onClick(DialogInterface dialog,
  22.                                         int which) {
  23.                                     Intent updateIntent = new Intent(
  24.                                             MainActivity.this,
  25.                                             UpdateService.class);
  26.                                     updateIntent.putExtra(
  27.                                             "app_name",
  28.                                             getResources().getString(
  29.                                                     R.string.app_name));
  30.                                     startService(updateIntent);
  31.                                 }
  32.                             })
  33.                     .setNegativeButton("取消",
  34.                             new DialogInterface.OnClickListener() {
  35.                                 public void onClick(DialogInterface dialog,
  36.                                         int which) {
  37.                                     dialog.dismiss();
  38.                                 }
  39.                             });
  40.             alert.create().show();
  41.         }
  42.     }
  43. }

我们在运行应用的时候要checkVersion();进行检查版本是否要进行升级.

最主要的是UpdateService服务类,

  1. @Override
  2.     public int onStartCommand(Intent intent, int flags, int startId) {
  3.         app_name = intent.getStringExtra("app_name");
  4.         // 创建文件 
  5.         FileUtil.createFile(app_name);// 创建文件 
  6.         createNotification();// 首次创建 
  7.         createThread();// 线程下载 
  8.         return super.onStartCommand(intent, flags, startId);
  9.     }

创建路径及文件,这里就不介绍了,不明白了下载源码看.

首先我们先 看createNotification().这个方法:

  1. /***
  2.      * 创建通知栏
  3.      */
  4.     RemoteViews contentView;
  5.     public void createNotification() {
  6.         notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  7.         notification = new Notification();
  8.         notification.icon = R.drawable.ic_launcher;// 这个图标必须要设置,不然下面那个RemoteViews不起作用. 
  9.         // 这个参数是通知提示闪出来的值. 
  10.         notification.tickerText = "开始下载";
  11.         // 
  12.         // updateIntent = new Intent(this, MainActivity.class); 
  13.         // pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0); 
  14.         // 
  15.         // // 这里面的参数是通知栏view显示的内容 
  16.         // notification.setLatestEventInfo(this, app_name, "下载:0%", 
  17.         // pendingIntent); 
  18.         // 
  19.         // notificationManager.notify(notification_id, notification); 
  20.         /***
  21.          * 在这里我们用自定的view来显示Notification
  22.          */
  23.         contentView = new RemoteViews(getPackageName(),
  24.                 R.layout.notification_item);
  25.         contentView.setTextViewText(R.id.notificationTitle, "正在下载");
  26.         contentView.setTextViewText(R.id.notificationPercent, "0%");
  27.         contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
  28.         notification.contentView = contentView;
  29.         updateIntent = new Intent(this, MainActivity.class);
  30.         updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  31.         pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
  32.         notification.contentIntent = pendingIntent;
  33.         notificationManager.notify(notification_id, notification);
  34.     }

上面实现的也不难理解.(主要是初始化Notification,用于提醒用户开始下载)

 

接着我们要看createThread方法

  1. /***
  2.      * 开线程下载
  3.      */
  4.     public void createThread() {
  5.         /***
  6.          * 更新UI
  7.          */
  8.         final Handler handler = new Handler() {
  9.             @Override
  10.             public void handleMessage(Message msg) {
  11.                 switch (msg.what) {
  12.                 case DOWN_OK:
  13.                     // 下载完成,点击安装 
  14.                     Uri uri = Uri.fromFile(FileUtil.updateFile);
  15.                     Intent intent = new Intent(Intent.ACTION_VIEW);
  16.                     intent.setDataAndType(uri,
  17.                             "application/vnd.Android.package-archive");
  18.                     pendingIntent = PendingIntent.getActivity(
  19.                             UpdateService.this, 0, intent, 0);
  20.                     notification.setLatestEventInfo(UpdateService.this,
  21.                             app_name, "下载成功,点击安装", pendingIntent);
  22.                     notificationManager.notify(notification_id, notification);
  23.                     stopSelf();
  24.                     break;
  25.                 case DOWN_ERROR:
  26.                     notification.setLatestEventInfo(UpdateService.this,
  27.                             app_name, "下载失败", pendingIntent);
  28.                     break;
  29.                 default:
  30.                     stopSelf();
  31.                     break;
  32.                 }
  33.             }
  34.         };
  35.         final Message message = new Message();
  36.         new Thread(new Runnable() {
  37.             @Override
  38.             public void run() {
  39.                 try {
  40.                     long downloadSize = downloadUpdateFile(down_url,
  41.                             FileUtil.updateFile.toString());
  42.                     if (downloadSize > 0) {
  43.                         // 下载成功 
  44.                         message.what = DOWN_OK;
  45.                         handler.sendMessage(message);
  46.                     }
  47.                 } catch (Exception e) {
  48.                     e.printStackTrace();
  49.                     message.what = DOWN_ERROR;
  50.                     handler.sendMessage(message);
  51.                 }
  52.             }
  53.         }).start();
  54.     }

这个方法有点小多,不过我想大家都看的明白,我在这里简单说名一下:首先我们创建一个handler用于检测最后下载ok还是not ok.

 

下面我们开启了线程进行下载数据。

我们接着看downloadUpdateFile这个方法:

  1. /***
  2.      * 下载文件
  3.      * 
  4.      * @return
  5.      * @throws MalformedURLException
  6.      */
  7.     public long downloadUpdateFile(String down_url, String file)
  8.             throws Exception {
  9.         int down_step = 5;// 提示step 
  10.         int totalSize;// 文件总大小 
  11.         int downloadCount = 0;// 已经下载好的大小 
  12.         int updateCount = 0;// 已经上传的文件大小 
  13.         InputStream inputStream;
  14.         OutputStream outputStream;
  15.         URL url = new URL(down_url);
  16.         HttpURLConnection httpURLConnection = (HttpURLConnection) url
  17.                 .openConnection();
  18.         httpURLConnection.setConnectTimeout(TIMEOUT);
  19.         httpURLConnection.setReadTimeout(TIMEOUT);
  20.         // 获取下载文件的size 
  21.         totalSize = httpURLConnection.getContentLength();
  22.         if (httpURLConnection.getResponseCode() == 404) {
  23.             throw new Exception("fail!");
  24.         }
  25.         inputStream = httpURLConnection.getInputStream();
  26.         outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉 
  27.         byte buffer[] = new byte[1024];
  28.         int readsize = 0;
  29.         while ((readsize = inputStream.read(buffer)) != -1) {
  30.             outputStream.write(buffer, 0, readsize);
  31.             downloadCount += readsize;// 时时获取下载到的大小 
  32.             /**
  33.              * 每次增张5%
  34.              */
  35.             if (updateCount == 0
  36.                     || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
  37.                 updateCount += down_step;
  38.                 // 改变通知栏 
  39.                 // notification.setLatestEventInfo(this, "正在下载...", updateCount 
  40.                 // + "%" + "", pendingIntent); 
  41.                 contentView.setTextViewText(R.id.notificationPercent,
  42.                         updateCount + "%");
  43.                 contentView.setProgressBar(R.id.notificationProgress, 100,
  44.                         updateCount, false);
  45.                 // show_view 
  46.                 notificationManager.notify(notification_id, notification);
  47.             }
  48.         }
  49.         if (httpURLConnection != null) {
  50.             httpURLConnection.disconnect();
  51.         }
  52.         inputStream.close();
  53.         outputStream.close();
  54.         return downloadCount;
  55.     }

--原文http://www.linuxidc.com/Linux/2012-09/69774.htm--
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值