更新插件代码:https://github.com/shixy/UpdateApp

来源:http://aspoems.iteye.com/blog/1897300

检查更新的时候,通过指定的URL获取服务器端版本信息。比较版本,如果更新,访问服务器端返回的apk的URL地址,下载,安装。各种 Makert 也是通过类似的机制实现的。原理搞清楚了,代码就相当简单了。

获取apk的VesionName,即AndroidManifest.xml中定义的android:versionName

  1. public String getVesionName(Context context) {
  2. String versionName = null;
  3. try {
  4. versionName = context.getPackageManager().getPackageInfo("net.vpntunnel", 0).versionName;
  5. } catch (NameNotFoundException e) {
  6. Log.e(TAG, e.getMessage());
  7. }
  8. return versionName;
  9. }

复制代码

更新以及安装程序需要的权限,在AndroidManifest.xml中添加

  1. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  3. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
  4. <uses-permission android:name="android.permission.INSTALL_PACKAGES"></uses-permission>

复制代码

获取apk的versionCode,即AndroidManifest.xml中定义的android:versionCode

  1. public int getVersionCode(Context context) {
  2. int versionCode = 0;
  3. try {
  4. versionCode = context.getPackageManager().getPackageInfo("net.vpntunnel", 0).versionCode;
  5. } catch (NameNotFoundException e) {
  6. Log.e(TAG, e.getMessage());
  7. }
  8. return versionCode;
  9. }

复制代码

服务器端version.JSON,包含apk路径以及版本信息

  1. {
  2. "ApkName":"NAME",
  3. "ApkFullName":"NAME_1.0.5.apk",
  4. "VersionName":"1.0.5",
  5. "VersionCode":3
  6. }

复制代码

获取远程服务器的版本信息

  1. private void getRemoteJSON(string host) throws ClientProtocolException, IOException, JSONException {
  2. String url = String.format("http://%s/%s", host, VER_JSON);
  3. StringBuilder sb = new StringBuilder();
  4. HttpClient client = new DefaultHttpClient();
  5. HttpParams httpParams = client.getParams();
  6. HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
  7. HttpConnectionParams.setSoTimeout(httpParams, 5000);
  8. HttpResponse response = client.execute(new HttpGet(url));
  9. HttpEntity entity = response.getEntity();
  10. if (entity != null) {
  11. BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
  12. String line = null;
  13. while ((line = reader.readLine()) != null) {
  14. sb.append(line + "\n");
  15. }
  16. reader.close();
  17. }
  18. JSONObject object = (JSONObject) new JSONTokener(sb.toString()).nextValue();
  19. this.apkFullName = object.getString("ApkFullName");
  20. this.versionName = object.getString("VersionName");
  21. this.versionCode = Integer.valueOf(object.getInt("VersionCode"));
  22. }

复制代码

发现更新的提醒窗口,通过AlertDialog实现

  1. private void shoVersionUpdate(String newVersion, final String updateURL) {
  2. String message = String.format("%s: %s, %s", mContext.getString(R.string.found_newversion), newVersion, mContext.getString(R.string.need_update));
  3. AlertDialog dialog = new AlertDialog.Builder(mContext).setTitle(mContext.getString(R.string.alertdialog_title)).setMessage(message)
  4. // update
  5. .setPositiveButton(mContext.getString(R.string.alertdialog_update_button), new DialogInterface.OnClickListener() {
  6. @Override
  7. public void onClick(DialogInterface dialog, int which) {
  8. pBar = new ProgressDialog(mContext);
  9. pBar.setTitle(mContext.getString(R.string.progressdialog_title));
  10. pBar.setMessage(mContext.getString(R.string.progressdialog_message));
  11. pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  12. dialog.dismiss();
  13. downFile(updateURL);
  14. }
  15. // cancel
  16. }).setNegativeButton(mContext.getString(R.string.alertdialog_cancel_button), new DialogInterface.OnClickListener() {
  17. public void onClick(DialogInterface dialog, int whichButton) {
  18. dialog.dismiss();
  19. }
  20. }).create();
  21. dialog.show();
  22. }

复制代码

下载新版的apk文件,存放地址可以放到SD卡中。通过Environment.getExternalStorageDirectory()获取SD卡中的路径

  1. private void downFile(final String url) {
  2. pBar.show();
  3. new Thread() {
  4. public void run() {
  5. HttpClient client = new DefaultHttpClient();
  6. HttpGet get = new HttpGet(url);
  7. HttpResponse response;
  8. try {
  9. response = client.execute(get);
  10. HttpEntity entity = response.getEntity();
  11. long length = entity.getContentLength();
  12. InputStream is = entity.getContent();
  13. FileOutputStream fileOutputStream = null;
  14. if (is != null) {
  15. File f = new File(UPDATE_DIR);
  16. if (!f.exists()) {
  17. f.mkdirs();
  18. }
  19. fileOutputStream = new FileOutputStream(new File(UPDATE_DIR, updateFileName));
  20. byte[] buf = new byte[1024];
  21. int ch = -1;
  22. int count = 0;
  23. while ((ch = is.read(buf)) != -1) {
  24. fileOutputStream.write(buf, 0, ch);
  25. count += ch;
  26. Log.d(TAG, String.valueOf(count));
  27. if (length > 0) {
  28. }
  29. }
  30. }
  31. fileOutputStream.flush();
  32. if (fileOutputStream != null) {
  33. fileOutputStream.close();
  34. }
  35. handler.post(new Runnable() {
  36. public void run() {
  37. pBar.cancel();
  38. installUpdate();
  39. }
  40. });
  41. } catch (Exception e) {
  42. pBar.cancel();
  43. Log.e(TAG, e.getMessage());
  44. }
  45. }
  46. }.start();
  47. }

复制代码

安装更新

  1. private void installUpdate() {
  2. Intent intent = new Intent(Intent.ACTION_VIEW);
  3. intent.setDataAndType(Uri.fromFile(new File(UPDATE_DIR, updateFileName)), "application/vnd.android.package-archive");
  4. mContext.startActivity(intent);
  5. }

复制代码

至此更新需要函数就完成了

最新文章

  1. PHP ob_start() 函数介绍
  2. POJ3666Making the Grade[DP 离散化 LIS相关]
  3. Eclipse使用Maven构建web项目
  4. Unreal Engine4 学习笔记2 动画蒙太奇
  5. 编译升级php之路(5.5.7 到 5.5.37)
  6. LeetCode Binary Tree Right Side View (DFS/BFS)
  7. 切换两个activity
  8. ASP.NET WEB API 自定义模型校验过滤器
  9. windows 10 下使用 binwalk
  10. bat自动打包压缩实现
  11. JFinal开发环境搭建,JFinal开发案例
  12. 图解从 URL 到网页通信原理
  13. Java使用RabbitMQ之消息确认(confirm模板)
  14. 基于AD5663的UV灯电压控制
  15. python -- 初始函数 函数的定义,函数的返回值以及函数的参数
  16. Oracle下select语句
  17. Linux进程间通信—信号
  18. Linq的使用 &lt;一&gt;
  19. 08_Spring自定义标签
  20. 【vs2013】如何在VS的MFC中配置使用GDI+?

热门文章

  1. 字符串问题之 去掉字符串中连续出现K个0的子串
  2. AJAX跨域资源共享 CORS 详解
  3. HDU 4004 The Frog&#39;s Games(2011年大连网络赛 D 二分+贪心)
  4. Ubuntu 16.04 安装 RabbitMQ
  5. js适配器模式
  6. 5.3 Razor语法基础
  7. Android环境配好的标志
  8. java 简单解析wsdl
  9. IE跨Iframe时Session丢失问题
  10. LeetCode OJ:Combinations (排列组合)