在开发过程,版本更新不可或缺的一个功能之一。主要通过VersionName或VersionCode值来判断版本是否需要更新,其整个更新的流程如下:
(1)访问服务器,获取服务器最新版本信息;
(2)比较服务器与客户端的版本信息;
(3)如版本信息不相符,提示用户更新;
(4)若用户选择更新,则下载更新文件;
(5)下载完毕,安装。
实现代码如下:
1)获取客户端的versionName和versionCode值
private String getInfo(int type) {
PackageInfo packageInfo = getPackageInfo();
if (packageInfo != null) {
switch (type) {
case 0:
return packageInfo.versionName;
case 1:
return String.valueOf(packageInfo.versionCode);
default:
break;
}
}
return null;
}
2)比较服务器与当前客户端的版本信息
private boolean isVersionEquals(String serviceVersion) {
return (getVersionName() != null && !versionName
.equalsIgnoreCase(serviceVersion));
}
3)调用版本更新函数
public void updateVersion(String downloadUrl, String path,
String serviceVersion) {
// 判断版本号是否相等
if (isVersionEquals(serviceVersion)) {
// 判断内存卡状态
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
savePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + path;
} else {
savePath = context.getFilesDir().toString() + path;
}
this.downloadUrl = downloadUrl;
showUpdateVersionDialog();
}
}
4)显示更新版本对话框
private void showUpdateVersionDialog() {
Builder builder = new AlertDialog.Builder(context);
builder.setTitle("软件版本更新")
.setMessage("检测服务器有新的版本,是否立即下载更新?")
.setPositiveButton("确定更新",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
showDownloadSoftwardDialog();
}
}).setNegativeButton("以后再说", null).create().show();
}
5)下载新的APK
private void downloadApk() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(downloadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.connect();
int length = httpURLConnection.getContentLength();
InputStream inputStream = httpURLConnection
.getInputStream();
File file = new File(savePath);
if (!file.exists()) {
file.mkdir();
}
saveFileName = savePath
+ "/"
+ downloadUrl.substring(
downloadUrl.lastIndexOf("/"),
downloadUrl.length());
File apkFile = new File(saveFileName);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
byte[] buffer = new byte[1024];
do {
int readNum = inputStream.read(buffer);
count += readNum;
downloadProgress = (int) (((float) count / length) * 100);
handler.sendEmptyMessage(DOWNLOAD_UPDATE);
if (readNum <= 0) {
handler.sendEmptyMessage(DOWNLOAD_OVER);
break;
}
fos.write(buffer, 0, readNum);
} while (cancelFlag);
fos.flush();
inputStream.close();
fos.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
6)安装APK
private void installApk() {
File apkFile = new File(saveFileName);
if (apkFile.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
"application/vnd.android.package-archive");
context.startActivity(intent);
updateFlag = true;
}
}