惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
V
Visual Studio Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Threatpost
TaoSecurity Blog
TaoSecurity Blog
Engineering at Meta
Engineering at Meta
T
Troy Hunt's Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
H
Heimdal Security Blog
Webroot Blog
Webroot Blog
A
About on SuperTechFans
S
Securelist
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题
P
Palo Alto Networks Blog
F
Fortinet All Blogs
Hacker News: Ask HN
Hacker News: Ask HN
WordPress大学
WordPress大学
W
WeLiveSecurity
N
Netflix TechBlog - Medium
博客园 - 叶小钗
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
G
GRAHAM CLULEY
Schneier on Security
Schneier on Security
博客园 - 聂微东
www.infosecurity-magazine.com
www.infosecurity-magazine.com
小众软件
小众软件
博客园 - 【当耐特】
有赞技术团队
有赞技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
A
Arctic Wolf
C
CXSECURITY Database RSS Feed - CXSecurity.com
Google DeepMind News
Google DeepMind News
Security Latest
Security Latest
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threat Research - Cisco Blogs
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Spread Privacy
Spread Privacy
罗磊的独立博客
The Hacker News
The Hacker News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
IT之家
IT之家
B
Blog
GbyAI
GbyAI
Hugging Face - Blog
Hugging Face - Blog
Google Online Security Blog
Google Online Security Blog
MongoDB | Blog
MongoDB | Blog

博客园 - 锐

Windows7 Server 2008 下安装Oracle 10g提示“程序异常终止,发生未知错误”的解决方法 Undefined exploded archive location 项目不能部署 linux下mysql5.5.19编译安装笔记【已验证】 CSS+DIV排版时容器内对象全部设置了float属性后容器不能自动适应高度的解决方案 php Smarty模板生成html文档的方法 - 锐 - 博客园 如何解决Firefox检测不到div高度问题 DD_belatedPNG,解决IE6不支持PNG绝佳方案 .net程序运行在无.net framework环境中 struts2 freemarker当中引进java 常量java静态方法 - 锐 简体-繁体互转换的一个JS - 锐 - 博客园 C#实现通过URL触发自己的程序 Tencent://Message/协议的实现原理 - 锐 - 博客园 国内三大免费流媒体WAP门户网站(视频类WAP网站) C#中RSA加密解密和签名与验证的实现 (转) C#读取CPUid,硬盘id,网卡Mac地址 Struts2.1.6使用小技巧 java -D参数简化加入多个jar MySQL Proxy 学习笔记(转) 用apache ab做web压力测试
Android应用自动更新功能的代码实现
· 2012-05-02 · via 博客园 - 锐

原文:http://blog.csdn.net/coolszy/article/details/7518345

由于Android项目开源所致,市面上出现了N多安卓软件市场。为了让我们开发的软件有更多的用户使用,我们需要向N多市场发布,软件升级后,我们也必须到安卓市场上进行更新,给我们增加了工作量。因此我们有必要给我们的Android应用增加自动更新的功能。

既然实现自动更新,我们首先必须让我们的应用知道是否存在新版本的软件,因此我们可以在自己的网站上放置配置文件,存放软件的版本信息:

  1. <update>  
  2.     <version>2</version>  
  3.     <name>baidu_xinwen_1.1.0</name>  
  4.     <url>http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk</url>  
  5. </update>  

在这里我使用的是XML文件,方便读取。由于XML文件内容比较少,因此可通过DOM方式进行文件的解析:

  1. public class ParseXmlService  
  2. {  
  3.     public HashMap<String, String> parseXml(InputStream inStream) throws Exception  
  4.     {  
  5.         HashMap<String, String> hashMap = new HashMap<String, String>();  
  6.           
  7.           
  8.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  9.           
  10.         DocumentBuilder builder = factory.newDocumentBuilder();  
  11.           
  12.         Document document = builder.parse(inStream);  
  13.           
  14.         Element root = document.getDocumentElement();  
  15.           
  16.         NodeList childNodes = root.getChildNodes();  
  17.         for (int j = 0; j < childNodes.getLength(); j++)  
  18.         {  
  19.               
  20.             Node childNode = (Node) childNodes.item(j);  
  21.             if (childNode.getNodeType() == Node.ELEMENT_NODE)  
  22.             {  
  23.                 Element childElement = (Element) childNode;  
  24.                   
  25.                 if ("version".equals(childElement.getNodeName()))  
  26.                 {  
  27.                     hashMap.put("version",childElement.getFirstChild().getNodeValue());  
  28.                 }  
  29.                   
  30.                 else if (("name".equals(childElement.getNodeName())))  
  31.                 {  
  32.                     hashMap.put("name",childElement.getFirstChild().getNodeValue());  
  33.                 }  
  34.                   
  35.                 else if (("url".equals(childElement.getNodeName())))  
  36.                 {  
  37.                     hashMap.put("url",childElement.getFirstChild().getNodeValue());  
  38.                 }  
  39.             }  
  40.         }  
  41.         return hashMap;  
  42.     }  
  43. }  

通过parseXml()方法,我们可以获取服务器上应用的版本、文件名以及下载地址。紧接着我们就需要获取到我们手机上应用的版本信息:

  1.  
  2.  
  3.  
  4.  
  5.  
  6.   
  7. private int getVersionCode(Context context)  
  8. {  
  9.     int versionCode = 0;  
  10.     try  
  11.     {  
  12.           
  13.         versionCode = context.getPackageManager().getPackageInfo("com.szy.update"0).versionCode;  
  14.     } catch (NameNotFoundException e)  
  15.     {  
  16.         e.printStackTrace();  
  17.     }  
  18.     return versionCode;  
  19. }  

通过该方法我们获取到的versionCode对应AndroidManifest.xml下android:versionCode。android:versionCode和android:versionName两个属性分别表示版本号,版本名称。versionCode是整数型,而versionName是字符串。由于versionName是给用户看的,不太容易比较大小,升级检查时,就可以检查versionCode。把获取到的手机上应用版本与服务器端的版本进行比较,应用就可以判断处是否需要更新软件。

处理流程


处理代码

  1. package com.szy.update;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.MalformedURLException;  
  9. import java.net.URL;  
  10. import java.util.HashMap;  
  11.   
  12. import android.app.AlertDialog;  
  13. import android.app.Dialog;  
  14. import android.app.AlertDialog.Builder;  
  15. import android.content.Context;  
  16. import android.content.DialogInterface;  
  17. import android.content.Intent;  
  18. import android.content.DialogInterface.OnClickListener;  
  19. import android.content.pm.PackageManager.NameNotFoundException;  
  20. import android.net.Uri;  
  21. import android.os.Environment;  
  22. import android.os.Handler;  
  23. import android.os.Message;  
  24. import android.view.LayoutInflater;  
  25. import android.view.View;  
  26. import android.widget.ProgressBar;  
  27. import android.widget.Toast;  
  28.   
  29.  
  30.  
  31.  
  32.  
  33.   
  34.   
  35. public class UpdateManager  
  36. {  
  37.       
  38.     private static final int DOWNLOAD = 1;  
  39.       
  40.     private static final int DOWNLOAD_FINISH = 2;  
  41.       
  42.     HashMap<String, String> mHashMap;  
  43.       
  44.     private String mSavePath;  
  45.       
  46.     private int progress;  
  47.       
  48.     private boolean cancelUpdate = false;  
  49.   
  50.     private Context mContext;  
  51.       
  52.     private ProgressBar mProgress;  
  53.     private Dialog mDownloadDialog;  
  54.   
  55.     private Handler mHandler = new Handler()  
  56.     {  
  57.         public void handleMessage(Message msg)  
  58.         {  
  59.             switch (msg.what)  
  60.             {  
  61.               
  62.             case DOWNLOAD:  
  63.                   
  64.                 mProgress.setProgress(progress);  
  65.                 break;  
  66.             case DOWNLOAD_FINISH:  
  67.                   
  68.                 installApk();  
  69.                 break;  
  70.             default:  
  71.                 break;  
  72.             }  
  73.         };  
  74.     };  
  75.   
  76.     public UpdateManager(Context context)  
  77.     {  
  78.         this.mContext = context;  
  79.     }  
  80.   
  81.      
  82.  
  83.   
  84.     public void checkUpdate()  
  85.     {  
  86.         if (isUpdate())  
  87.         {  
  88.               
  89.             showNoticeDialog();  
  90.         } else  
  91.         {  
  92.             Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();  
  93.         }  
  94.     }  
  95.   
  96.      
  97.  
  98.  
  99.  
  100.   
  101.     private boolean isUpdate()  
  102.     {  
  103.           
  104.         int versionCode = getVersionCode(mContext);  
  105.           
  106.         InputStream inStream = ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");  
  107.           
  108.         ParseXmlService service = new ParseXmlService();  
  109.         try  
  110.         {  
  111.             mHashMap = service.parseXml(inStream);  
  112.         } catch (Exception e)  
  113.         {  
  114.             e.printStackTrace();  
  115.         }  
  116.         if (null != mHashMap)  
  117.         {  
  118.             int serviceCode = Integer.valueOf(mHashMap.get("version"));  
  119.               
  120.             if (serviceCode > versionCode)  
  121.             {  
  122.                 return true;  
  123.             }  
  124.         }  
  125.         return false;  
  126.     }  
  127.   
  128.  
  129.  
  130.  
  131.  
  132.  
  133.   
  134. private int getVersionCode(Context context)  
  135. {  
  136.     int versionCode = 0;  
  137.     try  
  138.     {  
  139.           
  140.         versionCode = context.getPackageManager().getPackageInfo("com.szy.update"0).versionCode;  
  141.     } catch (NameNotFoundException e)  
  142.     {  
  143.         e.printStackTrace();  
  144.     }  
  145.     return versionCode;  
  146. }  
  147.   
  148.      
  149.  
  150.   
  151.     private void showNoticeDialog()  
  152.     {  
  153.           
  154.         AlertDialog.Builder builder = new Builder(mContext);  
  155.         builder.setTitle(R.string.soft_update_title);  
  156.         builder.setMessage(R.string.soft_update_info);  
  157.           
  158.         builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener()  
  159.         {  
  160.             @Override  
  161.             public void onClick(DialogInterface dialog, int which)  
  162.             {  
  163.                 dialog.dismiss();  
  164.                   
  165.                 showDownloadDialog();  
  166.             }  
  167.         });  
  168.           
  169.         builder.setNegativeButton(R.string.soft_update_later, new OnClickListener()  
  170.         {  
  171.             @Override  
  172.             public void onClick(DialogInterface dialog, int which)  
  173.             {  
  174.                 dialog.dismiss();  
  175.             }  
  176.         });  
  177.         Dialog noticeDialog = builder.create();  
  178.         noticeDialog.show();  
  179.     }  
  180.   
  181.      
  182.  
  183.   
  184.     private void showDownloadDialog()  
  185.     {  
  186.           
  187.         AlertDialog.Builder builder = new Builder(mContext);  
  188.         builder.setTitle(R.string.soft_updating);  
  189.           
  190.         final LayoutInflater inflater = LayoutInflater.from(mContext);  
  191.         View v = inflater.inflate(R.layout.softupdate_progress, null);  
  192.         mProgress = (ProgressBar) v.findViewById(R.id.update_progress);  
  193.         builder.setView(v);  
  194.           
  195.         builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener()  
  196.         {  
  197.             @Override  
  198.             public void onClick(DialogInterface dialog, int which)  
  199.             {  
  200.                 dialog.dismiss();  
  201.                   
  202.                 cancelUpdate = true;  
  203.             }  
  204.         });  
  205.         mDownloadDialog = builder.create();  
  206.         mDownloadDialog.show();  
  207.           
  208.         downloadApk();  
  209.     }  
  210.   
  211.      
  212.  
  213.   
  214.     private void downloadApk()  
  215.     {  
  216.           
  217.         new downloadApkThread().start();  
  218.     }  
  219.   
  220.      
  221.  
  222.  
  223.  
  224.  
  225.  
  226.   
  227.     private class downloadApkThread extends Thread  
  228.     {  
  229.         @Override  
  230.         public void run()  
  231.         {  
  232.             try  
  233.             {  
  234.                   
  235.                 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))  
  236.                 {  
  237.                       
  238.                     String sdpath = Environment.getExternalStorageDirectory() + "/";  
  239.                     mSavePath = sdpath + "download";  
  240.                     URL url = new URL(mHashMap.get("url"));  
  241.                       
  242.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  243.                     conn.connect();  
  244.                       
  245.                     int length = conn.getContentLength();  
  246.                       
  247.                     InputStream is = conn.getInputStream();  
  248.   
  249.                     File file = new File(mSavePath);  
  250.                       
  251.                     if (!file.exists())  
  252.                     {  
  253.                         file.mkdir();  
  254.                     }  
  255.                     File apkFile = new File(mSavePath, mHashMap.get("name"));  
  256.                     FileOutputStream fos = new FileOutputStream(apkFile);  
  257.                     int count = 0;  
  258.                       
  259.                     byte buf[] = new byte[1024];  
  260.                       
  261.                     do  
  262.                     {  
  263.                         int numread = is.read(buf);  
  264.                         count += numread;  
  265.                           
  266.                         progress = (int) (((float) count / length) * 100);  
  267.                           
  268.                         mHandler.sendEmptyMessage(DOWNLOAD);  
  269.                         if (numread <= 0)  
  270.                         {  
  271.                               
  272.                             mHandler.sendEmptyMessage(DOWNLOAD_FINISH);  
  273.                             break;  
  274.                         }  
  275.                           
  276.                         fos.write(buf, 0, numread);  
  277.                     } while (!cancelUpdate);  
  278.                     fos.close();  
  279.                     is.close();  
  280.                 }  
  281.             } catch (MalformedURLException e)  
  282.             {  
  283.                 e.printStackTrace();  
  284.             } catch (IOException e)  
  285.             {  
  286.                 e.printStackTrace();  
  287.             }  
  288.               
  289.             mDownloadDialog.dismiss();  
  290.         }  
  291.     };  
  292.   
  293.      
  294.  
  295.   
  296.     private void installApk()  
  297.     {  
  298.         File apkfile = new File(mSavePath, mHashMap.get("name"));  
  299.         if (!apkfile.exists())  
  300.         {  
  301.             return;  
  302.         }  
  303.           
  304.         Intent i = new Intent(Intent.ACTION_VIEW);  
  305.         i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");  
  306.         mContext.startActivity(i);  
  307.     }  
  308. }  

效果图

检查模拟器SDCARD是否存在下载文件: