在開發過程,版本更新不可或缺的一個功能之一。主要通過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;
}
}