public class Test extends Activity { private Handler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.front); mHandler = new Handler(); /** 获取最后一次更新时间并保存到 Preferences 中 **/ SharedPreferences prefs = getPreferences(0); lastUpdateTime = prefs.getLong("lastUpdateTime", 0); /** 查检是否更新 **/ if ((lastUpdateTime + (24 * 60 * 60 * 1000)) < System.currentTimeMillis()) { /** 保存时间以便下次更新**/ lastUpdateTime = System.currentTimeMillis(); SharedPreferences.Editor editor = getPreferences(0).edit(); editor.putLong("lastUpdateTime", lastUpdateTime); editor.commit(); /** 开始更新 **/ checkUpdate.start(); } } /** 该线程在后台检查更新 **/ private Thread checkUpdate = new Thread() { public void run() { try { URL updateURL = new URL("http://my.company.com/update"); URLConnection conn = updateURL.openConnection(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } /** 读取的字节转换为字符串. **/ final String s = new String(baf.toByteArray()); /** 获取当前版本号 **/ int curVersion = getPackageManager().getPackageInfo("your.app.id", 0).versionCode; int newVersion = Integer.valueOf(s); /** 对比版本号? **/ if (newVersion > curVersion) { /** 显示更新 **/ mHandler.post(showUpdate); } } catch (Exception e) { } } }; /** 该线打开市场下载应用 **/ private Runnable showUpdate = new Runnable(){ public void run(){ new AlertDialog.Builder(Test.this) .setIcon(R.drawable.icon) .setTitle("Update Available") .setMessage("An update for is available!\\n\\nOpen Android Market and see the details?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /** User clicked OK so do some stuff **/ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:your.app.id")); startActivity(intent); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /** User clicked Cancel **/ } }) .show(); } }; }