一)先检查版本:
/**
* 检查更新*/
public void run() {
String updateUrl = context.getResources().getString(R.string.update_url);
try {
HttpResponseEntity hre = HTTP.get(updateUrl);
if (hre != null) {
if (hre.getHttpResponseCode() != 200) {
Log.e("UpdateVersion", "http error, code: " + hre.getHttpResponseCode());
throw new RuntimeException("Failed : HTTP error code : "
+ hre.getHttpResponseCode());
}
String result = StringUtil.byte2String(hre.getB());
JSONObject jo = new JSONObject(result);
JSONArray datas = jo.getJSONArray("data");
for (int i = 0; i < datas.length(); i++) {
JSONObject data = datas.getJSONObject(i);
int type = data.getInt("sysType");
if (Constants.VERSION_SYSTEM_TYPE == type) {
String downloadUrl = data.getString("url");
//获取当前程序版本号
int versionCode = context.getPackageManager().getPackageInfo(
"com.baidu.hrlms.android.activity", 0).versionCode;
int newVersion = data.getInt("version");
if (newVersion > versionCode) {
handler.sendMessage(handler.obtainMessage(
Constants.HANDLER_VERSION_UPDATE, downloadUrl));
} else {
handler.sendMessage(handler
.obtainMessage(Constants.HTTPCONNECTION_TIMEOUT));
}
}
}
}
} catch (Exception e) {
Log.e("UpdateVersion", "http error", e);
handler.sendMessage(handler.obtainMessage(Constants.HANDLER_HTTPSTATUS_ERROR));
}
try {
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(Constants.BASE_DIR_PATH);
if (!file.exists()) {
file.mkdir();
}
File ApkFile = new File(file, Constants.APK_NAME);
FileOutputStream fos = new FileOutputStream(ApkFile);
int count = 0;
byte buf[] = new byte[1024];
do {
int numread = is.read(buf);
count += numread;
int progress = (int)(((float)count / length) * 100);
// 更新进度
mHandler.sendMessage(mHandler.obtainMessage(
Constants.HANDLER_APK_DOWNLOAD_PROGRESS, progress));
if (numread <= 0) {
// 下载完成通知安装
mHandler.sendEmptyMessage(Constants.HANDLER_APK_DOWNLOAD_FINISH);
break;
}
fos.write(buf, 0, numread);
} while (true);
fos.close();
is.close();
} catch (IOException e) {
mHandler.sendEmptyMessage(Constants.HTTPCONNECTION_TIMEOUT);
Log.e(TAG, e.getMessage(), e);
}
三)安装新版本:
File file = new File(Constants.BASE_DIR_PATH,
Constants.APK_NAME);
protected void installApk(File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
context.startActivity(intent);
}