Android编程实现应用自动更新、下载、安装的方法

2019-12-10 19:05:05刘景俊

或者在AndroidManifest中将android:versionName=”1.2.0″写成 android:versionName=”@string/app_versionName”,然后在values/strings.xml中添加对应 字符串,这样实现之后,就可以使用如下代码获得版本名称:

public static String getVerName(Context context) {
      String verName = context.getResources()
      .getText(R.string.app_versionName).toString();
      return verName;
}

同理,apk的应用名称可以这样获得:

public static String getAppName(Context context) {
      String verName = context.getResources()
      .getText(R.string.app_name).toString();
      return verName;
}

2. 流程框架

比较》下载》安装。

3. 版本检查

在服务端放置最新版本的apk文件,如:http://www.easck.com/> ver.json中的内容为:

[{"appname":"jtapp12","apkname":"jtapp-12-updateapksamples.apk","verName":1.0.1,"verCode":2}]

然后,在手机客户端上进行版本读取和检查:

private boolean getServerVer () {
  try {
    String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
        + Config.UPDATE_VERJSON);
    JSONArray array = new JSONArray(verjson);
    if (array.length() > 0) {
      JSONObject obj = array.getJSONObject(0);
      try {
        newVerCode = Integer.parseInt(obj.getString("verCode"));
        newVerName = obj.getString("verName");
      } catch (Exception e) {
        newVerCode = -1;
        newVerName = "";
        return false;
      }
    }
  } catch (Exception e) {
    Log.e(TAG, e.getMessage());
    return false;
  }
  return true;
}