为程序添加版本自动更新功能(转+详细分析)

本文详细介绍了如何为Android应用程序添加自动更新功能。通过后台检查更新,如果检测到新版本,程序会弹出对话框让用户决定是否通过Market更新。主要涉及到SharedPreferences用于存储更新时间,System.currentTimeMillis用于比较时间,以及通过网络读取更新信息。当检测到新版本时,通过Intent打开Market进行更新。
摘要由CSDN通过智能技术生成

OverView:
程序通过后台每天检查是否有最新版本,如果需要更新当前版本,将弹出对话框让用户选择是否在当前通过Market来更新软件
Knowledge Points:

  • SharedPreferences: 一个轻量级的存储方法,类似于经常使用的.ini文件,它也是通过检索关键字来取得相应的数值。之所以是成为轻量级,是因为它所能应用的数值类型有限,对于存储较大数值,效率相对较低。官方参考
  • System.currentTimeMillis:将当前时间以毫秒作为单位来表示,用于比较两个时间的先后顺序。(其数值表示从1970-01-01 00:00:00直到当前时间的总毫秒数)官方参考
  • 通过网络来读取信息:在checkUpdate()方法中包含了通过制定的URL来读取网络资源。具体操作步骤,请参考源代码
  • Runnable: 在其内部的Run()方法中实现所要执行的任何代码,当这个runnable interface被调用后可以视作为新的线程。

Source Code:

  1. public class hello extends Activity  {
  2.         /** Called when the activity is first created. */
  3.         private Handler mHandler;
  4.          
  5.     @Override
  6.     public void onCreate(Bundle savedInstanceState) {
  7.         super.onCreate(savedInstanceState);
  8.         setContentView(R.layout.main);
  9.         
  10.         mHandler = new Handler();
  11.         /* Get Last Update Time from Preferences */
  12.         SharedPreferences prefs = getPreferences(0);
  13.         long lastUpdateTime =  prefs.getLong("lastUpdateTime", System.currentTimeMillis());
  14.         int curVersion = 0;
  15.                 try {
  16.                         curVersion = getPackageManager().getPackageInfo("linhai.com.hello", 0).versionCode;
  17.                 } catch (NameNotFoundException e) {
  18.                         // TODO Auto-generated catch block
  19.                         e.printStackTrace();
  20.                 }
  21.         Log.i("DEMO",String.valueOf(curVersion));
  22.         /* Should Activity Check for Updates Now? */
  23.         if ((lastUpdateTime + (24 * 60 * 60 * 1000)) < System.currentTimeMillis()) {
  24.             /* Save current timestamp for next Check*/
  25.            lastUpdateTime = System.currentTimeMillis();
  26.             SharedPreferences.Editor editor = getPreferences(0).edit();
  27.             editor.putLong("lastUpdateTime", lastUpdateTime);
  28.             editor.commit();      
  29.             /* Start Update */
  30.          //   checkUpdate.start();
  31.         }
  32.     }
  33.     /* This Thread checks for Updates in the Background */
  34.     private Thread checkUpdate = new Thread()
  35.     {
  36.         public void run() {
  37.             try {
  38.                 URL updateURL = new URL("http://my.company.com/update");
  39.                 URLConnection conn = updateURL.openConnection();
  40.              
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值