`
寻梦者
  • 浏览: 624988 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

android应用检测更新代码

阅读更多

JAVA代码:

UpdateManager.java

[java] view plaincopy
  1. package com.iteye.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.AlertDialog.Builder;  
  14. import android.app.Dialog;  
  15. import android.content.Context;  
  16. import android.content.DialogInterface;  
  17. import android.content.DialogInterface.OnClickListener;  
  18. import android.content.Intent;  
  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. import com.iteye.androidtoast.R;  
  30.   
  31. public class UpdateManager  
  32. {  
  33.     /* 下载中 */  
  34.     private static final int DOWNLOAD = 1;  
  35.     /* 下载结束 */  
  36.     private static final int DOWNLOAD_FINISH = 2;  
  37.     /* 保存解析的XML信息 */  
  38.     HashMap<String, String> mHashMap;  
  39.     /* 下载保存路径 */  
  40.     private String mSavePath;  
  41.     /* 记录进度条数量 */  
  42.     private int progress;  
  43.     /* 是否取消更新 */  
  44.     private boolean cancelUpdate = false;  
  45.   
  46.     private Context mContext;  
  47.     /* 更新进度条 */  
  48.     private ProgressBar mProgress;  
  49.     private Dialog mDownloadDialog;  
  50.   
  51.     private Handler mHandler = new Handler()  
  52.     {  
  53.         public void handleMessage(Message msg)  
  54.         {  
  55.             switch (msg.what)  
  56.             {  
  57.             // 正在下载  
  58.             case DOWNLOAD:  
  59.                 // 设置进度条位置  
  60.                 mProgress.setProgress(progress);  
  61.                 break;  
  62.             case DOWNLOAD_FINISH:  
  63.                 // 安装文件  
  64.                 installApk();  
  65.                 break;  
  66.             default:  
  67.                 break;  
  68.             }  
  69.         };  
  70.     };  
  71.   
  72.     public UpdateManager(Context context)  
  73.     {  
  74.         this.mContext = context;  
  75.     }  
  76.   
  77.     /** 
  78.      * 检测软件更新 
  79.      */  
  80.     public void checkUpdate()  
  81.     {  
  82.         if (isUpdate())  
  83.         {  
  84.             // 显示提示对话框  
  85.             showNoticeDialog();  
  86.         } else  
  87.         {  
  88.             Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();  
  89.         }  
  90.     }  
  91.   
  92.     /** 
  93.      * 检查软件是否有更新版本 
  94.      *  
  95.      * @return 
  96.      */  
  97.     private boolean isUpdate()  
  98.     {  
  99.         // 获取当前软件版本  
  100.         int versionCode = getVersionCode(mContext);  
  101.         // 把version.xml放到网络上,然后获取文件信息  
  102.         //InputStream inStream = ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");  
  103.         // 解析XML文件。 由于XML文件比较小,因此使用DOM方式进行解析  
  104.         ParseXmlService service = new ParseXmlService();  
  105.         try  
  106.         {  
  107.             String path = "http://192.168.1.146:8080/picweb/xml/version.xml";  
  108.             URL url = new URL(path);  
  109.             HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  110.             conn.setReadTimeout(5*1000);  
  111.             conn.setRequestMethod("GET");  
  112.             InputStream inStream = conn.getInputStream();  
  113.             mHashMap = service.parseXml(inStream);  
  114.         } catch (Exception e)  
  115.         {  
  116.             e.printStackTrace();  
  117.         }  
  118.         if (null != mHashMap)  
  119.         {  
  120.             int serviceCode = Integer.valueOf(mHashMap.get("version"));  
  121.             // 版本判断  
  122.             if (serviceCode > versionCode)  
  123.             {  
  124.                 return true;  
  125.             }  
  126.         }  
  127.         return false;  
  128.     }  
  129.   
  130.     /** 
  131.      * 获取软件版本号 
  132.      *  
  133.      * @param context 
  134.      * @return 
  135.      */  
  136.     private int getVersionCode(Context context)  
  137.     {  
  138.         int versionCode = 0;  
  139.         try  
  140.         {  
  141.             // 获取软件版本号,对应AndroidManifest.xml下android:versionCode  
  142.             versionCode = context.getPackageManager().getPackageInfo("com.iteye.androidtoast"0).versionCode;  
  143.         } catch (NameNotFoundException e)  
  144.         {  
  145.             e.printStackTrace();  
  146.         }  
  147.         return versionCode;  
  148.     }  
  149.   
  150.     /** 
  151.      * 显示软件更新对话框 
  152.      */  
  153.     private void showNoticeDialog()  
  154.     {  
  155.         // 构造对话框  
  156.         AlertDialog.Builder builder = new Builder(mContext);  
  157.         builder.setTitle(R.string.soft_update_title);  
  158.         builder.setMessage(R.string.soft_update_info);  
  159.         // 更新  
  160.         builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener()  
  161.         {  
  162.             @Override  
  163.             public void onClick(DialogInterface dialog, int which)  
  164.             {  
  165.                 dialog.dismiss();  
  166.                 // 显示下载对话框  
  167.                 showDownloadDialog();  
  168.             }  
  169.         });  
  170.         // 稍后更新  
  171.         builder.setNegativeButton(R.string.soft_update_later, new OnClickListener()  
  172.         {  
  173.             @Override  
  174.             public void onClick(DialogInterface dialog, int which)  
  175.             {  
  176.                 dialog.dismiss();  
  177.             }  
  178.         });  
  179.         Dialog noticeDialog = builder.create();  
  180.         noticeDialog.show();  
  181.     }  
  182.   
  183.     /** 
  184.      * 显示软件下载对话框 
  185.      */  
  186.     private void showDownloadDialog()  
  187.     {  
  188.         // 构造软件下载对话框  
  189.         AlertDialog.Builder builder = new Builder(mContext);  
  190.         builder.setTitle(R.string.soft_updating);  
  191.         // 给下载对话框增加进度条  
  192.         final LayoutInflater inflater = LayoutInflater.from(mContext);  
  193.         View v = inflater.inflate(R.layout.softupdate_progress, null);  
  194.         mProgress = (ProgressBar) v.findViewById(R.id.update_progress);  
  195.         builder.setView(v);  
  196.         // 取消更新  
  197.         builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener()  
  198.         {  
  199.             @Override  
  200.             public void onClick(DialogInterface dialog, int which)  
  201.             {  
  202.                 dialog.dismiss();  
  203.                 // 设置取消状态  
  204.                 cancelUpdate = true;  
  205.             }  
  206.         });  
  207.         mDownloadDialog = builder.create();  
  208.         mDownloadDialog.show();  
  209.         // 现在文件  
  210.         downloadApk();  
  211.     }  
  212.   
  213.     /** 
  214.      * 下载apk文件 
  215.      */  
  216.     private void downloadApk()  
  217.     {  
  218.         // 启动新线程下载软件  
  219.         new downloadApkThread().start();  
  220.     }  
  221.   
  222.     /** 
  223.      * 下载文件线程 
  224.      */  
  225.     private class downloadApkThread extends Thread  
  226.     {  
  227.         @Override  
  228.         public void run()  
  229.         {  
  230.             try  
  231.             {  
  232.                 // 判断SD卡是否存在,并且是否具有读写权限  
  233.                 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))  
  234.                 {  
  235.                     // 获得存储卡的路径  
  236.                     String sdpath = Environment.getExternalStorageDirectory() + "/";  
  237.                     mSavePath = sdpath + "download";  
  238.                     URL url = new URL(mHashMap.get("url"));  
  239.                     // 创建连接  
  240.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  241.                     conn.connect();  
  242.                     // 获取文件大小  
  243.                     int length = conn.getContentLength();  
  244.                     // 创建输入流  
  245.                     InputStream is = conn.getInputStream();  
  246.   
  247.                     File file = new File(mSavePath);  
  248.                     // 判断文件目录是否存在  
  249.                     if (!file.exists())  
  250.                     {  
  251.                         file.mkdir();  
  252.                     }  
  253.                     File apkFile = new File(mSavePath, mHashMap.get("name"));  
  254.                     FileOutputStream fos = new FileOutputStream(apkFile);  
  255.                     int count = 0;  
  256.                     // 缓存  
  257.                     byte buf[] = new byte[1024];  
  258.                     // 写入到文件中  
  259.                     do  
  260.                     {  
  261.                         int numread = is.read(buf);  
  262.                         count += numread;  
  263.                         // 计算进度条位置  
  264.                         progress = (int) (((float) count / length) * 100);  
  265.                         // 更新进度  
  266.                         mHandler.sendEmptyMessage(DOWNLOAD);  
  267.                         if (numread <= 0)  
  268.                         {  
  269.                             // 下载完成  
  270.                             mHandler.sendEmptyMessage(DOWNLOAD_FINISH);  
  271.                             break;  
  272.                         }  
  273.                         // 写入文件  
  274.                         fos.write(buf, 0, numread);  
  275.                     } while (!cancelUpdate);// 点击取消就停止下载.  
  276.                     fos.close();  
  277.                     is.close();  
  278.                 }  
  279.             } catch (MalformedURLException e)  
  280.             {  
  281.                 e.printStackTrace();  
  282.             } catch (IOException e)  
  283.             {  
  284.                 e.printStackTrace();  
  285.             }  
  286.             // 取消下载对话框显示  
  287.             mDownloadDialog.dismiss();  
  288.         }  
  289.     };  
  290.   
  291.     /** 
  292.      * 安装APK文件 
  293.      */  
  294.     private void installApk()  
  295.     {  
  296.         File apkfile = new File(mSavePath, mHashMap.get("name"));  
  297.         if (!apkfile.exists())  
  298.         {  
  299.             return;  
  300.         }  
  301.         // 通过Intent安装APK文件  
  302.         Intent i = new Intent(Intent.ACTION_VIEW);  
  303.         i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");  
  304.         mContext.startActivity(i);  
  305.     }  
  306. }  


ParseXmlService.java

 

[java] view plaincopy
  1. package com.iteye.update;  
  2.   
  3. import java.io.InputStream;  
  4. import java.util.HashMap;  
  5.   
  6. import javax.xml.parsers.DocumentBuilder;  
  7. import javax.xml.parsers.DocumentBuilderFactory;  
  8.   
  9. import org.w3c.dom.Document;  
  10. import org.w3c.dom.Element;  
  11. import org.w3c.dom.Node;  
  12. import org.w3c.dom.NodeList;  
  13.   
  14.   
  15. public class ParseXmlService  
  16. {  
  17.     public HashMap<String, String> parseXml(InputStream inStream) throws Exception  
  18.     {  
  19.         HashMap<String, String> hashMap = new HashMap<String, String>();  
  20.           
  21.         // 实例化一个文档构建器工厂  
  22.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  23.         // 通过文档构建器工厂获取一个文档构建器  
  24.         DocumentBuilder builder = factory.newDocumentBuilder();  
  25.         // 通过文档通过文档构建器构建一个文档实例  
  26.         Document document = builder.parse(inStream);  
  27.         //获取XML文件根节点  
  28.         Element root = document.getDocumentElement();  
  29.         //获得所有子节点  
  30.         NodeList childNodes = root.getChildNodes();  
  31.         for (int j = 0; j < childNodes.getLength(); j++)  
  32.         {  
  33.             //遍历子节点  
  34.             Node childNode = (Node) childNodes.item(j);  
  35.             if (childNode.getNodeType() == Node.ELEMENT_NODE)  
  36.             {  
  37.                 Element childElement = (Element) childNode;  
  38.                 //版本号  
  39.                 if ("version".equals(childElement.getNodeName()))  
  40.                 {  
  41.                     hashMap.put("version",childElement.getFirstChild().getNodeValue());  
  42.                 }  
  43.                 //软件名称  
  44.                 else if (("name".equals(childElement.getNodeName())))  
  45.                 {  
  46.                     hashMap.put("name",childElement.getFirstChild().getNodeValue());  
  47.                 }  
  48.                 //下载地址  
  49.                 else if (("url".equals(childElement.getNodeName())))  
  50.                 {  
  51.                     hashMap.put("url",childElement.getFirstChild().getNodeValue());  
  52.                 }  
  53.             }  
  54.         }  
  55.         return hashMap;  
  56.     }  
  57. }  

 

version.xml

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <update>  
  3.     <version>1</version>  
  4.     <name>baidu_xinwen_1.1.0</name>  
  5.     <url>http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk</url>  
  6. </update>   


测试代码:

[html] view plaincopy
  1. UpdateManager manager = new UpdateManager(MainTwoActivity.this);  
  2. // 检查软件更新  
  3. manager.checkUpdate();  

 

 

注:只需要把version.xml放到网上服务器去,更新版本时,到服务器把版本号和url修改一下就可以。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics