我正在开发一个应用程序来检查更新是否可用。问题是我的应用程序无法识别自己是最新版本。
我的服务器上有一个文件,该文件包含最新版本号 (1.0.1)。我的应用程序版本也是 1.0.1,但是当我检查更新时,我的应用程序表明有更新可用,文本显示最新和已安装的版本是 1.0.1。
所以这是我的代码:
(checkupdatebutton)
{
setContentView(R.layout.updater);
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httppost = new HttpGet("http://myserver.com/latestversion.txt");
HttpResponse response;
response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
TextView versionupdnew = (TextView)findViewById(R.id.versionupdnew);
//Set text to value of my file (latestversion.txt)
versionupdnew.setText(total);
TextView installedversion = (TextView)findViewById(R.id.versionupdcur);
installedversion.setText(R.string.version);
TextView title = (TextView)findViewById(R.id.title);
if(installedversion.equals(versionupdnew))
{
//Current version is latest
title.setText("No update needed!");
Button buttonUpdate = (Button)findViewById(R.id.buttonUpdate);
buttonUpdate.setEnabled(false);
}else{
title.setText("New version is available!");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
使用 SharedPreferences 存储最新版本,否则使用 R.string.version 将始终检查已安装的 apk 附带的版本,并且当下载新版本时,它不会更新此版本。
如果您将版本映射到整数,那将是最简单的,这样您就不需要解析版本字符串。每个新版本都会比上一个大 1。
// use preferences to get the current version, with default = 1
// (replace 1 with the version that came with the apk)
preferences.getInt("current_version", 1);
if (server_version > current_version) {
update();
preferences_editor.putInt("current_version", server_version).commit();
}
关于Android:检查更新是否可用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17383757/