为程序添加版本自动更新功能 android

来源:互联网 发布:淘宝开源 编辑:程序博客网 时间:2024/04/30 02:32
程序通过后台每天检查是否有最新版本,如果需要更新当前版本,将弹出对话框让用户选择是否在当前通过Market来更新软件。

知识点:

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

Source Code:

1  package com.archfee.demo;
2  
3   import java.io.BufferedInputStream;
4   import java.io.InputStream;
5   import java.net.URL;
6   import java.net.URLConnection;
7   import org.apache.http.util.ByteArrayBuffer;
8   import android.app.Activity;
9   import android.app.AlertDialog;
10  import android.content.DialogInterface;
11  import android.content.Intent;
12  import android.content.SharedPreferences;
13  import android.net.Uri;
14  import android.os.Bundle;
15  import android.os.Handler;
16 
17  public class Test extends Activity {
18      private Handler mHandler;
19 
20      @Override
21      public void onCreate(Bundle savedInstanceState) {
22 
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.front);
25         mHandler = new Handler();
26         /* Get Last Update Time from Preferences */
27         SharedPreferences prefs = getPreferences(0);
28         long lastUpdateTime = prefs.getLong("lastUpdateTime",
29                 System.currentTimeMillis());
30         /* Should Activity Check for Updates Now? */
31         if ((lastUpdateTime + (24 * 60 * 60 * 1000)) < System
32                 .currentTimeMillis()) {
33             /* Save current timestamp for next Check */
34             lastUpdateTime = System.currentTimeMillis();
35             SharedPreferences.Editor editor = getPreferences(0).edit();
36             editor.putLong("lastUpdateTime", lastUpdateTime);
37             editor.commit();
38             /* Start Update */
39             checkUpdate.start();
40         }
41      }
42 
43      /* This Thread checks for Updates in the Background */
44      private Thread checkUpdate = new Thread() {
45 
46         public void run() {
47 
48             try {
49                 URL updateURL = new URL("http://my.company.com/update");
50                 URLConnection conn = updateURL.openConnection();
51                 InputStream is = conn.getInputStream();
52                 BufferedInputStream bis = new BufferedInputStream(is);
53                 ByteArrayBuffer baf = new ByteArrayBuffer(50);
54                 int current = 0;
55                 while ((current = bis.read()) != -1) {
56                     baf.append((byte) current);
57                 }
58                 /* Convert the Bytes read to a String. */
59                 final String s = new String(baf.toByteArray());
60                 /* Get current Version Number */
61                 int curVersion = getPackageManager().getPackageInfo(
62                         "your.app.id", 0).versionCode;
63                 int newVersion = Integer.valueOf(s);
64                 /* Is a higher version than the current already out? */
65                 if (newVersion > curVersion) {
66                     /* Post a Handler for the UI to pick up and open the Dialog */
67                     mHandler.post(showUpdate);
68                 }
69             } catch (Exception e) {
70             }
71         }
72      };
73 
74      /* This Runnable creates a Dialog and asks the user to open the Market */
75 
76      private Runnable showUpdate = new Runnable() {
77 
78         public void run() {
79 
80             new AlertDialog.Builder(Test.this)
81                     .setIcon(R.drawable.icon)
82                     .setTitle("Update Available")
83                     .setMessage(
84                            "An update for is available!nnOpen Android Market and see the details?")
85                     .setPositiveButton("Yes",
86                            new DialogInterface.OnClickListener() {
87 
88                                public void onClick(DialogInterface dialog,
89                                        int whichButton) {
90                                    /* User clicked OK so do some stuff */
91                                    Intent intent = new Intent(
92                                            Intent.ACTION_VIEW,
93                                            Uri.parse("market://search?q=pname:your.app.id"));
94                                    startActivity(intent);
95                                }
96                            })
97 
98                     .setNegativeButton("No",
99                            new DialogInterface.OnClickListener() {
100                               public void onClick(DialogInterface dialog,
101                                       int whichButton) {
102                                   /* User clicked Cancel */
103                               }
104                           })
105                    .show();
106        }
107     };
108 }
109

分为三个部分:

  • 置于onCreate()方法中的程序用于判断当前时间是否需要检查更新(如果距离上次更新时间大于1天,将启动检查更新)
  • 当以上条件满足时,启动checkUpdate来检查当前程序是否为最新版本。
  • 如果确定版本已过期,那么将登录market,并直接指向当前程序页面。
原创粉丝点击