OverView:
程序通过后台每天检查是否有最新版本,如果需要更新当前版本,将弹出对话框让用户选择是否在当前通过Market来更新软件。
Knowledge Points:
- SharedPreferences: 一个轻量级的存储方法,类似于经常使用的.ini文件,它也是通过检索关键字来取得相应的数值。之所以是成为轻量级,是因为它所能应用的数值类型有限,对于存储较大数值,效率相对较低。官方参考
- System.currentTimeMillis:将当前时间以毫秒作为单位来表示,用于比较两个时间的先后顺序。(其数值表示从1970-01-01 00:00:00直到当前时间的总毫秒数)官方参考
- 通过网络来读取信息:在checkUpdate()方法中包含了通过制定的URL来读取网络资源。具体操作步骤,请参考源代码。
- Runnable: 在其内部的Run()方法中实现所要执行的任何代码,当这个runnable interface被调用后可以视作为新的线程。
Source Code:
- public class hello extends Activity {
- /** Called when the activity is first created. */
- private Handler mHandler;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mHandler = new Handler();
- /* Get Last Update Time from Preferences */
- SharedPreferences prefs = getPreferences(0);
- long lastUpdateTime = prefs.getLong("lastUpdateTime", System.currentTimeMillis());
- int curVersion = 0;
- try {
- curVersion = getPackageManager().getPackageInfo("linhai.com.hello", 0).versionCode;
- } catch (NameNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Log.i("DEMO",String.valueOf(curVersion));
- /* Should Activity Check for Updates Now? */
- if ((lastUpdateTime + (24 * 60 * 60 * 1000)) < System.currentTimeMillis()) {
- /* Save current timestamp for next Check*/
- lastUpdateTime = System.currentTimeMillis();
- SharedPreferences.Editor editor = getPreferences(0).edit();
- editor.putLong("lastUpdateTime", lastUpdateTime);
- editor.commit();
- /* Start Update */
- // checkUpdate.start();
- }
- }
- /* This Thread checks for Updates in the Background */
- private Thread checkUpdate = new Thread()
- {
- public void run() {
- try {
- URL updateURL = new URL("http://my.company.com/update");
- URLConnection conn = updateURL.openConnection();