APP在设计中,肯定存在技术上的缺陷或未考虑完善的需求,不可能一下子做到完美。于是,就有了版本的更新,这也是平常手机使用中设置里常用的功能。怎么实现版本更新呢?大体分为三步:
1、去后台检查最新版本,查看当前版本是否是最新版本;
2、当前版本不是最新版本时,提示用户存在最新版本,是否需要升级到最新版本,当用户接受后下载新版本;
3、将下载的新版本保存到本地,并打开新版本,提示用户安装。
其实第一步的获取新版本很简单,就是与服务器的一个简单交互操作,得到最新版本号及Url,这里我主要分享下自己使用
AsyncHttpClient实现的后面两步。
在检查新版本确定要更新并得到用户确认后,使用
httpApi.downloadNewVersion(downloadNewVersionHandler,verUrl);下载新版本。
downloadNewVersion是与服务器交互的接口,downloadNewVersionHandler 是与服务器交互后的处理函数,verUrl是最新版本地址。
两个函数分别如下:
public void downloadNewVersion(BinaryHttpResponseHandler asyHandler,String verUrl) { String url = getAbsoluteUrl(verUrl); Logs.d("url: " + url + " verUrl: " + verUrl); getClient().get(url, asyHandler); }这个函数就是利用前面建立的连接,请求下载版本,服务器返回的结果由 downloadNewVersionHandler处理。
BinaryHttpResponseHandler downloadNewVersionHandler = new BinaryHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { Logs.d(TAG, "onSuccess "); httpApi.dismissDialog(); if(bytes == null){ Logs.e(TAG, "Can't download newest version apk."); return; } if(SDCardFileUtil.avaiableSDCard()){ try { File folder = new File(Constant.APK_FILE_PATH); if(!folder.exists()) folder.mkdirs(); fileName = Constant.APK_FILE_PATH + "OnLineLearning" + Util.newObjectId() + ".apk"; File file = new File(fileName); if(!file.exists()) file.createNewFile(); Logs.d(TAG, "download file: " + fileName); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bfw = new BufferedOutputStream(fos); bfw.write(bytes); bfw.flush(); fos.flush(); if(bfw != null) bfw.close(); if(fos != null) { fos.close(); } updateVersion(); Logs.d(TAG, "download file: " + fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else{ Logs.e(TAG, "SDCard isn't exist. "); } } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { Logs.d(TAG, "onFailure " + throwable.getMessage()); httpApi.dismissDialog(); } @Override public void onStart() { super.onStart(); httpApi.setDialogMessage(R.string.text_download_new_version); httpApi.showDialog(); } };
这个函数就是处理服务器下载的结果,保存到文件中。在保存文件中,进行了SD卡检查、目录及文件检查。文件目录定义在另一个文件中,如下:
/*项目目录*/ public static final String PROJECT_FOLDER_PATH = SDCardFileUtil .getSDCardRootPath() + File.separator + APP_NAME + File.separator; /*下载路径,用于存放下载的版本*/ public static final String APK_FILE_PATH = PROJECT_FOLDER_PATH + "download" + File.separator;
public void updateVersion(){ Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(fileName)) , "application/vnd.android.package-archive"); startActivity(intent); }
到此为止,用户就完成了新版本的更新及安装。
以上是本人的浅陋见解,不足之处,多多交流。