步骤:

1.检測当前版本号的信息AndroidManifest.xml-->manifest-->android:versionName。

2.从server获取版本号号(版本号号存在于xml文件里)并与当前检測到的版本号进行匹配,假设不匹配,提示用户进行升级。假设匹配则进入程序主界面。

3.当提示用户进行版本号升级时。假设用户点击了确定,系统将自己主动从server上下载并进行自己主动升级,假设点击取消将进入程序主界面。

效果图:

   

  

获取当前程序的版本:

[java] view
plain
copy

  1. /*
  2. * 获取当前程序的版本
  3. */
  4. private String getVersionName() throws Exception{
  5. //获取packagemanager的实例
  6. PackageManager packageManager = getPackageManager();
  7. //getPackageName()是你当前类的包名,0代表是获取版本号信息
  8. PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
  9. return packInfo.versionName;
  10. }

获取server端的版本:

[java] view
plain
copy

  1. /*
  2. * 用pull解析器解析server返回的xml文件 (xml封装了版本)
  3. */
  4. public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{
  5. XmlPullParser  parser = Xml.newPullParser();
  6. parser.setInput(is, "utf-8");//设置解析的数据源
  7. int type = parser.getEventType();
  8. UpdataInfo info = new UpdataInfo();//实体
  9. while(type != XmlPullParser.END_DOCUMENT ){
  10. switch (type) {
  11. case XmlPullParser.START_TAG:
  12. if("version".equals(parser.getName())){
  13. info.setVersion(parser.nextText()); //获取版本
  14. }else if ("url".equals(parser.getName())){
  15. info.setUrl(parser.nextText()); //获取要升级的APK文件
  16. }else if ("description".equals(parser.getName())){
  17. info.setDescription(parser.nextText()); //获取该文件的信息
  18. }
  19. break;
  20. }
  21. type = parser.next();
  22. }
  23. return info;
  24. }

从server下载apk:

[java] view
plain
copy

  1. public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{
  2. //假设相等的话表示当前的sdcard挂载在手机上而且是可用的
  3. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  4. URL url = new URL(path);
  5. HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
  6. conn.setConnectTimeout(5000);
  7. //获取到文件的大小
  8. pd.setMax(conn.getContentLength());
  9. InputStream is = conn.getInputStream();
  10. File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
  11. FileOutputStream fos = new FileOutputStream(file);
  12. BufferedInputStream bis = new BufferedInputStream(is);
  13. byte[] buffer = new byte[1024];
  14. int len ;
  15. int total=0;
  16. while((len =bis.read(buffer))!=-1){
  17. fos.write(buffer, 0, len);
  18. total+= len;
  19. //获取当前下载量
  20. pd.setProgress(total);
  21. }
  22. fos.close();
  23. bis.close();
  24. is.close();
  25. return file;
  26. }
  27. else{
  28. return null;
  29. }
  30. }

匹配、下载、自己主动安装:

[java] view
plain
copy

  1. /*
  2. * 从server获取xml解析并进行比对版本
  3. */
  4. public class CheckVersionTask implements Runnable{
  5. public void run() {
  6. try {
  7. //从资源文件获取server 地址
  8. String path = getResources().getString(R.string.serverurl);
  9. //包装成url的对象
  10. URL url = new URL(path);
  11. HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
  12. conn.setConnectTimeout(5000);
  13. InputStream is =conn.getInputStream();
  14. info =  UpdataInfoParser.getUpdataInfo(is);
  15. if(info.getVersion().equals(versionname)){
  16. Log.i(TAG,"版本同样无需升级");
  17. LoginMain();
  18. }else{
  19. Log.i(TAG,"版本不同 ,提示用户升级 ");
  20. Message msg = new Message();
  21. msg.what = UPDATA_CLIENT;
  22. handler.sendMessage(msg);
  23. }
  24. } catch (Exception e) {
  25. // 待处理
  26. Message msg = new Message();
  27. msg.what = GET_UNDATAINFO_ERROR;
  28. handler.sendMessage(msg);
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33. Handler handler = new Handler(){
  34. @Override
  35. public void handleMessage(Message msg) {
  36. // TODO Auto-generated method stub
  37. super.handleMessage(msg);
  38. switch (msg.what) {
  39. case UPDATA_CLIENT:
  40. //对话框通知用户升级程序
  41. showUpdataDialog();
  42. break;
  43. case GET_UNDATAINFO_ERROR:
  44. //server超时
  45. Toast.makeText(getApplicationContext(), "获取server更新信息失败", 1).show();
  46. LoginMain();
  47. break;
  48. case DOWN_ERROR:
  49. //下载apk失败
  50. Toast.makeText(getApplicationContext(), "下载新版本号失败", 1).show();
  51. LoginMain();
  52. break;
  53. }
  54. }
  55. };
  56. /*
  57. *
  58. * 弹出对话框通知用户更新程序
  59. *
  60. * 弹出对话框的步骤:
  61. *  1.创建alertDialog的builder.
  62. *  2.要给builder设置属性, 对话框的内容,样式,button
  63. *  3.通过builder 创建一个对话框
  64. *  4.对话框show()出来
  65. */
  66. protected void showUpdataDialog() {
  67. AlertDialog.Builder builer = new Builder(this) ;
  68. builer.setTitle("版本号升级");
  69. builer.setMessage(info.getDescription());
  70. //当点确定button时从server上下载 新的apk 然后安装
  71. builer.setPositiveButton("确定", new OnClickListener() {
  72. public void onClick(DialogInterface dialog, int which) {
  73. Log.i(TAG,"下载apk,更新");
  74. downLoadApk();
  75. }
  76. });
  77. //当点取消button时进行登录
  78. builer.setNegativeButton("取消", new OnClickListener() {
  79. public void onClick(DialogInterface dialog, int which) {
  80. // TODO Auto-generated method stub
  81. LoginMain();
  82. }
  83. });
  84. AlertDialog dialog = builer.create();
  85. dialog.show();
  86. }
  87. /*
  88. * 从server中下载APK
  89. */
  90. protected void downLoadApk() {
  91. final ProgressDialog pd;    //进度条对话框
  92. pd = new  ProgressDialog(this);
  93. pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  94. pd.setMessage("正在下载更新");
  95. pd.show();
  96. new Thread(){
  97. @Override
  98. public void run() {
  99. try {
  100. File file = DownLoadManager.getFileFromServer(info.getUrl(), pd);
  101. sleep(3000);
  102. installApk(file);
  103. pd.dismiss(); //结束掉进度条对话框
  104. } catch (Exception e) {
  105. Message msg = new Message();
  106. msg.what = DOWN_ERROR;
  107. handler.sendMessage(msg);
  108. e.printStackTrace();
  109. }
  110. }}.start();
  111. }
  112. //安装apk
  113. protected void installApk(File file) {
  114. Intent intent = new Intent();
  115. //运行动作
  116. intent.setAction(Intent.ACTION_VIEW);
  117. //运行的数据类型
  118. intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
  119. startActivity(intent);
  120. }
  121. /*
  122. * 进入程序的主界面
  123. */
  124. private void LoginMain(){
  125. Intent intent = new Intent(this,MainActivity.class);
  126. startActivity(intent);
  127. //结束掉当前的activity
  128. this.finish();
  129. }

UpdataInfo:

[java] view
plain
copy

  1. public class UpdataInfo {
  2. private String version;
  3. private String url;
  4. private String description;
  5. public String getVersion() {
  6. return version;
  7. }
  8. public void setVersion(String version) {
  9. this.version = version;
  10. }
  11. public String getUrl() {
  12. return url;
  13. }
  14. public void setUrl(String url) {
  15. this.url = url;
  16. }
  17. public String getDescription() {
  18. return description;
  19. }
  20. public void setDescription(String description) {
  21. this.description = description;
  22. }
  23. }

update.xml:

[html] view
plain
copy

  1. <?

    xml version="1.0" encoding="utf-8"?>

  2. <info>
  3. <version>2.0</version>
  4. <url>http://192.168.1.187:8080/mobilesafe.apk</url>
  5. <description>检測到最新版本号,请及时更新!</description>
  6. </info>

最新文章

  1. 让 Generator 自启动
  2. 一句SQL实现获取自增列操作
  3. CSS3实现的超酷动态圆形悬浮效果
  4. android设置背景半透明效果
  5. Powerdesigner自定义DBMS(以derby数据库为例)
  6. [codeforces 293]A. Weird Game
  7. root密码
  8. java的Socket通信例子及关于java.net.SocketException: Socket is closed错误
  9. 【存储器相关】RAM、SRAM、SDRAM、ROM、EPROM、EEPROM、Flash存储器区别
  10. JNI学习总结
  11. 基于smarty+medoo手搭php简单的框架
  12. Eclipse:使用findBugs预先检测错误
  13. 使用WinInet实现HTTP站点访问
  14. 对象关系映射 ORM
  15. Java学习--抽象类和接口
  16. centos7下安装docker(22.docker swarm-----service)
  17. Ado.net和EF的区别
  18. PTA——数列求和
  19. Zookeeper C++编程实战之配置更新
  20. HTTP协议-MIME类型

热门文章

  1. 随时查看源码的网站---http://www.sooset.com/
  2. BZOJ1396: 识别子串(后缀自动机,线段树)
  3. spring基础内容
  4. Java Drp项目实战——Servlet
  5. Spring3拦截引发的问题——WEB开发中的client路径
  6. android:一个Open键引发的问题!!
  7. 删除online日志測试及ora-600 [4194]错误的处理
  8. C++静态库编译
  9. 83.#pragma详解
  10. 深拷贝&amp;浅拷贝