我所开发应用不是面向大众的应用,因此没法放到应用市场去让你们下载,而后经过应用市场更新.因此我必要作一个应用自动更新功能.可是不难,Thanks to下面这篇博客:java
Android应用自动更新功能的实现!!! android
若是你是之前没有作过此类功能,建议你先看上面的文章.而后再来看个人.由于我也是参考了上面的实现.安全
其实这个自动更新功能大致就是两个三个步骤:服务器
(1)检查更新网络
(2)下载更新app
(3)安装更新 ide
检查更新和下载更新其实能够算是一步.由于都比较简单,都是主要是下载.this
1) 当你有新的版本发布时,在一个位置放一个更新的文件.url
里面到少放有最新应用的版本号.而后你拿当前应用的版本号和服务器上的版本号对比,就知道要不要下载更新了.spa
2 ) 下载这个过程,对于Java来讲不是什么难事,由于Java提供了丰富的API.更况且Android内置了HttpClient可用.
3) 这个,安装过程,其实就是使用一个打开查看此下载文件的 Intent.
这时须要考虑的是文件下载后放到哪里,安全否.:
通常就是先检测SD卡.而后选择一个合适的目录.
private void checkUpdate() { RequestFileInfo requestFileInfo = new RequestFileInfo(); requestFileInfo.fileUrl = "http://www.waitab.com/demo/demo.apk"; String status = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(status)) { ToastUtils.showFailure(getApplicationContext(), "SDcard cannot use!"); return; } requestFileInfo.saveFilePath = Environment .getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); requestFileInfo.saveFileName = "DiTouchClient.apk"; showHorizontalFragmentDialog(R.string.title_wait, R.string.title_download_update); new DownlaodUpdateTask().execute(requestFileInfo); }
上面的进度条显示我已经封装好的了.showHorizontalFragmentDialog()
显然我使用了android-support-v4兼容包来使用Fragment的.
在进度条中有显示,下载文件大小,已经下载了多少.速度等信息.
因为涉及到网络操做.因此把这整个逻辑放在AsyncTask中.
代码以下:
private class DownlaodUpdateTask extends AsyncTask<RequestFileInfo, ProgressValue, BasicCallResult> { @Override protected BasicCallResult doInBackground(RequestFileInfo... params) { final RequestFileInfo req = params[0]; String apkFileName = ""; try { URL url = new URL(req.fileUrl); // throw MalformedURLException HttpURLConnection conn = (HttpURLConnection) url .openConnection();// throws IOException Log.i(TAG, "response code:" + conn.getResponseCode()); // 1检查网络链接性 if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) { return new BasicCallResult( "Can not connect to the update Server! ", false); } int length = conn.getContentLength(); double total = StringUtils.bytes2M(length); InputStream is = conn.getInputStream(); File path = new File(req.saveFilePath); if (!path.exists()) path.mkdir(); File apkFile = new File(req.saveFilePath, req.saveFileName); apkFileName = apkFile.getAbsolutePath(); FileOutputStream fos = new FileOutputStream(apkFile); ProgressValue progressValue = new ProgressValue(0, " downlaod…"); int count = 0; long startTime, endTime; byte buffer[] = new byte[1024]; do { startTime = System.currentTimeMillis(); int numread = is.read(buffer); endTime = System.currentTimeMillis(); count += numread; if (numread <= 0) { // publish end break; } fos.write(buffer, 0, numread); double kbPerSecond = Math .ceil((endTime - startTime) / 1000f); double current = StringUtils.bytes2M(count); progressValue.message = String.format( "%.2f M/%.2f M\t\t%.2fKb/S", total, current, kbPerSecond); progressValue.progress = (int) (((float) count / length) * DialogUtil.LONG_PROGRESS_MAX); publishProgress(progressValue); } while (true); fos.flush(); fos.close(); } catch (MalformedURLException e) { e.printStackTrace(); return new BasicCallResult("Wrong url! ", false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return new BasicCallResult("Error: " + e.getLocalizedMessage(), false); } BasicCallResult callResult = new BasicCallResult( "download finish!", true); callResult.result = apkFileName; return callResult; } @Override protected void onPostExecute(BasicCallResult result) { removeFragmentDialog(); if (result.ok) { installApk(result.result); } else { ToastUtils.showFailure(getApplicationContext(), result.message); } } @Override protected void onProgressUpdate(ProgressValue... values) { ProgressValue value = values[0]; updateProgressDialog(value); } } /** * 安装更新APK. * * @param fileUri */ private void installApk(String fileUri) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + fileUri), "application/vnd.android.package-archive"); startActivity(intent); this.finish(); }
PS:Java中传递或者返回多个值,我经常使用的办法就是将数据封装到一个对象中去.上面用到的一些封装对象以下:
传递多个值用对象是由于AsyncTask设计让你传递一个对象做为传递参数,因此传递对象也须要这样使用.
/** * 传递给android 设置进度条对象 * * @author banxi1988 * */ public final class ProgressValue { /** * 须要设置的进度 */ public int progress; /** * 提示信息 */ public String message; public ProgressValue(int progress, String message) { super(); this.progress = progress; this.message = message; } }
基本的调用返回对象:
public class BasicCallResult { public String message; public boolean ok; public String result; public BasicCallResult(String message, boolean ok) { super(); this.message = message; this.ok = ok; } }
传递下载相关信息..
public class RequestFileInfo { public String fileUrl; public String saveFilePath; public String saveFileName; }
今天更新到这里,有什么问题,请指出,谢谢.