Android应用版本更新
原理都是请求服务器端的数据,返回XML文件内容或者JSON内容数据
本人是用的方法是在服务器端建立一张APKVersion表
每当APKVersion经过修改之后,都会在在Version表中插入一条数据,并上传APK附件
现在看手机客户端获取应用版本信息代码
/**
* 提取当前应用版本信息
* @return
*/
public APKVersion getLocalVersion() {
String packageName = getPackageName();
PackageManager manager = getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(packageName, 0);
int versionCode = info.versionCode;
String versionName = info.versionName;
APKVersion version = new APKVersion(versionCode, versionName);
return version;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
获取服务器端最新版本信息代码
/**
* 应用版本检测
* @param bool 出错是否进行提示
*/
public void invokeLastVersion(final boolean bool) {
final APKVersion localVersion = getLocalVersion();
new Thread(new Runnable() {
@Override
public void run() {
String methodName = "getLastVersion";
String namespace = new GlobalConfigUtil(BaseActivity.this).getNamespace();
String webServiceURL = new GlobalConfigUtil(BaseActivity.this).getWebUrl();
Object obj = Ksoap2Util.invokeWebService(namespace, methodName, webServiceURL);
if (obj != null) {
Message msg = new Message();
Bundle data = new Bundle();
data.putBoolean("bool", bool);
if (GlobalConfigUtil.WEBERROR.equals(obj.toString())) {
} else {
APKVersion lastVersion = GsonUtils
.convertToEntity(obj.toString(),
APKVersion.class);
data.putSerializable("localVersion", localVersion);
data.putSerializable("lastVersion", lastVersion);
}
msg.setData(data);
versionHandler.sendMessage(msg);
}
}
}).start();
}
版本比对后下载服务器端APK资源
/**
* 根据网络路径下载文件
* @param webUrl
* @return
*/
public static int download(String webUrl) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(getInputStream(webUrl));
out = new BufferedOutputStream(new FileOutputStream(getFile(webUrl)));
byte[] buffer = new byte[1024];
int i = 0;
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i);
}
out.flush();
return 0;
} catch (IOException e) {
e.printStackTrace();
return -1;
} finally {
IOUtils.freeResource(in, out);
}
}
/**
* 获取网络文本文件数据流
* @param webUrl 网络文本文件路径
* @return
* @throws IOException
*/
public static InputStream getInputStream(String webUrl) throws IOException {
URL url = new URL(webUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
return connection.getInputStream();
}
/**
* 安装APK操作
* @param file
*/
public void installAPK(File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
如此就完成了检测服务器端的Version、Download、Install等过程
个人喜欢将下载过程放到Services中。