我正在开发一个应用程序来检查更新是否可用。问题是我的应用程序无法识别自己是最新版本。

我的服务器上有一个文件,该文件包含最新版本号 (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/

    10-11 22:48
    查看更多